DEV Community

Cover image for Good practices for Gitflow - Buenas prácticas para Gitflow
difilippoagustin
difilippoagustin

Posted on • Updated on

Good practices for Gitflow - Buenas prácticas para Gitflow

This post is written in two languages, if you want to read it in English, then click here!

Este post está escrito en dos idiomas, si querés seguir leyendo en español, solo continuá.

En este post voy a dejar una serie de recomendaciones para cuando trabajemos con gitflow. A mí me han servido y espero que a ustedes también. Sin más preámbulos, empecemos!

Nombre de las ramas:

Nombrar las ramas acorde a la historia de usuario (de ahora en adelante HU), y a sus subtareas, por ejemplo:

Nombre de la HU:
1. HU-1234
Descripción:
Agregar un nuevo botón que sea capaz de descargar un archivo PDF
al hacerle clic

Subtareas:
1. Crear un nuevo botón
2. Agregar funcionalidad al botón creado
Enter fullscreen mode Exit fullscreen mode

Por lo que vamos a trabajar con las siguientes ramas:

  • HU-1234
  • HU-1234_crear-boton
  • HU-1234_agregar-funcionalidad-boton

Creamos la HU-1234 y de la misma sacamos una llamada HU-1234_crear-boton.

Entonces, hacemos el desarrollo de crear un nuevo botón sobre la rama HU-1234_crear-boton, cuando esté todo listo, la integramos a la principal de la HU, HU-1234.
Una vez hecho esto, creamos la rama correspondiente a la siguiente sub tarea, HU-1234_agregar-funcionalidad-boton, sacandolá desde la rama HU-1234 la cual ya tiene creado el botón y repetimos el proceso.

Cuando esté todo listo, la rama que se va a integrar al circuito sería la HU-1234.


Code review:

Consiste en, como su nombre lo indica, revisar el código de alguien más para poder mejorar como desarrolladores y detectar y evitar errores en el código.
Es por eso que siempre se recomienda hacer un code review.
Algunas cosas para tener en cuenta:

  • No sentirse ofendido por los comentarios recibidos.
  • Cerrar las discusiones abiertas que han sido solucionadas.
  • No deberías hacer una revisión de código de más de una hora.
  • No deberías hacer un code review de muchos cambios, se hace difícil hacer una buena revisión de código.
  • De ser posible, hacer el code review junto a la persona que lo desarrolló.

Hacer un squash de los commits:

Es necesario si queremos tener el historial de commits de nuestras ramas principales lo más limpio posible. Probablemente no queramos tener todos los mensajes de commits en estas ramas, solo nos importará tener un solo commit con la característica añadida o lo que fuere que se trabajó.

Supongamos que tenemos este merge request con estos commits
merge request sin squash
Entonces, luego de hacer un squash, el merge request nos quedaría así
merge request con squash

Cómo hacerlo en GitLab

Actualmente, esto puede hacerse con un simple clic.
Link a documentación GitLab

Cómo hacerlo en Github

Puede hacerse con par de clics
Link a documentación Github

Cómo hacerlo manualmente

Dejo un link a un post sobre cómo hacer un squash


Merge requests/Pull requests

Hay varios puntos que quiero tocar en esta sección.

MR/PR claros

Es muy importante que los MR/PR tengan un título y descripción clara de lo que se va a integrar, pueden tener texto, links, imágenes y todo lo que sea necesario para que las personas que van a hacer el code review entiendan de qué va el código y tenga contexto de qué se va a integrar.

No es lo mismo esto:
MR sin descripción

Que esto:
MR con descripción

MR/PR chicos:

No crear MR/PR con muchos archivos modificados, hace difícil la tarea de revisar el código, para ello la HU no debe ser muy extensa. Crear ramas para cada sub tarea ayuda a tener MR/PR más chicos y fáciles de revisar.

Pedir aprobación para integrar:

Pedir un proporcional de aprobaciones para integrar una rama. Si el equipo es de 5 desarrolladores, que por lo menos, 3 de ellos lo hayan aprobado para poder integrar. Recordar que mientras más personas participen, menor es el número de fallos que pueden integrarse.


Tener una lista de TO DO's:

¿TO DO's de qué? De las cosas a tener en cuenta a la hora de crear un MR/PR. Por ejemplo, los tests pasan, la aplicación funciona, no se están introduciendo nuevos errores, etc.
Esto sirve para dos cosas, hacerle saber a los demás del estado del MR/PR y hacernos recordar de las cosas que debemos hacer. Siempre debemos actualizar contra develop la rama que vamos a querer integrar, esta es una tarea sumamente sencilla, tan sencilla que a veces uno se olvida de hacerla.
Teniendo una lista de TO DO's como esta sería imposible olvidarnos de ello.

[x] Build correcto
[X] Sin errores en el código y en consola
[x] Integración con un proyecto correcta
[x] 70% de cobertura de tests
[x] Tests realizados
[x] Actualizado con develop
Enter fullscreen mode Exit fullscreen mode

Esta lista, iría como parte de la descripción del MR/PR.


Mantener actualizado el repositorio:

No dejar ramas ya integradas sin borrar. A medida de que las ramas se vayan integrando deben ser eliminadas, sino nos queda el repositorio "sucio", lleno de ramas que no son necesarias y solo molestan.


Pipelines:

Si es posible, implementarlos. Estos te permiten ejecutar un ciclo de tareas de manera automática al momento de, por ejemplo, hacer un MR/PR. Teniendo los pipelines correctos se pueden correr las tareas necesarias automáticamente, lo que da más seguridad a los desarrolladores que están realizando la revisión de código, ya que saben que los tests pasan, la cobertura de test es la indicada, el build de la aplicación se hace sin ningún problema, etc.


Mensajes de commits

Comenzar el commit con la finalidad del mismo, si se trabajó en un bug fix, que el commit comience con el texto 'fix:', si se trabajó en un nuevo feature, que comience 'feat:'.
A continuación dejo una tabla con la cuál te podés guiar:

feat:     Nueva funcionalidad añadida
fix:      Solución a un error
style:    Funcionalidad y actualizaciones relacionados a estilos
refactor: Refactorización de código
test:     Cualquier cosa relacionada a testing
docs:     Cualquier cosa relacionada a documentación
etc.
Enter fullscreen mode Exit fullscreen mode

El tiempo verbal y el idioma en el que se escriben depende de lo que decida el equipo, lo que sí hay que tener en cuenta, es que todos deben ser iguales. Con respecto al tiempo verbal, hay quienes prefieren describir qué se hizo en el commit, por ejemplo, 'feat: se añadió un nuevo botón' y otros (que es lo más recomendado) que prefieren decir qué va a pasar cuando se integre el commit, relacionandoló a una acción, un comando, por ejemplo, 'feat: agregar nuevo botón' ¿qué va a hacer el commit cuando se integre a una rama?, va a agregar un nuevo botón.
Por otro lado, a algunos les gusta agregar el número de la HU en el mensaje del commit, por ejemplo 'feat: HU-1234 - solucionar error en botón'. Esto nos permite saber rápidamente sobre qué HU se está trabajando.

Y vos, aplicabas algunas de éstas prácticas? Aplicás otras que no fueron mencionadas? Dejameló en los comentarios!





In this post I will give you some recommendations for when you work with gitflow. These have helped me and I hope that help you too. Without any more preambles, let's go!

Branches name:

Name branches according to user story (since now US), and its sub tasks, for example:

US name:
1. US-1234
Description:
Add a new button that it be available to download a PDF file
when you do click it

Sub tasks:
1. Create a new button
2. Add functionality to new button
Enter fullscreen mode Exit fullscreen mode

So we are going to work with followings branches:

  • US-1234
  • US-1234_create-button
  • US-1234_add-functionality-button

We create US-1234 and then we extract a new one called US-1234_create-button.

Then, we do development to create a new button in US-1234_create-button branch, when all is ready, we integrate it to the main branch related to US, US-1234.
Once done this, we create a branch related to the next sub task, US-1234_add-functionality-button, extracting it from US-1234 branch, which one has created the button and we repeat the process.

When all of this is ready, the branch that will be integrated into the flow would be US-1234.


Code review:

This consists in, as its name indicates, reviewing the code of someone for can be better developers and for detecting and avoiding mistakes in the code.
As for that, it is always recommended to do a code review.
Some things for consider:

  • Don't feel insulted because of the comments received.
  • Close the open discussions that have been resolved.
  • You shouldn't do a code review that takes more than 1 hour.
  • You shouldn't do a code review that has a lot of changes, it gets hard to do a good code review.
  • Is it posible, do the code review together with the person who developed the code.

Squash the commits:

This is necessary if we want to keep our history clean of changes of our main branches. Probably we don't want to have all commits messages in these branches, we will only care to have one commit with the new feature added or the task done.

Imagine that we have this merge request with this commits
merge request sin squash
So, after to do a squash, the merge request would be like this
merge request con squash

How to do this in GitLab

Actually, this can do it in a simple click
Link to GitLab documentation

How to do this in Github

This can do it in a couple of clicks
Link to Github documentation

How to do this manually

I give you a link about to how to squash


Merge requests/Pull requests

There are some points that I want to cover in this section.

Clear MR/PR

Is very important that the MR/PR have a clear title and description about the things that will be integrated, they can have text, links, images and everything that were necessary with the purpose of the people who will do the code review, understand the code and have context of what thing will be integrated.

This is not the same:
MR sin descripción

As this:
MR con descripción

Small MR/PR:

Don't create MR/PR with a lot of files modified, it do so hard to review the code, for it, the US doesn't be too large. Creating branches for each sub task helps you to have a smaller and easier to review MR/PR.

Ask for approbation for integrate:

Ask for a proportional of approbations for integrate a branch. If the team has 5 members, at least 3 of them had to approve it for integration. Remember, if more people take part, less is the number of mistakes that can be integrated.


Have a TO DO's list:

¿TO DO's of what? Of things to consider when you create a new MR/PR. For example, the tests are ok, the application works, there are not new errors introduced, etc.
This is useful because two things, let the others know about MR/PR state and allows us to remember things we have to do. Before creating MR/PR, we must update our branch with develop, this is a very easy task, so easy that sometimes you forget do it.
If we have a TO DO's list like this, it would be impossible to forget it.

- [x] Build OK
- [x] No errors in the code and console
- [x] Integration with external project
- [x] 70% of test coverage
- [x] Tests done
- [x] Updated with develop
Enter fullscreen mode Exit fullscreen mode

This list would be in the description of MR/PR.


Keep the repository clean:

Erase any integrated branches. As well as the branches are integrated, they must be deleted, otherwise you will get a "dirty" repository, with unnecessary branches whose only purpose is bothering.


Pipelines:

If it's possible, implement it. These allow you to run a cycle of tasks automatically when, for example, you perform an MR / PR. Having the correct pipelines we can run the necessary tasks automatically, it gives more security to developers who are doing the code review, because they know the tests work, the test coverage is correct, the application's build it's OK, etc.


Commits messages

Start the commit with the purpose of it, if we worked on a bug fix, then the commit must starts with the text 'fix:', if we worked on a new feature, it must starts with the text 'feat:'.
Next, I leave you a table with which you can orient yourself:

feat:     The new feature added
fix:      A bug fix
style:    Feature and updates related to styling
refactor: Refactoring of code
test:     Everything related to testing
docs:     Everything related to documentation
etc.
Enter fullscreen mode Exit fullscreen mode

The verbal tense and the language used depend on what the team decides, what you do have to bear in mind is, they must all be the same. About to the verbal tense, there are who prefer describe what they did it in the commit, for example, 'feat: added a new button' and others (that is the most recommended) that prefer say what will happen when the commit be integrated, relating it to an action, a command, for example, 'feat: add new button'. What will the commit do when be integrated to a branch? It adds a new button.
On the other hand, somebody likes to add the US number in the commit's message, for example 'feat: US-1234 - fix bug in button'. This allows us to know quickly in what US it is working.

And you, did you apply some of these practices? Are you applying another not mentioned here? Let me know in the comments!

PD: I hope that you understood, I don't have a very good English

Oldest comments (0)