Translated to Spanish the day38 file

This commit is contained in:
Manuel Vergara 2023-04-22 10:18:30 +02:00
parent e3a77adee1
commit 233f5a1f21

View File

@ -1,110 +1,110 @@
## Staging & Changing ## Puesta en marcha (Staging) y cambios de git
We have already covered some of the basics but putting things into a walkthrough makes it better for me to learn and understand how and why we are doing it this way. Before we get into any git-based services such as GitHub, git has its powers that we can take advantage of on our local workstation. Ya hemos cubierto algunos de los conceptos básicos, pero poner las cosas en un tutorial hace que sea mejor para aprender y entender cómo y por qué lo estamos haciendo de esta manera en concreto. Antes de entrar en cualquier servicio basado en git como GitHub, git tiene superpoderes para aprovechar en local.
We are going to take the project folder we created at the start of the git session and we are going to walk through some of the simple steps we can do with git. We created a folder on our local machine and we initialised it with the `git init` command Vamos a verlos seleccionando la carpeta del proyecto que creamos al inicio de la sesión de git y veremos algunos de los sencillos y potentes pasos que podemos hacer con git. Creamos una carpeta en nuestra máquina local y la inicializamos con el comando `git init`.
![](Images/Day38_Git1.png) ![](Images/Day38_Git1.png)
We can also see now that we have initialised the folder we have a hidden folder in our directory. También podemos ver que después de inicializar tenemos una carpeta oculta en nuestro directorio: `.git`.
![](Images/Day38_Git2.png) ![](Images/Day38_Git2.png)
This is where the details of the git repository are stored as well as the information regarding our branches and commits. Aquí es donde se almacenan los detalles del repositorio git así como la información relativa a nuestras ramas y commits. ¡Donde habita toda la magía de git!
### Staging Files ### Ficheros Staging
We then start working on our empty folder and maybe we add some source code on the first days of work. We create our readme.mdfile and we can see that file in the directory, next we check our `git status` and it knows about the new readme.mdfile but we have not committed the file yet. A continuación, empezamos a trabajar en nuestra carpeta vacía. Podemos añadir algo de código fuente de los primeros días de trabajo. Creamos nuestro fichero `readme.md` y comprobamos nuestro `git status`. Veremos el nuevo fichero `readme.md` pero sin confirmar todavía.
![](Images/Day38_Git3.png) ![](Images/Day38_Git3.png)
We can stage our readme.mdfile with the `git add README.md` command then we can see changes to be committed that we did not have before and a green new file. Con el comando `git add README.md` podremos ver en `git status` que el fichero está en verde, esto indica que tenemos los cambios preparados para confirmar.
![](Images/Day38_Git4.png) ![](Images/Day38_Git4.png)
Next up we want to commit this, our first commit or our first snapshot of our project. We can do this by using the `git commit -m "Meaningful message"` command so that we can easily see what has changed for each commit. Also, notice the yellow cross changes now to a green tick. This is something I have within my terminal with the theme I use, something we covered in the Linux section. A continuación vamos confirmar esto, que no quede pendiente, haremos nuestro primer commit o, visto de otra manera, la primera instantánea de nuestro proyecto. Esto lo hacemos con el comando `git commit -m "<Mensaje significativo>"` dejando un mensaje esclarecedor y conciso que describa los cambios que se incluyen a la rama. Además, observe que la cruz amarilla cambia ahora a una marca verde. Esto es algo que tengo dentro de mi terminal con el tema que uso, lo vimos en la sección de Linux.
![](Images/Day38_Git5.png) ![](Images/Day38_Git5.png)
### Committing Changes ### Confirmando cambios
We are going to most likely want to add more files or even change the files we have in our directory. We have already done our first commit above. But now we are going to add more details and more files. O como maldecimos algunos en español "comiteando que es gerundio". Lo más probable es que queramos añadir más archivos o incluso cambiar los archivos que tenemos en nuestro directorio. Ya hemos hecho nuestro primer commit, pero ahora vamos a añadir más y más y más.
We could repeat our process from before, create or edit our file > `git add .` to add all files to the staging area then `git commit -m "meaningful message"` and this would work just fine. But to be able to offer a meaningful message on commit of what has changed you might not want to write something out like `git commit -m "Well, I changed some code because it did not work and when I fixed that I also added something new to the readme.mdto ensure everyone knew about the user experience and then I made a tea."` I mean this would work as well although probably make it descriptive but the preferred way here is to add this with a text editor. Podríamos repetir nuestro proceso de antes, crear o editar nuestro archivo con `git add .` para añadir todos los archivos a la zona de preparación y luego `git commit -m "mensaje significativo"` y esto funcionaría sin problemas. Pero para ser capaz de ofrecer un mensaje significativo en el commit de lo que ha cambiado puede que no quieras escribir algo como `git commit -m "Bueno, he cambiado algo de código porque no funcionaba y cuando lo arreglé también añadí algo nuevo al readme.mdpara asegurarme de que todo el mundo conocía la experiencia de usuario y luego hice un té."` Quiero decir que esto funcionaría también aunque probablemente lo haría descriptivo pero la forma preferida aquí es añadir esto con un editor de texto.
If we run `git commit` after running `git add` it will open our default text editor which in my case here is nano. Here are the steps I took to add some changes to the file, ran `git status` to show what is and what is not staged. Then I used `git add` to add the file to the staging area, then ran `git commit` which opened nano. Si ejecutamos `git commit` después de ejecutar `git add` se abrirá nuestro editor de texto por defecto que en mi caso es nano. Estos son los pasos que seguí para añadir algunos cambios al archivo, ejecuté `git status` para mostrar lo que está y lo que no está preparado. Luego usé `git add` para agregar el archivo al área de staging, luego ejecuté `git commit` que abrió nano.
![](Images/Day38_Git6.png) ![](Images/Day38_Git6.png)
When nano opens you can then add your short and long description and then save the file. Cuando se abra nano puedes añadir tu descripción corta y larga y luego guardar el archivo.
![](Images/Day38_Git7.png) ![](Images/Day38_Git7.png)
### Committing Best Practices ### Mejores prácticas para el commit
There is a balance here between when to commit and commit often. We do not want to be waiting to be finished the project before committing, each commit should be meaningful and they also should not be coupled with non-relevant tasks with each other. If you have a bug fix and a typo make sure they are two separate commits as a best practice. Hay un equilibrio entre confirmar empaquetando cambios relacionados y confirmar a menudo. No queremos esperar a terminar un proyecto para nuestro primer commit y cada confirmación debe ser significativa. Tampoco debe estar asociada con tareas no relevantes entre sí. Si tienes una corrección de errores y un error tipográfico la mejor práctica es asegurarse de incluirlos en dos commits distintos. Así puedes abreviar y darle significado al mensaje del commit.
Make the commit message mean something. En términos de redacción, el equipo o tú mismo deberíais ceñiros a la misma redacción para cada confirmación. Por ejemplo, recomiendan que los mensajes comiencen con un verbo en infinitivo, como "añadir" o "eliminar". Esto ayuda a mantener la consistencia y a que los mensajes sean más fáciles de leer. En muchos proyectos se decide que sean en inglés. También se agradece la brevedad cuando repasas los logs de git 😅
In terms of wording, the team or yourself should be sticking to the same wording for each commit. ### Saltarse la zona de preparación
### Skipping the Staging Area ¿Tenemos que preparar siempre nuestros cambios antes de confirmarlos?
Do we always have to stage our changes before committing them? La respuesta es sí. Pero no lo veas como un handicap, es la manera de estar 100% seguro de que no vas a errar. Además, la práctica recomendada es evitar utilizar 'git add .' y en su lugar utilizar 'git add <file>' para añadir los cambios del archivo o archivos en concreto para ser más específico y asegurarte de que no estás añadiendo cambios que no quieres. ¿Conoces el dicho "Más vale prevenir que curar"? Pues eso.
The answer is yes but don't see this as a shortcut, you have to be sure 100% that you are not needing that snapshot to roll back to, it is a risky thing to do. También hay una forma de saltarse la zona de preparación y confirmar directamente con el comando `git commit -a -m "<Mensaje significativo>"`. Es útil cuando tienes un cambio pequeño y no quieres tener que pasar por el proceso de preparación y confirmación. Pero cuidadito, si tienes muchos cambios y no los has preparado, esto podría añadirlos todos a la confirmación.
![](Images/Day38_Git8.png) ![](Images/Day38_Git8.png)
### Removing Files ### Eliminación de archivos
What about removing files from our project, maybe we have another file in our directory that we have committed but now the project no longer needs or using it, as a best practice we should remove it. Qué pasa con la eliminación de archivos de nuestro proyecto, tal vez tenemos otro archivo en nuestro directorio que hemos confirmado, pero ahora el proyecto ya no lo necesita o utiliza, como una mejor práctica debemos eliminarlo.
Just because we remove the file from the directory, git is still aware of this file and we also need to remove it from the repository. You can see the workflow for this below. Sólo porque eliminamos el archivo del directorio, git todavía es consciente de este archivo y también tenemos que eliminarlo del repositorio. Puedes ver el flujo de trabajo para esto a continuación.
![](Images/Day38_Git9.png) ![](Images/Day38_Git9.png)
That could be a bit of a pain to either remember or have to deal with if you have a large project which has many moving files and folders. We can do this with one command with `git rm oldcode.ps1` Esto podría ser un poco molesto de recordar o tener que lidiar con ello si tienes un proyecto grande que tiene muchos archivos y carpetas en movimiento. Podemos hacer esto con un comando con `git rm oldcode.ps1`.
![](Images/Day38_Git10.png) ![](Images/Day38_Git10.png)
### Renaming or Moving Files ### Renombrar o Mover Archivos
Within our operating system, we can rename and move our files. We will no doubt need to do this from time to time with our projects. Similar to removing though there is a two-step process, we change our files on our OS and then we have to modify and make sure that the staging area or that the files are added correctly. Steps as follows: Dentro de nuestro sistema operativo podemos renombrar y mover nuestros archivos. Sin duda necesitaremos hacer esto de vez en cuando con nuestros proyectos. Similar a eliminar aunque hay un proceso de dos pasos, cambiamos nuestros archivos en nuestro sistema operativo y luego tenemos que modificar y asegurarnos de que la zona de montaje o que los archivos se añaden correctamente. Los pasos son los siguientes:
![](Images/Day38_Git11.png) ![](Images/Day38_Git11.png)
However, like removing files from the operating system and then the git repository we can perform this rename using a git command too. Sin embargo, al igual que eliminamos archivos del sistema operativo y luego del repositorio git podemos realizar este renombrado utilizando también un comando git.
![](Images/Day38_Git12.png) ![](Images/Day38_Git12.png)
### Ignoring Files ### Ignorando Archivos
We may have the requirement to ignore files or folders within our project that we might be using locally or that will be just wasted space if we were to share with the overall project, a good example of this could be logs. I also think using this for secrets that you do not want to be shared out in public or across teams. Podemos tener la necesidad de ignorar los archivos o carpetas dentro de nuestro proyecto que podríamos estar utilizando a nivel local o que sólo sería un desperdicio de espacio si tuviéramos que compartir con el proyecto en general, un buen ejemplo de esto podría ser registros. También creo que el uso de este para los secretos que no quieren ser compartidos en público o entre los equipos.
We can ignore files by adding folders or files to the `.gitignore` file in our project directory. Podemos ignorar archivos añadiendo carpetas o archivos al archivo `.gitignore` en el directorio de nuestro proyecto.
![](Images/Day38_Git13.png) ![](Images/Day38_Git13.png)
You can then open the `.gitignore` file and see that we have the logs/ directory present. But we could also add additional files and folders here to ignore. Podemos abrir el archivo `.gitignore` y ver que tenemos el directorio logs/ presente. Pero también podríamos añadir aquí archivos y carpetas adicionales para ignorar.
![](Images/Day38_Git14.png) ![](Images/Day38_Git14.png)
We can then see `git status` and then see what has happened. A continuación podemos ver `git status` y ver qué ha pasado.
![](Images/Day38_Git15.png) ![](Images/Day38_Git15.png)
There are also ways in which you might need to go back and ignore files and folders, maybe you did want to share the logs folder but then later realised that you didn't want to. You will have to use `git rm --cached ` to remove files and folders from the staging area if you have a previously tracked folder that you now want to ignore. También hay formas en las que podrías necesitar volver atrás e ignorar archivos y carpetas, quizás querías compartir la carpeta de logs pero luego te diste cuenta de que no querías hacerlo. Tendrás que usar `git rm --cached ` para eliminar archivos y carpetas del área de preparación si tienes una carpeta previamente rastreada que ahora quieres ignorar.
### Short Status ### Estado breve
We have been using `git status` a lot to understand what we have in our staging area and what we do not, it's a very comprehensive command with lots of detail. Most of the time you will just want to know what has been modified or what is new? We can use `git status -s` for a short status of this detail. I would usually set an alias on my system to just use `git status -s` vs the more detailed command. Hemos estado usando mucho `git status` para entender lo que tenemos en nuestra área de preparación y lo que no, es un comando muy completo con muchos detalles. La mayoría de las veces sólo querrás saber qué ha sido modificado o qué hay de nuevo. Podemos usar `git status -s` para un breve estado de este detalle. Yo normalmente establecería un alias en mi sistema para usar `git status -s` en lugar del comando más detallado.
![](Images/Day38_Git16.png) ![](Images/Day38_Git16.png)
In the post tomorrow we will continue to look through these short examples of these common git commands. En el post de mañana seguiremos viendo estos breves ejemplos de estos comandos comunes de git.
## Resources ## Recursos
- [What is Version Control?](https://www.youtube.com/watch?v=Yc8sCSeMhi4) - [What is Version Control?](https://www.youtube.com/watch?v=Yc8sCSeMhi4)
- [Types of Version Control System](https://www.youtube.com/watch?v=kr62e_n6QuQ) - [Types of Version Control System](https://www.youtube.com/watch?v=kr62e_n6QuQ)
@ -113,5 +113,13 @@ In the post tomorrow we will continue to look through these short examples of th
- [Git and GitHub for Beginners - Crash Course](https://www.youtube.com/watch?v=RGOj5yH7evk&t=8s) - [Git and GitHub for Beginners - Crash Course](https://www.youtube.com/watch?v=RGOj5yH7evk&t=8s)
- [Complete Git and GitHub Tutorial](https://www.youtube.com/watch?v=apGV9Kg7ics) - [Complete Git and GitHub Tutorial](https://www.youtube.com/watch?v=apGV9Kg7ics)
- [Git cheatsheet](https://www.atlassian.com/git/tutorials/atlassian-git-cheatsheet) - [Git cheatsheet](https://www.atlassian.com/git/tutorials/atlassian-git-cheatsheet)
- [En español] [Comandos Git](https://gitea.vergaracarmona.es/man-linux/comandos-git)
- [En español][Apuntes Curso de Git](https://vergaracarmona.es/wp-content/uploads/2022/10/Curso-git_vergaracarmona.es_.pdf) de [Juan Carlos Rubio](https://www.linkedin.com/in/juan-carlos-rubio-pineda/Curso-git_vergaracarmona-es).
- [En español] En los [apuntes](https://vergaracarmona.es/apuntes/) del traductor:
- ["Instalar git en ubuntu"](https://vergaracarmona.es/instalar-git-en-ubuntu/)
- ["Comandos de git"](https://vergaracarmona.es/comandos-de-git/)
- ["Estrategias de fusión en git: Ship / Show / Ask"](https://vergaracarmona.es/estrategias-bifurcacion-git-ship-show-ask/)
- ["Resolver conflictos en Git. Merge, Squash, Rebase o Pull"](https://vergaracarmona.es/merge-squash-rebase-pull/)
- ["Borrar commits de git: reset, rebase y cherry-pick"](https://vergaracarmona.es/reset-rebase-cherry-pick/)
See you on [Day 39](day39.md) Nos vemos en el [Día 39](day39.md).