Komorebi AI
Introducción a Git

Introduction to Git: Step by step.

Welcome to this useful guide that will help you to take your first steps in the unforgettable world of Git! Let 's start from the beginning! Before getting deeper in the topic, we would need to establish the basic concepts that will act as a light in the middle of our dark path.

Definition 1. A version control system, also known as source control , is a tool that will help us track and manage changes to software code.

Definition 1.1. A repository or ‘repo’ is a storage location for files, directories or any software package we would like to check and change.

Definition1.2. A change is a modification of a file.

Our starting point is a mental image that would probably be familiar to you:

track proyect history

To make clear the previous definitions, let’s see in detail two different types of working with them that will clarify the concept.

Centralized version control. 

The amazing ‘Book of chess, dice and tables’ , commissioned by Alfonso X of Castile, is located in the Royal Library in the monastery of San Lorenzo de El Escorial. If one day you feel like you would like to read it, it has to be in person. Start checking your flights to Spain! However, maybe one morning you just wake up with an intense feeling of studying the manuscript deeply without moving from home. You would need a scanned version of the most important chapters. Obviously, carrying the manuscript home or copying it all are not considerable options. If in a specific moment, the best chess player in the world or even Alfonso X decided to add new moves, then, it will be needed a permit or going to the library. The way of modifying new chess moves represents how centralized control versions from the XIII century works.

Distributed version control. 

Congratulations! You are a lucky person! Your favorite professor uploads all class notes in a well-organized platform. We all have access to Geometry lecture notes. You work on them, doodle, add graphs. You don't need to be in class to see the notes on the board, because you can have them downloaded (offline). Your teacher can't see the mathematical atrocities you write either because you haven't sent her your modifications yet (push/pull files). The typos have to be sent to the professor who will change the file, and students will not encounter an unnecessary minus sign again. Your wonderful professor is acting as a central repository, and in the described processes our protagonist is described : Git. A distributed version control system.

Now that we've got a handle on what Git is, you may be asking yourself a few different questions. Let 's start answering them.

1. Do I need to know any other terms before I start?

In addition to keeping in mind the definitions we have established as the foundation of our path, we should add a few more concepts to our vocabulary.

Definition 2. A historical record is the traceability of the file. It allows us to answer the questions: Who modified it? When? Why?

Definition 3.   A commit is the minimum unit of storage.

2. What are we using Git for?

Tomando el símil de la forma de trabajar de tu profesora favorita, podemos sacar algunas conclusiones sobre quién puede ser partícipe en el control de versiones.

Taking the analogy of your favorite professors’ way of working, we can draw some conclusions about who can be involved in version control. You can use it privately to manage the changes you make to your work. We can also use Git to collaborate with other people. For example, it allows us to synchronize all the collaborators on a project through a central repository. In this case the central/remote repository is called GitHub.

3. How do we work with file modifications?

To answer this question, we need to consider three identities in which we will be passing the files:

  • Your computer.
  • GitHub (central/remote repository).
  • A server.

4. 4. How do we interact with the central repository aka GitHub?

The first option we have is with the Git terminal:

Si trabajar sobre la terminal no está en tus aficiones, quizás te interesa usar un cliente gráfico, como podría ser RStudio o VSCode (un editor de código).

It is time to get down to work.

Now that the questions have been answered, it is time to get down to work and see how everything we have just mentioned works in practice, using VSCode in this case. Join me step by step and we will discover how all the terms we have just mentioned work.

Let's create a new repository in our GitHub account (to have one you just need an email :) ) from VSCode.

Paso 1. Log In en GitHub

Paso 2. Creamos un nuevo repositorio en nuestra cuenta.

Paso 3.  Queremos trabajar en local (es decir, queremos hacer todas las modificaciones desde nuestro ordenador o nuestro servidor local), necesitamos clonar nuestro repositorio. ¡Dibujar las flechas de nuestro esquema anterior!

Es hora de crear nuestro clon en VSCode. Aunque podemos usar los diferentes iconos, aquí usaremos la terminal, y usamos nuestra URL correspondiente en el modo SSH (para mayor seguridad).

¿Dónde encontrar la URL? 

¿Cómo clonar en VSCode desde la terminal?

Al iniciar nuestro repositorio desde cero, tenemos que añadir algún archivo para empezar. ¡No queremos trabajar con un conjunto vacío! Desde GitHub nos recomiendan crear un archivo README.md y realizar nuestro primer commit, es decir, ¡nuestro primer cambio registrado!

Toda esta información es lo que aparece en el interior de tu nuevo repositorio. Esa parte de código que parece que va a generar una bomba nuclear al ejecutar:

Podemos tener cierta desconfianza al ejecutar estas líneas en nuestra terminal. Descubramos una por una qué es lo que nos intentan decir.

				
					echo "# Unforgettable_Git >> README.md
				
			

En esta línea de código, creamos el  archivo README.md para convertir nuestro ahora conjunto vacío, en un repositorio con aspiraciones.

				
					git init
				
			

Al ejecutar, inicializamos nuestro repositorio.

				
					git add README.md
				
			

Añadimos en nuestro repositorio el archivo README.md que hemos creado.

				
					 git commit -m "first commit"
				
			

Nos interesa guardar nuestro primer cambio con un mensaje para que nos quede muy claro que este es nuestro "first commit" en el repositorio.

A partir de ahora es necesario indicar dónde se van a guardar todos los cambios que vamos haciendo. Para ello, creamos una rama o branch.

				
					git branch -M main
				
			

Esta es la rama principal que tendrá el registro de cambios almacenados (commits) . Por supuesto , podemos crear todas las ramas que queramos en las que añadiremos diferentes modificaciones. De momento no nos interesa para nuestros primeros pasos, pero es interesante observar la siguiente imagen para entender hasta dónde puede llegar la complejidad.

Además, de ponerle un bonito nombre a nuestro registro, cada vez que queramos trabajar en este repositorio copiar nuestro URL inicial para indicar dónde estamos trabajando sería tedioso, por eso vamos a ponerle un nombre original. Como el repositorio es el origen de nuestra aventura, le llamaremos ‘origin‘:

				
					git remote add origin git@github.com:Aliiciaa/Unforgettable_Git.git
				
			

Aparentemente parece que todo está listo. No obstante, simplemente hemos registrado nuestro cambio. ¿Cómo lo podemos ver en GitHub?

“ Por favor git, podrías añadir mis cambios a ‘origin‘ sin salirte de la rama principal ‘main’ “ – dijo un usuario a la terminal.

				
					git push origin
git push -u origin main
				
			
Si has seguido todos los pasos a la perfección, ¡ya podemos empezar a trabajar! Recuerda que hemos hecho nuestro primer repositorio, creado nuestro primer archivo, y lo mejor de todo, ya hemos hecho el primer commit y ha quedado registrado. Es más, si tuvieras curiosidad para ver cómo aparece en GitHub verás que puedes ver todas tus modificaciones y cuándo se hicieron. Ten cuidado con lo que registras porque tus errores más oscuros pueden quedar para la posteridad.

Hemos terminado con los pasos esenciales. Seguidamente, te pondrás a escribir código, y te interesará hacer un nuevo commit para dejar constancia de tus modificaciones. Para que puedas continuar usando Git y te conviertas en un experto, te mencionaré las últimas pinceladas que te ayudaran a  volar de manera independiente en el proceso.

  • Recuerda que a la hora de ‘hacer commit’ estamos registrando un cambio. Esto es, si perdemos nuestro trabajo en local, pero está registrado en GitHub siempre vamos a poder recuperarlo. ¡Qué alivio!
  • Puede que de momento solo estés trabajando en tus propios archivos, pero cuando colaboras con más gente, les interesa saber por qué te dedicaste a borrar su código o añadir algunas líneas más. Escribe un mensaje extenso dando los motivos de cambio cuando ‘hagas un commit’. Facilitarán la lectura a tus colaboradores.
  • En este momento, tanto cambio puede generar confusión en el camino. Anota estos comandos útiles para comprobar estos estados.
				
					git log
				
			

Permite ver los commits que hemos hecho en el repositorio.

				
					git status

				
			

Permite comprobar el estado de nuestro archivo. ¿Hemos registrado nuestras modificaciones? ¿Hemos cambiado algo? ¿Nos falta algún paso que se nos haya podido olvidar?

Estados de nuestros ficheros. Aunque de manera impulsiva queremos realizar más commits, tenemos que conocer los estados de los cambios y cómo quedan representados, para no perdernos en la emoción.

  1. Estado modificado : [directorio.git] Todo OK, todo listo y registrado en git.
  2. Estado preparado: [working directory] trabajando en local listo para registrar. Bienvenido al área de preparación, nos indica que ficheros de los modificados son los que vamos a hacer commit. Si está vacía, todo perfecto, y todo está limpio (‘clean’).
  3. Estado confirmado: [staging area] aquí se está esperando a subir y confirmar lo que hemos hecho para que esté en el repositorio central.

Si quieres estar al día de nuestras publicaciones síguenos en LinkedIn o visítanos en www.komorebi.a

Latest posts

IA & Tech

¿Automation vs. augmentation?

¿Cómo elegir entre automatizar o aumentar una tarea con la IA. La automatización implica que la IA haga el trabajo por nosotros, mientras que el

Leer más »