Merge pull request #403 from manuelver/feature/translateES-12

This commit is contained in:
Michael Cade 2023-05-06 20:31:27 +02:00 committed by GitHub
commit 546a15d340
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 524 additions and 471 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 642 KiB

View File

@ -1,138 +1,140 @@
## Installing & Configuring Git
## Instalación y configuración de Git
Git is an open source, cross-platform tool for version control. If you are like me, using Ubuntu or most Linux environments you might find that you already have git installed but we are going to run through the install and configuration.
Git es una herramienta multiplataforma de código abierto para el control de versiones. En la mayoría de entornos Linux viene instalado por defecto, pero de todas formas vamos a repasar la instalación y configuración.
Even if you already have git installed on your system it is also a good idea to make sure we are up to date.
Incluso si ya tienes git instalado en tu sistema es una buena idea asegurarse de que está actualizado.
### Installing Git
### Instalación de Git
As already mentioned Git is cross-platform, we will be running through Windows and Linux but you can find macOS also listed [here](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
Como ya se ha mencionado Git es multiplataforma, vamos a ver Windows y Linux, pero también puedes encontrar macOS en la lista de [descargas](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
For [Windows](https://git-scm.com/download/win) we can grab our installers from the official site.
Para [Windows](https://git-scm.com/download/win) podemos obtener nuestros instaladores desde el sitio oficial o también puedes usar `winget`, Windows Application Package Manager.
You could also use `winget` on your Windows machine, think of this as your Windows Application Package Manager.
Before we install anything let's see what version we have on our Windows Machine. Open a PowerShell window and run `git --version`
Antes de instalar nada vamos a ver qué versión tenemos en nuestra máquina Windows. Abre una ventana de PowerShell y ejecuta `git --version`.
![](Images/Day36_Git1.png)
We can also check our WSL Ubuntu version of Git as well.
También podemos comprobar nuestra versión en el [WSL](https://es.wikipedia.org/wiki/Subsistema_de_Windows_para_Linux) Ubuntu.
![](Images/Day36_Git2.png)
At the time of writing the latest Windows release is `2.35.1` so we have some updating to do there which I will run through. I expect the same for Linux.
En el momento de escribir esto la última versión de Windows es `2.35.1` por lo que tenemos que actualizarla. Lo mismo con Linux.
I went ahead and downloaded the latest installer and ran through the wizard and will document that here. The important thing to note is that git will uninstall previous versions before installing the latest.
Descargué el último instalador y ejecuté el asistente. Lo importante a tener en cuenta es que git desinstalará las versiones anteriores antes de instalar la última. Lo que significa que el proceso que se muestra a continuación es también el mismo proceso en su mayor parte como si estuviera instalando por primera vez.
Meaning that the process shown below is also the same process for the most part as if you were installing from no git.
It is a very simple installation. Once downloaded double click and get started. Read through the GNU license agreement. But remember this is free and open-source software.
Es una instalación muy sencilla. Una vez descargado haga doble clic y comience. Lea el acuerdo de licencia GNU. Pero recuerde que este es un software libre y de código abierto.
![](Images/Day36_Git3.png)
Now we can choose additional components that we would like to also install but also associate with git. On Windows, I always make sure I install Git Bash as this allows us to run bash scripts on Windows.
Ahora podemos elegir componentes adicionales que nos gustaría también instalar para asociar con git. En Windows, siempre me aseguro de instalar Git Bash ya que nos permite ejecutar scripts bash en Windows.
![](Images/Day36_Git4.png)
We can then choose which SSH Executable we wish to use. IN leave this as the bundled OpenSSH that you might have seen in the Linux section.
Podemos entonces elegir qué ejecutable SSH deseamos utilizar.
![](Images/Day36_Git5.png)
We then have experimental features that we may wish to enable, for me I don't need them so I don't enable them, you can always come back in through the installation and enable these later on.
Luego tenemos características experimentales que podemos habilitar, yo no las necesito así que no las habilito, siempre puedes volver a la instalación y habilitarlas más tarde.
![](Images/Day36_Git6.png)
Installation complete, we can now choose to open Git Bash and or the latest release notes.
Instalación completada, ahora podemos elegir abrir Git Bash y o las últimas notas de la versión.
![](Images/Day36_Git7.png)
The final check is to take a look in our PowerShell window at what version of git we have now.
La comprobación final es echar un vistazo en PowerShell la versión actual de git.
![](Images/Day36_Git8.png)
Super simple stuff and now we are on the latest version. On our Linux machine, we seemed to be a little behind so we can also walk through that update process.
Super simple y ahora estamos en la última versión.
I simply run the `sudo apt-get install git` command.
En nuestra máquina Linux el proceso de actualización resulta más directo ejecutando el comando `sudo apt-get install git`.
![](Images/Day36_Git9.png)
You could also run the following which will add the git repository for software installations.
También puedes añadir el repositorio git para las actualizaciones del software.
```
```shell
sudo add-apt-repository ppa:git-core/ppa -y
sudo apt-get update
sudo apt-get install git -y
sudo apt-get install git -yinstalaciones
git --version
```
### Configuring Git
### Configurando Git
When we first use git we have to define some settings,
Cuando usamos git por primera vez tenemos que definir algunas configuraciones,
- Name
- Email
- Default Editor
- Line Ending
- Nombre de usuario
- Correo electrónico
- Editor por defecto
- Fin de línea
This can be done at three levels
Esto se puede hacer en tres niveles
- System = All users
- Global = All repositories of the current user
- Local = The current repository
- Sistema = Todos los usuarios
- Global = Todos los repositorios del usuario actual
- Local = El repositorio actual
Example:
`git config --global user.name "Michael Cade"`
`git config --global user.email Michael.Cade@90DaysOfDevOPs.com"`
Depending on your Operating System will determine the default text editor. In my Ubuntu machine without setting the next command is using nano. The below command will change this to visual studio code.
Ejemplo:
```shell
git config --global user.name "Michael Cade"
git config --global user.email "Michael.Cade@90DaysOfDevOPs.com"
```
Dependiendo del sistema operativo se determinará el editor de texto por defecto. En Ubuntu sin configurar el siguiente comando está utilizando nano. El siguiente comando cambiará esto a visual studio code.
`git config --global core.editor "code --wait"`
```shell
git config --global core.editor "code --wait"
```
now if we want to be able to see all git configurations then we can use the following command.
Podemos ver todas las configuraciones de git con el siguiente comando.
`git config --global -e`
```shell
git config --global -e
```
![](Images/Day36_Git10.png)
On any machine this file will be named `.gitconfig` on my Windows machine you will find this in your user account directory.
En cualquier máquina este archivo se llamará `.gitconfig`. En Windows lo encontrarás en el directorio de la cuenta de usuario.
![](Images/Day36_Git11.png)
### Git Theory
### Teoría Git
I mentioned in the post yesterday that there were other version control types and we can split these down into two different types. One is Client Server and the other is Distributed.
Mencioné en el post de ayer que había otros tipos de control de versiones y podemos dividirlos en dos tipos diferentes. Los que son Cliente-Servidor y los que son Distribuidos.
### Client-Server Version Control
### Control de versiones Cliente-Servidor
Before git was around Client-Server was the defacto method for version control. An example of this would be [Apache Subversion](https://subversion.apache.org/) which is an open source version control system founded in 2000.
Antes de que existiera git, el tipo de Cliente-Servidor era el método de facto para el control de versiones. Un ejemplo de esto sería [Apache Subversion](https://subversion.apache.org/) que es un sistema de control de versiones de código abierto fundado en el año 2000.
In this model of Client-Server version control, the first step the developer downloads the source code and the actual files from the server. This doesn't remove the conflicts but it does remove the complexity of the conflicts and how to resolve them.
En este modelo de control de versiones Cliente-Servidor, el primer paso que da el desarrollador es descargar el código fuente y los archivos reales del servidor. Esto no elimina los conflictos, pero sí la complejidad de los conflictos y cómo resolverlos.
![](Images/Day36_Git12.png)
Now for example let's say we have two developers working on the same files and one wins the race and commits or uploads their file back to the server first with their new changes. When the second developer goes to update they have a conflict.
Ahora, por ejemplo, digamos que tenemos dos desarrolladores trabajando en los mismos archivos y uno gana la carrera y confirma o sube su archivo de nuevo al servidor en primer lugar con sus nuevos cambios. Cuando el segundo desarrollador va a actualizar tiene un conflicto.
![](Images/Day36_Git13.png)
So now the Dev needs to pull down the first devs code change next to their check and then commit once those conflicts have been settled.
Así que ahora el desarrollador tiene que tirar hacia abajo el primer cambio de código junto a su cheque y luego confirmar una vez que los conflictos se han resuelto.
![](Images/Day36_Git15.png)
### Distributed Version Control
### Control de versiones distribuido
Git is not the only distributed version control system. But it is very much the defacto.
Git no es el único sistema de control de versiones distribuido. Pero es en gran medida el defacto.
Some of the major benefits of Git are:
Algunos de los principales beneficios de Git son:
- Fast
- Smart
- Rápido
- Inteligente
- Flexible
- Safe & Secure
- Seguro
Unlike the Client-Server version control model, each developer downloads the source repository meaning everything. History of commits, all the branches etc.
A diferencia del modelo de control de versiones Cliente-Servidor, cada desarrollador descarga el repositorio fuente, es decir, todo. Historial de commits, todas las ramas, etc.
![](Images/Day36_Git16.png)
## Resources
## Recursos
- [What is Version Control?](https://www.youtube.com/watch?v=Yc8sCSeMhi4)
- [Types of Version Control System](https://www.youtube.com/watch?v=kr62e_n6QuQ)
@ -140,5 +142,13 @@ Unlike the Client-Server version control model, each developer downloads the sou
- [Git for Professionals Tutorial](https://www.youtube.com/watch?v=Uszj_k0DGsg)
- [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)
- [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 37](day37.md)
Nos vemos en el [Día 37](day37.md)

View File

@ -1,154 +1,161 @@
## Gitting to know Git
## Conociendo a Git
Apologies for the terrible puns in the title and throughout. I am surely not the first person to turn Git into a dad joke!
Pido disculpas por los terribles juegos de palabras del título (Título original: *Gitting to know Git*). Seguro que no soy la primera persona que convierte Git en un chiste de padres.
In the last two posts we learnt about version control systems, and some of the fundamental workflows of git as a version control system [Day 35](day35.md) Then we got git installed on our system, updated and configured. We also went a little deeper into the theory between the Client-Server version control system and Git which is a distributed version control system [Day 36](day36.md).
En los dos últimos posts aprendimos acerca de los sistemas de control de versiones, y algunos de los flujos de trabajo fundamentales de git ([Día 35](day35.md)). Luego conseguimos instalar git en nuestro sistema, actualizarlo y configurarlo. También vimos algo de la teoría entre los tipos de sistema de control de versiones Cliente-Servidor y los distribuidos en el [Día 36](day36.md).
Now we are going to run through some of the commands and use cases that we will all commonly see with git.
Ahora vamos a repasar algunos de los comandos y casos de uso habituales con git.
### Where to git help with git?
### Git ayuda con git
There are going to be times when you just cannot remember or just don't know the command you need to get things done with git. You are going to need help.
Habrá momentos en los que simplemente no recuerdes o no sepas el comando que necesitas para hacer algo con git. Necesitarás ayuda. Google o cualquier motor de búsqueda será probablemente tu primer puerto de escala cuando busques ayuda. (También las IAs)
Google or any search engine is likely to be your first port of call when searching for help.
Secondly, the next place is going to be the official git site and the documentation. [git-scm.com/docs](http://git-scm.com/docs) Here you will find not only a solid reference to all the commands available but also lots of different resources.
El siguiente lugar, sobretodo a modo de confirmación, va a ser el sitio oficial de git y la documentación: [git-scm.com/docs](http://git-scm.com/docs). Aquí no sólo encontrarás una referencia sólida de todos los comandos disponibles, sino también un montón de recursos diferentes.
![](Images/Day37_Git1.png)
We can also access this same documentation which is super useful if you are without connectivity from the terminal. If we chose the `git add` command for example we can run `git add --help` and we see below the manual.
También podemos acceder a esta misma documentación desde la terminal, lo cual es muy útil si trabajas sin conexión. Si elegimos el comando `git add` por ejemplo podemos ejecutar `git add --help` y veremos el manual concreto del subcomando.
![](Images/Day37_Git2.png)
We can also in the shell use `git add -h` which is going to give us a summary of the options we have available.
También podemos usar en la shell `git add -h` que nos va a dar un resumen de las opciones que tenemos disponibles.
![](Images/Day37_Git3.png)
### Myths surrounding Git
### Mitos en torno a Git
"Git has no access control" - You can empower a leader to maintain source code.
"Git no tiene control de acceso" - Puedes autorizar a quien quieras a mantener el código fuente.
"Git is too heavy" - Git can provide shallow repositories which means a reduced amount of history if you have large projects.
"Git es demasiado pesado" - Git puede proporcionar repositorios poco profundos, lo que significa una cantidad reducida de historial si tienes proyectos grandes.
### Real shortcomings
### Deficiencias reales
Not ideal for Binary files. Great for source code but not great for executable files or videos for example.
No es ideal para archivos binarios. Es ideal para código fuente, pero no para archivos ejecutables o vídeos, por ejemplo.
Git is not user-friendly, the fact that we have to spend time talking about commands and functions of the tool is probably a key sign of that.
Git no es fácil de aprender, el hecho de que tengamos que pasar tiempo hablando de comandos y funciones de la herramienta es probablemente una señal de ello. Sin embargo, en general, git es difícil de aprender pero fácil de usar.
Overall though, git is hard to learn but easy to use.
### El ecosistema git
### The git ecosystem
Quiero cubrir brevemente el ecosistema alrededor de git pero no profundizar en estas áreas, pero creo que es importante señalarlas aquí a un alto nivel.
I want to briefly cover the ecosystem around git but not deep dive into some of these areas but I think it's important to note these here at a high level.
Casi todas las herramientas de desarrollo modernas soportan Git.
Almost all modern development tools support Git.
- Developer tools - We have already mentioned visual studio code but you will find git plugins and integrations into sublime text and other text editors and IDEs.
- Team tools - Also mentioned around tools like Jenkins from a CI/CD point of view, Slack from a messaging framework and Jira for project management and issue tracking.
- Cloud Providers - All the large cloud providers support git, Microsoft Azure, Amazon AWS, and Google Cloud Platform.
- Git-Based services - Then we have GitHub, GitLab and BitBucket which we will cover in more detail later on. I have heard of these services as the social network for code!
- **Herramientas para desarrolladores** - Ya hemos mencionado visual studio code pero encontrarás plugins de git e integraciones en sublime text y otros editores de texto e IDEs.
- **Herramientas de equipo** - También se han mencionado herramientas como Jenkins desde un punto de vista de CI/CD, Slack desde un marco de mensajería y Jira para la gestión de proyectos y seguimiento de incidencias.
- **Proveedores de nube** - Todos los grandes proveedores de nube soportan git: Microsoft Azure, Amazon AWS y Google Cloud Platform.
- **Servicios basados en Git** - Luego tenemos GitHub, GitLab y BitBucket que cubriremos en más detalle más adelante. Estos servicios se conocen como las redes sociales del código.
### The Git Cheatsheet
We have not covered most of these commands but having looked at some cheat sheets available online I wanted to document some of the git commands and what their purpose is. We don't need to remember these all, and with more hands-on practice and use you will pick at least the git basics.
No hemos cubierto la mayoría de comandos de git, ya que tiene un amplio abanico de posibilidades, pero después de haber mirado algunas hojas de trucos disponibles en línea vamos a documentar algunos de ellos y su propósito. No necesitamos recordarlos todos, ya que a través de la práctica y el uso aprenderás al menos mucho más de git.
I have taken these from [atlassian](https://www.atlassian.com/git/tutorials/atlassian-git-cheatsheet) but writing them down and reading the description is a good way to get to know what the commands are as well as getting hands-on in everyday tasks.
Estos comandos se han sacado de [atlassian](https://www.atlassian.com/git/tutorials/atlassian-git-cheatsheet), escribirlos y leer la descripción es una buena forma de conocer su uso, así que manos a la obra en las tareas diarias:
### Git Basics
- [Conceptos básicos de Git](#conceptos-básicos-de-git)
- [Deshacer cambios Git](#deshacer-cambios-git)
- [Historial de reescritura de Git](#historial-de-reescritura-de-git)
- [Git Branches](#git-branches)
- [Repositorios remotos Git](#repositorios-remotos-git)
- [Git Diff](#git-diff)
- [Git Config](#git-config)
- [Git Rebase](#git-rebase)
- [Git Pull](#git-pull)
- [Git Reset](#git-reset)
- [Git Push](#git-push)
| Command | Example | Description |
| ------------- | --------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| git init | `git init <directory>` | Create an empty git repository in the specified directory. |
| git clone | `git clone <repo>` | Clone repository located at <repo> onto local machine. |
| git config | `git config user.name` | Define author name to be used for all commits in current repository `system`, `global`, `local` flag to set config options. |
| git add | `git add <directory>` | Stage all changes in <directory> for the next commit. We can also add <files> and <.> for everything. |
| git commit -m | `git commit -m "<message>"` | Commit the staged snapshot, use <message> to detail what is being committed. |
| git status | `git status` | List files that are staged, unstaged and untracked. |
| git log | `git log` | Display all commit history using the default format. There are additional options with this command. |
| git diff | `git diff` | Show unstaged changes between your index and working directory. |
### Conceptos básicos de Git
### Git Undoing Changes
| Comando | Ejemplo | Descripción |
| ------------- | --------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| git init | `git init <directory>` | Crea un repositorio git vacío en el directorio especificado. |
| git clone | `git clone <repo>` | Clona el repositorio ubicado en <repo> en la máquina local. |
| git config | `git config user.name` | Definir opciones que se usará para todos los commits según el entorno `system`, `global` o `local`. |
| git add | `git add <directory>` | Prepara los cambios en <directorio> para la próxima confirmación. También podemos añadir <ficheros> y <.> para todo. |
| git commit -m | `git commit -m "<message>"` | Confirmar la instantánea preparada, usando <mensaje> para detallar lo que se está confirmando. |
| git status | `git status` | Lista los archivos que están organizados, no organizados y sin seguimiento. |
| git log | `git log` | Muestra todo el historial de confirmaciones usando el formato por defecto. Hay opciones adicionales con este comando. |
| git diff | `git diff` | Muestra los cambios no organizados entre tu índice y el directorio de trabajo. |
| Command | Example | Description |
| ---------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| git revert | `git revert <commit>` | Create a new commit that undoes all of the changes made in <commit> then apply it to the current branch. |
| git reset | `git reset <file>` | Remove <file> from the staging area, but leave the working directory unchanged. This unstaged a file without overwriting any changes. |
| git clean | `git clean -n` | Shows which files would be removed from the working directory. Use `-f` in place of `-n` to execute the clean. |
### Deshacer cambios Git
### Git Rewriting History
| Comando | Ejemplo | Descripción |
| ---------- | --------------------- | ------------------------------------------------------------------------------------------------------------------ |
| git revert | `git revert <commit>` | Crear un nuevo commit que deshaga todos los cambios realizados en <commit> y aplicarlo a la rama actual. |
| git reset | `git reset <file>` | Elimina <fichero> del área de preparación dejando el directorio de trabajo sin cambios. |
| git clean | `git clean -n` | Muestra qué archivos se eliminarán del directorio de trabajo. Usa `-f` en lugar de `-n` para ejecutar la limpieza. |
| Command | Example | Description |
| ---------- | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| git commit | `git commit --amend` | Replace the last commit with the staged changes and the last commit combined. Use with nothing staged to edit the last commits message. |
| git rebase | `git rebase <base>` | Rebase the current branch onto <base>. <base> can be a commit ID, branch name, a tag, or a relative reference to HEAD. |
| git reflog | `git reflog` | Show a log of changes to the local repositorys HEAD. Add --relative-date flag to show date info or --all to show all refs. |
### Historial de reescritura de Git
| Comando | Ejemplo | Descripción |
| ---------- | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| git commit | `git commit --amend` | Reemplazar el último commit con los cambios en staged y el último commit combinados. Editas el mensaje del último commit. |
| git rebase | `git rebase <base>` | Rebase la rama actual en <base> que puede ser un commit ID, un nombre de rama, una etiqueta o una referencia relativa a HEAD. |
| git reflog | `git reflog` | Muestra registro de cambios en el HEAD del repositorio local. Con --relative-date muestra información de fechas y --all para mostrar todas las referencias. |
### Git Branches
| Command | Example | Description |
| ------------ | -------------------------- | ------------------------------------------------------------------------------------------------------------- |
| git branch | `git branch` | List all of the branches in your repo. Add a <branch> argument to create a new branch with the name <branch>. |
| git checkout | `git checkout -b <branch>` | Create and check out a new branch named <branch>. Drop the -b flag to checkout an existing branch. |
| git merge | `git merge <branch>` | Merge <branch> into the current branch. |
| Comando | Ejemplo | Descripción |
| ------------ | -------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| git branch | `git branch` | Lista todas las ramas de tu repositorio. Añade un argumento <branch> para crear una nueva rama con el nombre <branch>. |
| git checkout | `git checkout -b <branch>` | Crea y comprueba una nueva rama con el nombre <branch>. Elimina la opción -b para obtener una rama existent |
| git merge | `git merge <branch>` | Fusiona <branch> en la rama actual. |
### Git Remote Repositories
### Repositorios remotos Git
| Command | Example | Description |
| -------------- | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| git remote add | `git remote add <name> <url>` | Create a new connection to a remote repo. After adding a remote, you can use <name> as a shortcut for <url> in other commands. |
| git fetch | `git fetch <remote> <branch>` | Fetches a specific <branch>, from the repo. Leave off <branch> to fetch all remote refs. |
| git pull | `git pull <remote>` | Fetch the specified remotes copy of current branch and immediately merge it into the local copy. |
| git push | `git push <remote> <branch>` | Push the branch to <remote>, along with necessary commits and objects. Creates named branch in the remote repo if it doesnt exist. |
| Comando | Ejemplo | Descripción |
| -------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| git remote add | `git remote add <name> <url>` | Crea una nueva conexión a un repositorio remoto. Después de añadir un remoto, puedes usar <nombre> como atajo para <url> en otros comandos. |
| git fetch | `git fetch <remote> <branch>` | Obtiene un <branch> específico del repositorio. Deja <branch> para obtener todas las referencias remotas. |
| git pull | `git pull <remote>` | Obtiene la copia remota especificada de la rama actual e inmediatamente la fusiona con la copia local. |
| git push | `git push <remote> <branch>` | Empuja la rama a <remote>, junto con los commits y objetos necesarios. Crea la rama con el nombre en el repositorio remoto si no existe. |
### Git Diff
| Command | Example | Description |
| ----------------- | ------------------- | ---------------------------------------------------------------------- |
| git diff HEAD | `git diff HEAD` | Show the difference between the working directory and the last commit. |
| git diff --cached | `git diff --cached` | Show difference between staged changes and last commit |
| Comando | Ejemplo | Descripción |
| ----------------- | ------------------- | ------------------------------------------------------------------------ |
| git diff HEAD | `git diff HEAD` | Muestra la diferencia entre el directorio de trabajo y el último commit. |
| git diff --cached | `git diff --cached` | Muestra la diferencia entre los cambios realizados y el último commit. |
### Git Config
| Command | Example | Description |
| ---------------------------------------------------- | ------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- |
| git config --global user.name <name> | `git config --global user.name <name>` | Define the author name to be used for all commits by the current user. |
| git config --global user.email <email> | `git config --global user.email <email>` | Define author email to be used for all commits by the current user. |
| git config --global alias <alias-name> <git-command> | `git config --global alias <alias-name> <git-command>` | Create shortcut for a git command . |
| git config --system core.editor <editor> | `git config --system core.editor <editor>` | Set the text editor to be used by commands for all users on the machine. <editor> arg should be the comamnd that launches the desired editor. |
| git config --global --edit | `git config --global --edit ` | Open the global configuration file in a text editor for manual editing. |
| Comando | Ejemplo | Descripción |
| ---------------------------------------------------- | ------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------- |
| git config --global user.name <name> | `git config --global user.name <name>` | Define el nombre de autor que se usará para todos los commits del usuario actual. |
| git config --global user.email <email> | `git config --global user.email <email>` | Define el email del autor que se usará para todas las confirmaciones del usuario actual. |
| git config --global alias <alias-name> <git-command> | `git config --global alias <alias-name> <git-command>` | Crear un acceso directo para un comando git. |
| git config --system core.editor <editor> | `git config --system core.editor <editor>` | Establece el editor de texto que usarán todos los usuarios de la máquina. <editor> arg debe ser el comando que lanza el editor deseado. |
| git config --global --edit | `git config --global --edit ` | Abrir el archivo de configuración global en un editor de texto para su edición manual. |
### Git Rebase
| Command | Example | Description |
| -------------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| git rebase -i <base> | `git rebase -i <base>` | Interactively rebase current branch onto <base>. Launches editor to enter commands for how each commit will be transferred to the new base. |
| Comando | Ejemplo | Descripción |
| -------------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| git rebase -i <base> | `git rebase -i <base>` | Rebase interactivamente la rama actual en <base>. Inicia el editor para introducir comandos sobre cómo se transferirá cada confirmación a la nueva base. |
### Git Pull
| Command | Example | Description |
| -------------------------- | ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| git pull --rebase <remote> | `git pull --rebase <remote>` | Fetch the remotes copy of current branch and rebases it into the local copy. Uses git rebase instead of the merge to integrate the branches. |
| Comando | Ejemplo | Descripción |
| -------------------------- | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| git pull --rebase <remote> | `git pull --rebase <remote>` | Obtiene la copia remota de la rama actual y la vuelve a basar en la copia local. Utiliza git rebase en lugar de merge para integrar las ramas. |
### Git Reset
| Command | Example | Description |
| ------------------------- | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| git reset | `git reset ` | Reset the staging area to match the most recent commit but leave the working directory unchanged. |
| git reset --hard | `git reset --hard` | Reset staging area and working directory to match most recent commit and overwrites all changes in the working directory |
| git reset <commit> | `git reset <commit>` | Move the current branch tip backwards to <commit>, reset the staging area to match, but leave the working directory alone |
| git reset --hard <commit> | `git reset --hard <commit>` | Same as previous, but resets both the staging area & working directory to match. Deletes uncommitted changes, and all commits after <commit>. |
| Comando | Ejemplo | Descripción |
| ------------------------- | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| git reset | `git reset ` | Restablece el área de preparación para que coincida con la confirmación más reciente, pero deja el directorio de trabajo sin cambios. |
| git reset --hard | `git reset --hard` | Restablece el área de preparación y el directorio de trabajo para que coincidan con la confirmación más reciente y sobreescribe todos los cambios en el directorio de trabajo. |
| git reset <commit> | `git reset <commit>` | Mueve la punta de la rama actual hacia atrás hasta <commit>, resetea el área de preparación para que coincida, pero deja el directorio de trabajo solo |
| git reset --hard <commit> | `git reset --hard <commit>` | Igual que el anterior, pero reinicia tanto el área de preparación como el directorio de trabajo para que coincidan. Borra los cambios no comprometidos, y todos los commits posteriores a <commit>. |
### Git Push
| Command | Example | Description |
| ------------------------- | --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| git push <remote> --force | `git push <remote> --force` | Forces the git push even if it results in a non-fast-forward merge. Do not use the --force flag unless youre sure you know what youre doing. |
| git push <remote> --all | `git push <remote> --all` | Push all of your local branches to the specified remote. |
| git push <remote> --tags | `git push <remote> --tags` | Tags arent automatically pushed when you push a branch or use the --all flag. The --tags flag sends all of your local tags to the remote repo. |
| Comando | Ejemplo | Descripción |
| ------------------------- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| git push <remote> --force | `git push <remote> --force` | Fuerza el git push incluso si resulta en una fusión no rápida. No uses la opción --force a menos que estés seguro de lo que haces. |
| git push <remote> --all | `git push <remote> --all` | Envía todas tus ramas locales a la remota especificada. |
| git push <remote> --tags | `git push <remote> --tags` | Las etiquetas no se envían automáticamente cuando envías una rama o usas la opción --all. La opción --tags envía todas tus etiquetas locales al repositorio remoto. |
## Resources
## Recursos
- [What is Version Control?](https://www.youtube.com/watch?v=Yc8sCSeMhi4)
- [Types of Version Control System](https://www.youtube.com/watch?v=kr62e_n6QuQ)
@ -157,5 +164,13 @@ I have taken these from [atlassian](https://www.atlassian.com/git/tutorials/atla
- [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)
- [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 38](day38.md)
Nos vemos en el [Día 38](day38.md)

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)
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)
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)
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)
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)
### 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)
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)
### 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)
### 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)
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)
### 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)
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)
### 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)
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)
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)
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)
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)
- [Types of Version Control System](https://www.youtube.com/watch?v=kr62e_n6QuQ)
@ -113,5 +113,14 @@ 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)
- [Complete Git and GitHub Tutorial](https://www.youtube.com/watch?v=apGV9Kg7ics)
- [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/)
- [Ejemplos README.md para tus proyectos](https://gitea.vergaracarmona.es/manuelver/plantillas-README)
See you on [Day 39](day39.md)
Nos vemos en el [Día 39](day39.md).

View File

@ -1,194 +1,190 @@
## Viewing, unstaging, discarding & restoring
## Visualización, desescalado, descarte y restauración
Continuing from where we finished yesterday around some of the commands that we have with git and how to leverage git with your projects. Remember we have not touched GitHub or any other git-based services yet this is all to help you keep control of your projects locally at the moment, but they will all become useful when we start to integrate into those tools.
Vamos a continuar donde lo dejamos ayer en torno a algunos de los comandos que tenemos con git y cómo aprovechar git con sus proyectos. Recuerde que no hemos tocado GitHub o cualquier otro servicio basado en git todavía, estamos viendo como mantener el control de los proyectos a nivel local por el momento, pero todos ellos serán útiles cuando empezamos a integrar esas herramientas.
### Viewing the Staged and Unstaged Changes
### Viendo los Cambios Staged y Unstaged
It is good practice to make sure you view the staged and unstaged code before committing. We can do this by running the `git diff --staged` command
Es una buena práctica asegurarse de ver el código preparado y no preparado antes de confirmar. Podemos hacerlo ejecutando el comando `git diff --staged`
![](Images/Day39_Git1.png)
This then shows us all the changes we have made and all new files we have added or deleted.
Esto nos muestra todos los cambios que hemos hecho y todos los archivos nuevos que hemos añadido o borrado.
changes in the modified files are indicated with `---` or `+++` you can see below that we just added +add some text below which means they are new lines.
Los cambios en los archivos modificados se indican con `---` o `+++` puedes ver abajo que acabamos de añadir +añadir algo de texto debajo lo que significa que son nuevas líneas.
![](Images/Day39_Git2.png)
We can also run `git diff` to compare our staging area with our working directory. If we make some changes to our newly added file code.txt and add some lines of text.
También podemos ejecutar `git diff` para comparar nuestra área de staging con nuestro directorio de trabajo. Si hacemos algunos cambios en nuestro archivo recién añadido code.txt y añadimos algunas líneas de texto.
![](Images/Day39_Git3.png)
If we then run `git diff` we compare and see the output below.
Si luego ejecutamos `git diff` comparamos y vemos la salida de abajo.
![](Images/Day39_Git4.png)
### Visual Diff Tools
### Herramientas visuales Diff
For me, the above is more confusing so I would much rather use a visual tool,
To name a few visual diff tools:
Para mí, lo anterior es algo confuso, así que prefiero utilizar una herramienta visual. Por nombrar algunas de ellas:
- KDiff3
- P4Merge
- WinMerge (Windows Only)
- WinMerge (Sólo Windows)
- VSCode
To set this in git we run the following command `git config --global diff.tool vscode`
Para configurar esto en git ejecutamos el siguiente comando `git config --global diff.tool vscode`.
We are going to run the above and we are going to set some parameters when we launch VScode.
Vamos a ejecutar lo anterior y vamos a establecer algunos parámetros cuando lancemos VScode.
![](Images/Day39_Git5.png)
We can also check our configuration with `git config --global -e`
También podemos comprobar nuestra configuración con `git config --global -e`.
![](Images/Day39_Git6.png)
We can then use `git difftool` to now open our diff visual tool.
Podemos usar `git difftool` para abrir nuestra herramienta visual diff.
![](Images/Day39_Git7.png)
Which then opens our VScode editor on the diff page and compares the two, we have only modified one file from nothing to now adding a line of code on the right side.
Esto abre nuestro editor VScode en la página diff y compara los dos. Veremos que sólo hemos modificado un archivo añadiendo una línea de código en el lado derecho.
![](Images/Day39_Git8.png)
I find this method much easier to track changes and this is something similar to what we will see when we look into git-based services such as GitHub.
Encuentro este método mucho más fácil para rastrear cambios y es algo similar a lo que veremos cuando busquemos en servicios basados en git como GitHub.
We can also use `git difftool --staged` to compare stage with committed files.
También podemos usar `git difftool --staged` para comparar el stage con los archivos confirmados.
![](Images/Day39_Git9.png)
Then we can cycle through our changed files before we commit.
Entonces podemos ver el ciclo a través de nuestros archivos cambiados antes de confirmar.
![](Images/Day39_Git10.png)
I am using VScode as my IDE and like most IDEs they have this functionality built in it is very rare you would need to run these commands from the terminal, although helpful if you don't have an IDE installed for some reason.
Estoy usando VScode como mi IDE y como la mayoría de los IDEs tienen esta funcionalidad incorporada. Es muy raro que necesites ejecutar estos comandos desde la terminal, aunque es útil si no tienes un IDE instalado por alguna razón.
### Viewing the History
### Viendo el Historial
We previously touched on `git log` which will provide us with a comprehensive view of all commits we have made in our repository.
Anteriormente hemos tocado `git log` que nos proporcionará una visión completa de todos los commits que hemos hecho en nuestro repositorio.
![](Images/Day39_Git11.png)
Each commit has its hexadecimal string, unique to the repository. Here you can see which branch we are working on and then also the author, date and commit message.
Cada commit tiene su cadena hexadecimal, única para el repositorio. Aquí puedes ver en qué rama estamos trabajando y también el autor, la fecha y el mensaje de confirmación.
We also have `git log --oneline` and this gives us a much smaller version of the hexadecimal string which we can use in other `diff` commands. We also only have the one-line description or commit message.
También tenemos `git log --oneline` que nos devuelve una versión mucho más pequeña de la cadena hexadecimal que podemos usar en otros comandos `diff`. También tenemos sólo la descripción de una línea o el mensaje de commit.
![](Images/Day39_Git12.png)
We can reverse this into a start with the first commit by running `git log --oneline --reverse` and now we see our first commit at the top of our page.
Podemos revertir esto en un inicio con el primer commit ejecutando `git log --oneline --reverse` y ahora vemos nuestro primer commit en la parte superior de nuestra página.
![](Images/Day39_Git13.png)
### Viewing a Commit
### Ver un commit
Being able to look at the commit message is great if you have been conscious about following best practices and you have added a meaningful commit message, however, there is also `git show` command which allows us to inspect and view a commit.
We can use `git log --oneline --reverse` to get a list of our commits. and then we can take those and run `git show <commit ID>`
Ser capaz de mirar el mensaje de confirmación es genial si has sido consciente de seguir las mejores prácticas y has añadido un mensaje de confirmación significativo, sin embargo, también existe el comando `git show` si queremos inspeccionar un commit concreto. Podemos utilizar `git log --oneline --reverse` para obtener una lista de nuestros commits. y luego podemos tomarlos y ejecutar `git show <commit ID>`.
![](Images/Day39_Git14.png)
The output of that command will look like below with the detail of the commit, author and what changed.
La salida de ese comando se verá como abajo con el detalle del commit, autor y lo que cambió.
![](Images/Day39_Git15.png)
We can also use `git show HEAD~1` where 1 is how many steps back from the current version we want to get back to.
También podemos usar `git show HEAD~1` donde 1 es el número de pasos hacia atrás desde la versión actual a la que queremos volver.
This is great if you want some detail on your files, but if we want to list all the files in a tree for the whole snapshot directory. We can achieve this by using the `git ls-tree HEAD~1` command, again going back one snapshot from the last commit. We can see below we have two blobs, these indicate files whereas the tree would indicate a directory. You can also see commits and tags in this information.
Esto es genial si queremos algún detalle de nuestros archivos, pero si queremos listar todos los archivos de un árbol para todo el directorio de la instantánea. Podemos conseguirlo usando el comando `git ls-tree HEAD~1`, de nuevo retrocediendo una instantánea desde el último commit. Podemos ver abajo que tenemos dos blobs, estos indican archivos mientras que el árbol indicaría un directorio. También puedes ver commits y tags en esta información.
![](Images/Day39_Git16.png)
We can then use the above to drill in and see the contents of our file (blobs) using the `git show` command.
Podemos usar lo anterior para ver el contenido de nuestro archivo (blobs) usando el comando `git show`.
![](Images/Day39_Git17.png)
Then the contents of that specific version of the file will be shown.
Entonces se mostrará el contenido de esa versión específica del archivo.
![](Images/Day39_Git18.png)
### Unstaging Files
### Unstaging archivos
There will be a time when you have maybe used `git add .` but there are files you do not wish to commit to that snapshot just yet. In this example below I have added newfile.txt to my staging area but I am not ready to commit this file so I am going to use the `git restore --staged newfile.txt` to undo the `git add` step.
Habrá un momento en el que quizás haya usado `git add .` pero hay archivos que no desea confirmar en esa instantánea todavía. En este ejemplo he añadido newfile.txt a mi área de staging pero no estoy listo para confirmar este archivo así que voy a usar `git restore --staged newfile.txt` para deshacer el paso `git add`.
![](Images/Day39_Git19.png)
We can also do the same to modified files such as main.js and unstage the commit, see above we have a greem M for modified and then below we are unstaging those changes.
También podemos hacer lo mismo con archivos modificados como main.js y deshacer el commit, mira arriba tenemos una M en verde y abajo hemos deshecho esos cambios.
![](Images/Day39_Git20.png)
I have found this command quite useful during the 90DaysOfDevOps as I sometimes work ahead of the days where I feel I want to make notes for the following day but I don't want to commit and push to the public GitHub repository.
He encontrado este comando bastante útil durante los 90DaysOfDevOps ya que a veces trabajo antes de los días en los que siento que quiero hacer anotaciones para el día siguiente pero no quiero hacer commit y push al repositorio público de GitHub.
### Discarding Local Changes
### Descartando Cambios Locales
Sometimes we might make changes but we are not happy with those changes and we want to throw them away. We are going to use the `git restore` command again and we are going to be able to restore files from our snapshots or previous versions. We can run `git restore .` against our directory and we will restore everything from our snapshot but notice that our untracked file is still present. There is no previous file being tracked called newfile.txt.
A veces podemos hacer cambios pero no estamos contentos con esos cambios y queremos desecharlos. Vamos a utilizar el comando `git restore` de nuevo y vamos a poder restaurar archivos de nuestras snapshots o versiones anteriores. Podemos ejecutar `git restore .` contra nuestro directorio y restauraremos todo desde nuestra instantánea, pero observa que nuestro archivo no rastreado sigue presente. No hay ningún archivo anterior siendo rastreado llamado newfile.txt.
![](Images/Day39_Git21.png)
Now to remove newfile.txt or any untracked files. We can use `git clean` we will get a warning alone.
Ahora para eliminar newfile.txt o cualquier archivo no rastreado. Podemos usar `git clean` solo obtendremos una advertencia.
![](Images/Day39_Git22.png)
Or if we know the consequences then we might want to run `git clean -fd` to force and remove all directories.
O si conocemos las consecuencias podemos ejecutar `git clean -fd` para forzar y eliminar todos los directorios.
![](Images/Day39_Git23.png)
### Restoring a File to an Earlier Version
### Restaurar un archivo a una versión anterior
As we have alluded to throughout a big portion of what Git can help with is being able to restore copies of your files from your snapshots (this is not a backup but it is a very fast restore point) My advice is that you also save copies of your code in other locations using a backup solution for this.
Como hemos aludido, lo que Git nos puede ayudar es a restaurar copias de tus archivos desde tus instantáneas (esto no es una copia de seguridad, pero es un punto de restauración muy rápido). Es recomendable que también guardes copias de tu código en otros lugares utilizando una solución de copia de seguridad expresamente para esto.
As an example let's go and delete our most important file in our directory, notice we are using Unix-based commands to remove this from the directory, not git commands.
Como ejemplo vamos a borrar nuestro archivo más importante en nuestro directorio, pero utilizando comandos basados en Unix para eliminar el directorio, no comandos de git.
![](Images/Day39_Git24.png)
Now we have no readme.mdin our working directory. We could have used `git rm readme.md` and this would then be reflected in our git database. Let's also delete it from here to simulate it being removed completely.
Ahora no tenemos readme.md en nuestro directorio de trabajo. Podríamos haber usado `git rm readme.md` y esto se reflejaría en nuestra base de datos de git. Así que lo borramos también así para simular la eliminación por completo.
![](Images/Day39_Git25.png)
Let's now commit this with a message and prove that we no longer have anything in our working directory or staging area.
Ahora confirmemos esto con un mensaje y probemos que ya no tenemos nada en nuestro directorio de trabajo o área de preparación.
![](Images/Day39_Git26.png)
Mistakes were made and we now need this file back!
¡Se cometieron errores y ahora necesitamos recuperar ese archivo! 😱
We could use the `git undo` command which will undo the last commit, but what if it was a while back? We can use our `git log` command to find our commits and then we find that our file is in the last commit but we don't all of those commits to be undone so we can then use this command `git restore --source=HEAD~1 README.md` to specifically find the file and restore it from our snapshot.
Podríamos usar el comando `git undo` que deshará el último commit, pero ¿qué pasa si fue hace tiempo? Podemos usar nuestro comando `git log` para encontrar el commit concreto pero no queremos que todos los commits que haya por el medio se deshagan, así que vamos a especificar el fichero con el comando `git restore --source=HEAD~1 README.md` y restaurarlo desde nuestro snapshot.
You can see using this process we now have the file back in our working directory.
Puedes ver que usando este proceso ahora tenemos el archivo de vuelta en nuestro directorio de trabajo 😅
![](Images/Day39_Git27.png)
We now have a new untracked file and we can use our commands previously mentioned to track, stage and commit our files and changes.
Ahora tenemos un nuevo archivo no rastreado y podemos usar los comandos mencionados anteriormente para rastrear, preparar y comitear nuestros cambios.
### Rebase vs Merge
This seems to be the biggest headache when it comes to Git and when to use rebase vs using merge on your git repositories.
Este parece ser el mayor dolor de cabeza cuando se trata de Git, cuando usar rebase o merge en tus repositorios git.
The first thing to know is that both `git rebase` and `git merge` solve the same problem. Both are to integrate changes from one branch into another branch. However, they do this in different ways.
Lo primero que hay que saber es que tanto `git rebase` como `git merge` resuelven el mismo problema. Ambos sirven para integrar cambios de una rama en otra rama. Sin embargo, lo hacen de formas diferentes.
Let's start with a new feature in a new dedicated branch. The Main branch continues with new commits.
Empecemos con una nueva característica en una nueva rama dedicada. La rama principal continúa con nuevos commits.
![](Images/Day39_Git28.png)
The easy option here is to use `git merge feature main` which will merge the main branch into the feature branch.
La opción fácil es usar `git merge feature main` que fusionará la rama principal en la rama feature.
![](Images/Day39_Git29.png)
Merging is easy because it is non-destructive. The existing branches are not changed in any way. However, this also means that the feature branch will have an irrelevant merge commit every time you need to incorporate upstream changes. If the main is very busy or active this will or can pollute the feature branch history.
La fusión es fácil porque no es destructiva. Las ramas existentes no se modifican. Sin embargo, esto también significa que la rama principal tendrá un commit de fusión irrelevante cada vez que necesites incorporar cambios de la rama principal. Si la main está muy ocupada o activa esto podría contaminar el historial de la rama feature.
As an alternate option, we can rebase the feature branch onto the main branch using
Como opción alternativa, podemos volver a basar la rama de características en la rama principal utilizando:
```
git checkout feature
git rebase main
```
This moves the feature branch (the entire feature branch) effectively incorporating all of the new commits in the main. But, instead of using a merge commit, rebasing re-writes the project history by creating brand new commits for each commit in the original branch.
Esto mueve la rama feature (toda la rama feature) incorporando efectivamente todos los nuevos commits en la main. Pero, en lugar de usar un commit merge, rebasing reescribe la historia del proyecto creando nuevos commits para cada commit en la rama original.
![](Images/Day39_Git30.png)
The biggest benefit of rebasing is a much cleaner project history. It also eliminates unnecessary merge commits. and as you compare the last two images, you can follow arguably a much cleaner linear project history.
El mayor beneficio de rebase es un historial del proyecto mucho más limpio. También elimina commits de fusión innecesarios. Si comparas las dos últimas imágenes, puedes seguir una historia del proyecto lineal mucho más limpia.
Although it's still not a foregone conclusion, choosing the cleaner history also comes with tradeoffs, If you do not follow the [The Golden rule of rebasing](https://www.atlassian.com/git/tutorials/merging-vs-rebasing#the-golden-rule-of-rebasing) re-writing project history can be potentially catastrophic for your collaboration workflow. And, less importantly, rebasing loses the context provided by a merge commit—you cant see when upstream changes were incorporated into the feature.
Aunque todavía no es una conclusión inevitable, la elección del historial más limpio también viene con desventajas, si no sigues [La regla de oro de rebasing](hhttps://www.atlassian.com/git/tutorials/merging-vs-rebasing#the-golden-rule-of-rebasing) y vuelves a escribir el historial del proyecto puede ser potencialmente catastrófico para su flujo de trabajo de colaboración. Y por otro lado, con menos importancia pero también presente, al realizar rebase se pierde el contexto proporcionado por un commit de fusión: no puedes ver cuándo se incorporaron realmente los cambios de la línea ascendente en la feature.
## Resources
## Recursos
- [What is Version Control?](https://www.youtube.com/watch?v=Yc8sCSeMhi4)
- [Types of Version Control System](https://www.youtube.com/watch?v=kr62e_n6QuQ)
@ -198,5 +194,13 @@ Although it's still not a foregone conclusion, choosing the cleaner history also
- [Complete Git and GitHub Tutorial](https://www.youtube.com/watch?v=apGV9Kg7ics)
- [Git cheatsheet](https://www.atlassian.com/git/tutorials/atlassian-git-cheatsheet)
- [Exploring the Git command line A getting started guide](https://veducate.co.uk/exploring-the-git-command-line/)
- [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 [Day40](day40.md)
Nos vemos en el [Día 40](day40.md)

View File

@ -1,191 +1,195 @@
## Social Network for code
## Red social para el código
Exploring GitHub | GitLab | BitBucket
Explorando GitHub | GitLab | BitBucket 🚀
Today I want to cover some of the git-based services that we have likely all heard of and expect we also use daily.
Hoy veremos algunos de los servicios basados en git de los que probablemente hemos oído hablar. Utilizaremos algunos de nuestros conocimientos adquiridos para mover copias de nuestros datos a cada uno de los principales servicios.
We will then use some of our prior session knowledge to move copies of our data to each of the main services.
I called this section "Social Network for Code" let me explain why?
He llamado a esta sección "Red Social para el Código", ya verás por qué...
### GitHub
Most common at least for me is GitHub, GitHub is a web-based hosting service for git. It is most commonly used by software developers to store their code. Source Code Management with the git version control features as well as a lot of additional features. It allows for teams or open contributors to easily communicate and provides a social aspect to coding. (hence the social networking title) Since 2018 GitHub is part of Microsoft.
El más común es GitHub, un servicio de alojamiento basado en web para git. Es muy utilizado por los desarrolladores de software para almacenar código. Tienes la gestión del código fuente centralizada en un repositorio remoto y distribuida gracias a las características de control de versiones git, así como un montón de características adicionales. Permite a los equipos y colaboradores comunicarse fácilmente y proporciona un aspecto social a la codificación. Desde 2018 GitHub forma parte de Microsoft (A golpe de talonario).
GitHub has been around for quite some time and was founded in 2007/2008. With Over 40 million users on the platform today.
GitHub fue fundada en 2007/2008. Con Más de 40 millones de usuarios en la plataforma a día de hoy.
GitHub Main Features
Características principales de GitHub
- Code Repository
- Pull Requests
- Project Management toolset - Issues
- CI / CD Pipeline - GitHub Actions
- Repositorio de código
- Solicitudes de Pull
- Herramientas de gestión de proyectos - Issues
- Canalización CI / CD - Acciones GitHub
In terms of pricing, GitHub has different levels of pricing for its users. More can be found on [Pricing](https://github.com/pricing)
En términos de precios, GitHub tiene diferentes niveles de precios para sus usuarios. Puedes encontrar más información en [Pricing](https://github.com/pricing)
For this, we will cover the free tier.
Aquí veremos tan solo el nivel gratuito.
I am going to be using my already created GitHub account during this walkthrough, if you do not have an account then on the opening GitHub page there is a sign-up option and some easy steps to get set up.
Voy a utilizar mi cuenta de GitHub ya creada durante este tutorial, si no tienes una cuenta, en la página de apertura de GitHub hay una opción de registro y algunos pasos sencillos para configurarla.
### GitHub opening page
### Página de inicio de GitHub
When you first log in to your GitHub account you get a page containing a lot of widgets giving you options of where and what you would like to see or do. First up we have the "All Activity" this is going to give you a look into what is happening with your repositories or activity in general associated with your organisation or account.
La primera vez que accedes a tu cuenta de GitHub aparece una página que contiene un montón de widgets que te dan opciones de dónde y qué te gustaría ver o hacer. En primer lugar tenemos "Toda la actividad", que te dará una visión de lo que está sucediendo con tus repositorios o actividad en general asociada a tu organización o cuenta.
![](Images/Day40_Git1.png)
Next, we have our Code Repositories, either our own or repositories that we have interacted with recently. We can also quickly create new repositories or search repositories.
A continuación, tenemos nuestros repositorios de código, ya sean propios o repositorios con los que hemos interactuado recientemente. También podemos crear rápidamente nuevos repositorios o buscar repositorios.
![](Images/Day40_Git2.png)
We then have our recent activity, these for me are issues and pull requests that I have created or contributed to recently.
Luego tenemos nuestra actividad reciente, que para mí son temas y pull requests que he creado o contribuido recientemente.
![](Images/Day40_Git3.png)
Over on the right side of the page, we have some referrals for repositories that we might be interested in, most likely based on your recent activity or own projects.
En la parte derecha tenemos algunas referencias de repositorios en los que podríamos estar interesados, probablemente basados en tu actividad reciente o en tus propios proyectos.
![](Images/Day40_Git4.png)
To be honest I am very rarely on my home page that we just saw and described, although I now see that the feed could be really useful to help interact with the community a little better on certain projects.
Para ser honesto no suelo entrar en mi propia página de inicio, veo que el feed podría ser realmente útil para ayudar a interactuar mejor con la comunidad en ciertos proyectos.
Next up if we want to head into our GitHub Profile we can navigate to the top right corner and on your image, there is a drop-down which allows you to navigate through your account. From here to access your Profile select "Your Profile"
A continuación, si queremos entrar en nuestro perfil de GitHub podemos navegar a la esquina superior derecha y en tu imagen, hay un desplegable que te permite navegar a través de tu cuenta. Desde aquí para acceder a tu Perfil selecciona "Tu Perfil"
![](Images/Day40_Git5.png)
Next, your profile page will appear, by default, unless you change your configuration you are not going to see what I have, I have added some functionality that shows my recent blog posts over on [vZilla](https://vzilla.co.uk) and then also my latest videos on my [YouTube](https://m.youtube.com/c/MichaelCade1) Channel.
A continuación, aparecerá tu página de perfil, por defecto, a menos que cambies tu configuración no vas a ver lo que yo tengo, he añadido alguna funcionalidad que muestra mis últimas entradas de blog en [vZilla](https://vzilla.co.uk) y también mis últimos vídeos en mi canal de [YouTube](https://m.youtube.com/c/MichaelCade1) Channel.
You are not going to be spending much time looking at your profile, but this is a good profile page to share around your network so they can see the cool projects you are working on.
No vas a pasar mucho tiempo mirando tu perfil, pero esta es una buena página de perfil para compartir en tu red para que puedan ver los proyectos interesantes en los que estás trabajando.
Si quieres ver algunos ejemplos de páginas de inicio:
- Página del autor [Michael Cade](https://github.com/MichaelCade/MichaelCade)
- Página del traductor [manuelver](https://github.com/manuelver/manuelver)
![](Images/Day40_Git6.png)
We can then drill down into the building block of GitHub, the repositories. Here you are going to see your repositories and if you have private repositories they are also going to be shown in this long list.
A continuación, podemos profundizar en el bloque de construcción de GitHub, los repositorios. Aquí vas a ver tus repositorios y si tienes repositorios privados también se mostrarán en esta larga lista.
![](Images/Day40_Git7.png)
As the repository is so important to GitHub let me choose a pretty busy one of late and run through some of the core functionality that we can use here on top of everything I am already using when it comes to editing our "code" in git on my local system.
El repositorio es muy importante en GitHub, así que elijo uno bastante movido últimamente para ejecutar algunas de las funciones básicas que podemos utilizar.
First of all, from the previous window, I have selected the 90DaysOfDevOps repository and we get to see this view. You can see from this view we have a lot of information, we have our main code structure in the middle showing our files and folders that are stored in our repository. We have our readme. mdbeing displayed down at the bottom. Over to the right of the page, we have an about section where the repository has a description and purpose. Then we have a lot of information underneath this showing how many people have starred in the project, forked, and watched.
Desde la ventana anterior, he seleccionado el repositorio 90DaysOfDevOps. Se puede ver en esta vista que tenemos una gran cantidad de información, tenemos nuestra estructura de código principal en el centro mostrando nuestros archivos y carpetas que se almacenan en nuestro repositorio. Tenemos nuestro readme.md que se muestra en la parte inferior y le da más importancia al fichero, ya que es nuestra presentación del proyecto. A la derecha de la página, tenemos una sección con una descripción y propósito del proyecto. Luego tenemos un montón de información debajo de esto que muestra cuántas personas han destacado en el proyecto con una star, cuántas lo han visto y cuántas lo han bifurcado.
![](Images/Day40_Git8.png)
If we scroll down a little further you will also see that we have Released, these are from the golang part of the challenge. We do not have any packages in our project, we have our contributors listed here. (Thank you community for assisting in my spelling and fact checking) We then have languages used again these are from different sections in the challenge.
Si nos desplazamos un poco más abajo también veremos que tenemos Releases, estos son de la parte golang del desafío. No tenemos ningún paquete en nuestro proyecto en este momento, y también vemos a nuestros colaboradores listados. (Gracias comunidad por ayudar en mi ortografía y otras correcciones) Luego tenemos lenguajes utilizados.
![](Images/Day40_Git9.png)
A the top of the page you are going to see a list of tabs. These may vary and these can be modified to only show the ones you require. You will see here that I am not using all of these and I should remove them to make sure my whole repository is tidy.
En la parte superior de la página verás una lista de pestañas. Éstas pueden variar y pueden modificarse para mostrar sólo las que necesites. Aquí verás que no estoy usando todas y que debería quitarlas para asegurarme de que todo mi repositorio está ordenado y limpio.
First up we had the code tab which we just discussed but these tabs are always available when navigating through a repository which is super useful so we can jump between sections quickly and easily. Next, we have the issues tab.
En primer lugar tenemos la pestaña de código, de la que acabamos de hablar, pero estas pestañas están siempre disponibles cuando se navega a través de un repositorio, lo que es muy útil para que podamos saltar entre las secciones de forma rápida y sencilla. A continuación, tenemos la pestaña de problemas.
Issues let you track your work on GitHub, where development happens. In this specific repository you can see I have some issues focused on adding diagrams or typos but also we have an issue stating a need or requirement for a Chinese version of the repository.
Las incidencias te permiten hacer un seguimiento de tu trabajo en GitHub, donde tiene lugar el desarrollo. En este repositorio específico se puede ver que tengo algunas cuestiones centradas en la adición de diagramas o errores tipográficos, pero también tenemos una cuestión que indica una necesidad o requisito para una versión china del repositorio.
If this was a code repository then this is a great place to raise concerns or issues with the maintainers, but remember to be mindful and detailed about what you are reporting, and give as much detail as possible.
Si esto fuera un repositorio de código, entonces este es un gran lugar para plantear inquietudes o problemas con los mantenedores, pero recuerde que debe ser consciente y detallado acerca de lo que está informando, y dar tantos detalles como sea posible.
![](Images/Day40_Git10.png)
The next tab is Pull Requests, Pull requests let you tell others about changes you've pushed to a branch in a repository. This is where someone may have forked your repository, made changes such as bug fixes or feature enhancements or just typos in a lot of the cases in this repository.
La siguiente pestaña es Pull Requests. Permite informar a otros sobre los cambios que ha empujado a una rama en un repositorio. Aquí es donde alguien puede haber bifurcado el repositorio en otra rama, sea del mismo proyecto o de un fork, ha hecho cambios como correcciones de errores o mejoras de características o simplemente errores tipográficos, y luego ha solicitado que se fusionen esos cambios en la rama principal del proyecto.
We will cover forking later on.
Cubriremos el forking con más detalle más adelante.
![](Images/Day40_Git11.png)
I believe the next tab is quite new? But I thought for a project like #90DaysOfDevOps this could help guide the content journey but also help the community as they walk through their learning journey. I have created some discussion groups for each section of the challenge so people can jump in and discuss.
La siguiente pestaña es bastante nueva, pero se ha creado para #90DaysOfDevOps porque no solo puede ayudar a guiar en el viaje por el contenido, sino que también ayuda a la comunidad a medida que caminan a través de su aprendizaje. Dentro hay grupos de discusión para cada sección del desafío para que quien quiera pueda entrar y comentar, a modo de foro.
![](Images/Day40_Git12.png)
The Actions tab is going to enable you to build, test and deploy code and a lot more right from within GitHub. GitHub Actions will be something we cover in the CI/CD section of the challenge but this is where we can set some configuration here to automate steps for us.
La pestaña de Actions te permitirá construir, probar, desplegar código y mucho más. GitHub Actions lo veremos en la sección de CI/CD del desafío. Como info previa, es aquí donde podemos establecer automatizaciones de tareas repetitivas para que se hagan por si solas con un disparador.
On my main GitHub Profile, I am using GitHub Actions to fetch the latest blog posts and YouTube videos to keep things up to date on that home screen.
Por ejemplo, en mi perfil principal de GitHub utilizo las Actions para obtener las últimas entradas del blog y vídeos de YouTube y mantener al día mi página de perfil Github.
![](Images/Day40_Git13.png)
I mentioned above how GitHub is not just a source code repository but is also a project management tool, The Project tab enables us to build out project tables kanban type boards so that we can link issues and PRs to better collaborate on the project and have visibility of those tasks.
Ya he mencionado que GitHub no es sólo un repositorio de código fuente, sino también una herramienta de gestión de proyectos. La pestaña Projects nos permite crear tablas de proyecto tipo kanban para que podamos vincular las incidencias y PRs para colaborar mejor en el proyecto y tener visibilidad/transparencia de las tareas.
![](Images/Day40_Git14.png)
I know that issues to me seem like a good place to log feature requests and they are but the wiki page allows for a comprehensive roadmap for the project to be outlined with the current status and in general better document your project is it troubleshooting or how-to type content.
La página wiki permite una hoja de ruta completa para el proyecto que se describe con el estado actual y, en general, documentar mejor el proyecto.
![](Images/Day40_Git15.png)
Not so applicable to this project but the Security tab is there to make sure that contributors know how to deal with certain tasks, we can define a policy here but also code scanning add-ons to make sure your code for example does not contain secret environment variables.
No es tan aplicable a este proyecto, pero la pestaña de Security está ahí para asegurarse de que los contribuyentes saben cómo hacer frente a ciertas tareas, podemos definir una política aquí, pero también complementos de escaneo de código para asegurarse de que su código, por ejemplo, no contiene variables de entorno con contraseñas.
![](Images/Day40_Git16.png)
For me the insights tab is great, it provides so much information about the repository from how much activity has been going on down to commits and issues, but it also reports on traffic to the repository. You can see a list on the left side that allows you to go into great detail about metrics on the repository.
Para mí la pestaña de Insights es genial ya que proporciona mucha información sobre el repositorio. Desde cuantificar la actividad que ha habido hasta los commits e issues, pasando también por informes sobre el tráfico del repositorio. Puedes ver una lista en el lado izquierdo que te permite entrar en gran detalle sobre las métricas del repositorio.
![](Images/Day40_Git17.png)
Finally, we have the Settings tab, this is where we can get into the details of how we run our repository, I am currently the only maintainer of the repository but we could share this responsibility here. We can define integrations and other such tasks here.
Por último, tenemos la pestaña Configuración donde podemos entrar en los detalles de cómo personalizar nuestro repositorio. Actualmente soy el único mantenedor del repositorio pero podríamos compartir esta responsabilidad aquí. Podemos definir integraciones, políticas de ramas y otras tareas.
![](Images/Day40_Git18.png)
This was a super quick overview of GitHub, I think there are some other areas that I might have mentioned that need explaining in a little more detail. As mentioned GitHub houses millions of repositories mostly these are holding source code and these can be public or privately accessible.
Como se mencionó GitHub alberga millones de repositorios, en su mayoría son código fuente y estos pueden ser de acceso público o privado.
Hemos echado un vistazo súper rápido de GitHub, creo que se podría detallar mucho más, pero por ahora no somos comerciales de la herramienta, así que vamos a la parte técnica.
### Forking
I am going to get more into Open-Source in the session tomorrow but a big part of any code repository is the ability to collaborate with the community. Let's think of the scenario I want a copy of a repository because I want to make some changes to it, maybe I want to fix a bug or maybe I want to change something to use it for a use case that I have that was maybe not the intended use case for the original maintainer of the code. This is what we would call forking a repository. A fork is a copy of a repository. Forking a repository allows you to freely experiment with changes without affecting the original project.
Voy a entrar más en Open-Source en la sesión de mañana, pero una gran parte de cualquier repositorio de código es la capacidad de colaborar con la comunidad. Pensemos en el escenario que quiero una copia de un repositorio porque quiero hacer algunos cambios en él, tal vez quiero corregir un error o tal vez quiero cambiar algo para utilizarlo para un caso de uso que tengo que tal vez no era el caso de uso previsto para el mantenedor original del código. Esto es lo que llamaríamos bifurcar un repositorio. Un fork es una copia de un repositorio. La bifurcación de un repositorio permite experimentar libremente con los cambios sin afectar al proyecto original.
Let me head back to the opening page after login and see one of those suggested repositories.
Permíteme volver a la página de inicio después de iniciar sesión y ver uno de esos repositorios sugeridos.
![](Images/Day40_Git19.png)
If we click on that repository we are going to get the same look as we have just walked through on the 90DaysOfDevOps repository.
Si hacemos click en ese repositorio vamos a obtener el mismo aspecto que acabamos de ver en el repositorio 90DaysOfDevOps.
![](Images/Day40_Git20.png)
If we notice below we have 3 options, we have watch, fork and star.
Si nos fijamos a continuación tenemos 3 opciones:
- Watch - Updates when things happen to the repository.
- Fork - a copy of a repository.
- Star - "I think your project is cool"
- Watch - Se actualiza con los visitante al repositorio.
- Fork - Las copias del repositorio.
- Star - "Creo que tu proyecto es genial".
![](Images/Day40_Git21.png)
Given our scenario of wanting a copy of this repository to work on we are going to hit the fork option. If you are a member of multiple organisations then you will have to choose where the fork will take place, I am going to choose my profile.
Vamos a darle a la opción fork para hacer una copia en la que trabajar. Si eres miembro de varias organizaciones entonces tendrás que elegir donde se realizará el fork, yo voy a elegir mi perfil.
![](Images/Day40_Git22.png)
Now we have our copy of the repository that we can freely work on and change as we see fit. This would be the start of the pull request process that we mentioned briefly before but we will cover it in more detail tomorrow.
Ahora ya tenemos nuestra copia del repositorio sobre la que podemos trabajar libremente y modificarla a nuestro antojo. Este sería el comienzo del proceso de pull request que mencionamos brevemente antes pero que cubriremos con más detalle mañana.
![](Images/Day40_Git23.png)
Ok, I hear you say, but how do I make changes to this repository and code if it's on a website, well you can go through and edit on the website but it's not going to be the same as using your favourite IDE on your local system with your favourite colour theme. For us to get a copy of this repository on our local machine we will perform a clone of the repository. This will allow us to work on things locally and then push our changes back into our forked copy of the repository.
Ok, te oigo decir, pero ¿cómo puedo hacer cambios en este repositorio y el código si está en un sitio web? Bueno, puedes editarlo directamente en el página Github, pero no va a ser lo mismo que usar tu IDE favorito en local. Para obtener una copia de este repositorio en local vamos a realizar un clon del repositorio. Esto nos permitirá trabajar localmente y luego empujar/pushear nuestros cambios de nuevo en nuestra copia bifurcada en el repositorio remoto.
We have several options when it comes to getting a copy of this code as you can see below.
Tenemos varias opciones cuando se trata de obtener una copia de este código como se puede ver a continuación.
There is a local version available of GitHub Desktop which gives you a visual desktop application to track changes and push and pull changes between local and GitHub.
Hay una versión local disponible de GitHub Desktop que le da una aplicación de escritorio visual para realizar un seguimiento de los cambios y empujar/pushear y tirar/pullear los cambios entre el local y GitHub.
For this little demo, I am going to use the HTTPS URL we see on there.
Para esta pequeña demostración, voy a utilizar la URL HTTPS.
![](Images/Day40_Git24.png)
Now on our local machine, I am going to navigate to a directory I am happy to download this repository to and then run `git clone url`
Ahora, en nuestra máquina local, voy a navegar al directorio donde quiero descargar el repositorio y luego ejecutar `git clone url`.
![](Images/Day40_Git25.png)
Now we could take it to VScode to make some changes to this.
Podemos llevarlo a VScode para hacer algunos cambios.
![](Images/Day40_Git26.png)
Let's now make some changes, I want to make a change to all those links and replace that with something else.
Vamos a hacer algunos cambios, quiero hacer un cambio en todos esos enlaces y sustituirlos por otra cosa.
![](Images/Day40_Git27.png)
Now if we check back on GitHub and we find our readme.mdin that repository, you should be able to see a few changes that I made to the file.
Si nos fijamos de nuevo en GitHub y encontramos nuestro readme.md, deberías ser capaz de ver algunos cambios que he hecho en el archivo.
![](Images/Day40_Git28.png)
At this stage, this might be complete and we might be happy with our change as we are the only people going to use our new change but maybe it was a bug change and if that is the case then we will want to contribute via a Pull Request to notify the original repository maintainers of our change and see if they accept our changes.
En esta etapa, esto podría estar completo y podríamos estar contentos con nuestro cambio, ya que somos las únicas personas que van a utilizar nuestro nuevo cambio, pero tal vez fue un cambio de error y si ese es el caso, entonces vamos a querer contribuir a través de un Pull Request para notificar a los mantenedores del repositorio original de nuestro cambio y ver si aceptan nuestros cambios.
We can do this by using the contribute button highlighted below. I will cover more on this tomorrow when we look into Open-Source workflows.
Podemos hacer esto utilizando el botón de contribución que se muestra a continuación. Mañana con los flujos de trabajo Open-Source veremos más sobre esto.
![](Images/Day40_Git29.png)
I have spent a long time looking through GitHub and I hear some of you cry but what about other options!
Me han dicho muchos: ¿qué pasa con las otras opciones de repositorios remotos?
Well, there are and I am going to find some resources that cover the basics for some of those as well. You are going to come across GitLab and BitBucket amongst others in your travels and whilst they are git-based services they have their differences.
Bueno, voy a dejar algunos recursos que cubren los conceptos básicos para el resto de opciones. En tus viajes te encontrarás con GitLab y BitBucket, entre otros, y aunque son servicios basados en Git, tienen sus diferencias.
You will also come across hosted options. Most commonly here I have seen GitLab as a hosted version vs GitHub Enterprise (Don't believe there is a free hosted GitHub?)
También encontrarás opciones alojadas, la más común es GitLab frente a GitHub Enterprise. El traductor recomienda la opcíon de código libre gitea.io.
## Resources
## Recursos
- [Learn GitLab in 3 Hours | GitLab Complete Tutorial For Beginners](https://www.youtube.com/watch?v=8aV5AxJrHDg)
- [BitBucket Tutorials Playlist](https://www.youtube.com/watch?v=OMLh-5O6Ub8&list=PLaD4FvsFdarSyyGl3ooAm-ZyAllgw_AM5)
@ -196,5 +200,14 @@ You will also come across hosted options. Most commonly here I have seen GitLab
- [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)
- [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/)
- [GitHub Profile README Generator](https://github.com/rahuldkjain/github-profile-readme-generator)
See you on [Day 41](day41.md)
Nos vemos en el [Día 41](day41.md)

View File

@ -1,118 +1,106 @@
---
title: '#90DaysOfDevOps - The Open Source Workflow - Day 41'
published: false
description: 90DaysOfDevOps - The Open Source Workflow
tags: 'DevOps, 90daysofdevops, learning'
cover_image: null
canonical_url: null
id: 1048806
---
## El flujo de trabajo del Open Source
## The Open Source Workflow
Esperemos que a través de las últimas 7 secciones de Git tengamos una mejor comprensión de lo que es git. También en GitHub cómo un servicio online que se integra con git para proporcionar un repositorio de código fuente, además de una forma en que la comunidad en general puede colaborar en el código y los proyectos abiertos.
Hopefully, through the last 7 sections of Git, we have a better understanding of what git is and then how a git-based service such as GitHub integrates with git to provide a source code repository but also a way in which the wider community can collaborate on code and projects together.
Cuando pasamos a través de los fundamentos de GitHub fuimos a través del proceso de bifurcación de un proyecto al azar y hacer un cambio en nuestro repositorio local. Aquí queremos ir un paso más allá y contribuir a un proyecto de código abierto.
When we went through the GitHub fundamentals we went through the process of forking a random project and making a change to our local repository. Here we want to go one step further and contribute to an open-source project. Remember that contributing doesn't need to be bug fixes or coding features but it could also be documentation. Every little helps and it also allows you to get hands-on with some of the git functionality we have covered.
Recuerda que contribuir no tiene por qué ser corregir errores o codificar características, sino que también puede ser documentación, traducción, propuestas de mejoras, etc. Todo ayuda a mejorar los proyectos comunitarios. Además permite ponerte manos a la obra con algunas de las funcionalidades de git que hemos cubierto o con las tecnologías que contienen los repositorios.
## Fork a Project
## Bifurcar un proyecto
The first thing we have to do is find a project we can contribute to. I have recently been presenting on the [Kanister Project](https://github.com/kanisterio/kanister) and I would like to share my presentations that are now on YouTube to the main readme.mdfile in the project.
Lo primero que tenemos que hacer es encontrar un proyecto en el que podamos contribuir. Recientemente he estado presentando en el [Proyecto Kanister](https://github.com/kanisterio/kanister) y me gustaría compartir mis presentaciones que ahora están en YouTube al fichero readme.md principal del proyecto.
First of all, we need to fork the project. Let's run through that process. I am going to navigate to the link shared above and fork the repository.
En primer lugar, tenemos que bifurcar el proyecto como vimos en el día de ayer. Voy a navegar hasta el enlace mencionado y hacer un fork del repositorio.
![](Images/Day41_Git1.png)
We now have our copy of the whole repository.
Ahora tenemos nuestra copia de todo el repositorio.
![](Images/Day41_Git2.png)
For reference on the Readme.mdfile the original Presentations listed are just these two so we need to fix this with our process.
En el archivo Readme.md las presentaciones originales listadas son solo estas dos por lo que vamos a aportar más.
![](Images/Day41_Git3.png)
## Clones to a local machine
## Clona a una máquina local
Now we have our fork we can bring that down to our local and we can then start making our edits to the files. Using the code button on our repo we can grab the URL and then use `git clone url` in a directory we wish to place the repository.
Ahora que tenemos nuestro fork podemos bajarlo a nuestra máquina local y empezar a editar los archivos. Usando el botón de código en nuestro repositorio podemos coger la URL y luego usar `git clone url` en un directorio en el que queramos colocar el repositorio. Personalmente, me gusta llamar al directorio con el mismo nombre del proyecto.
![](Images/Day41_Git4.png)
## Make our changes
## Realizamos nuestros cambios
We have our project local so we can open VSCode or an IDE or text editor of your choice to add your modifications.
Tenemos nuestro proyecto en local así que podemos abrir VSCode o un IDE o editor de texto de nuestra elección para añadir las modificaciones.
![](Images/Day41_Git5.png)
The readme.mdfile is written in markdown language and because I am modifying someone else's project I am going to follow the existing project formatting to add our content.
El archivo readme.md está escrito en lenguaje markdown y como estoy modificando el proyecto de otra persona voy a seguir el formato del proyecto existente para añadir nuestro contenido. Quiero decir con esto que es importante seguir la línea editorial de un proyecto y hacer cambios que encajen con el proyecto para no dificurtar su futura lectura y la comprobación de cambios por el autor.
![](Images/Day41_Git6.png)
## Test your changes
## Prueba tus cambios
We must as a best practice test our changes, this makes total sense if this was a code change to an application you would want to ensure that the application still functions after a code change, well we also must make sure that documentation is formatted and looks correct.
Como buena práctica debemos probar nuestros cambios, esto tiene sentido total si se tratara de un cambio de código a una aplicación que desea asegurarse de que la aplicación sigue funcionando después de un cambio de código, así que también debemos asegurarnos de que la documentación tiene el formato y el aspecto correcto. Ni se te ocurra pedir cambios en una pull request con errores porque no se te aceptará y puede que en muchos casos simplemente seas ignorado.
In vscode we can add a lot of plugins one of these is the ability to preview markdown pages.
En vscode podemos añadir un montón de plugins para previsualizar páginas markdown.
![](Images/Day41_Git7.png)
## Push changes back to our forked repository
Personalmente utilizo [markdown](https://marketplace.visualstudio.com/items?itemName=starkwang.markdown) y [markdown all in one](https://marketplace.visualstudio.com/items?itemName=yzhang.markdown-all-in-one), que me permite previsualizar el archivo markdown y mucho más.
We do not have the authentication to push our changes directly back to the Kanister repository so we have to take this route. Now that I am happy with our changes we can run through some of those now well-known git commands.
## Enviar los cambios a nuestro repositorio fork
No tenemos la autenticación para pushear cambios directamente al repositorio Kanister así que tenemos que tomar otra ruta. En el momento que estoy satisfecho con los cambios y lo he comprobado las veces necesarias para estar seguro que no tiene errores, podemos ejecutar los comandos git que ya tenemos en nuestro haber.
![](Images/Day41_Git8.png)
Now we go back to GitHub to check the changes once more and then contribute back to the master project.
Ahora volvemos a GitHub para comprobar los cambios una vez más, no dejes de comprobarlo, los errores no vendrán por hacer las cosas mal, eso es normal, los errores vendrán por no comprobar las suficientes veces. En este punto, ya podemos contribuir al proyecto original.
Looks good.
Tiene buena pinta.
![](Images/Day41_Git9.png)
Now we can go back to the top of our forked repository for Kanister and we can see that we are 1 commit ahead of the kanisterio:master branch.
Ahora podemos volver a la parte superior de nuestro repositorio bifurcado para Kanister y podemos ver que estamos 1 commit por delante de la rama kanisterio:master.
![](Images/Day41_Git10.png)
Next, we hit that contribute button highlighted above. We see the option to "Open Pull Request"
A continuación, pulsamos el botón de contribuir resaltado arriba, la opción "Open Pull Request".
![](Images/Day41_Git11.png)
## Open a pull request
## Abrir un pull request
There is quite a bit going on in this next image, top left you can now see we are in the original or the master repository. then you can see what we are comparing and that is the original master and our forked repository. We then have a create pull request button which we will come back to shortly. We have our single commit but if this was more changes you might have multiple commits here. then we have the changes we have made in the readme.mdfile.
Atento, en la siguiente imagen hay bastantes cosas sucediendo, arriba a la izquierda puedes ver que estamos en el repositorio original master. Luego puedes ver lo que estamos comparando y que es el repositorio original y nuestro repositorio bifurcado. A continuación, tenemos un botón de crear pull request al que vamos a volver en breve. Tenemos nuestra único commit, pero si se tratara de más cambios se podrían ver todos los commits aquí. Vemos los cambios realizados en readme.md.
![](Images/Day41_Git12.png)
We have reviewed the above changes and we are ready to create a pull request by hitting the green button.
Hemos revisado los cambios anteriores y estamos listos para crear un pull request dándole al botón verde.
Then depending on how the maintainer of a project has set out their Pull Request functionality on their repository you may or may not have a template that gives you pointers on what the maintainer wants to see.
Entonces, dependiendo de cómo el mantenedor de un proyecto ha establecido su funcionalidad Pull Request, puede o no tener una plantilla que le da indicaciones sobre lo que el mantenedor quiere ver.
This is again where you want to make a meaningful description of what you have done, clear and concise but with enough detail. You can see I have made a simple change overview and I have ticked documentation.
Aquí es donde puedes hacer una descripción significativa de lo que has hecho, clara y concisa, pero con suficiente detalle. Puedes ver que he hecho un simple resumen de cambios y he marcado documentación.
![](Images/Day41_Git13.png)
## Create a pull request
## Crear un pull request
We are now ready to create our pull request. After hitting the "Create Pull Request" at the top of the page you will get a summary of your pull request.
Ya estamos listos para crear nuestro pull request. Después de pulsar "Create Pull Request" en la parte superior de la página obtendrás un resumen de tu pull request.
![](Images/Day41_Git14.png)
Scrolling down you are likely to see some automation taking place, in this instance, we require a review and some checks are taking place. We can see that Travis CI is in progress and a build has started and this will check our update, making sure that before anything is merged we are not breaking things with our additions.
Desplazándote hacia abajo es probable que veas que sucede alguna automatización, en este caso, requerimos una revisión y algunas comprobaciones que se están llevando a cabo. Podemos ver que Travis CI está en progreso y una construcción ha comenzado y esto comprobará nuestra actualización, asegurándose de que no estamos rompiendo nada con nuestras adiciones antes de que se fusione.
![](Images/Day41_Git15.png)
Another thing to note here is that the red in the screenshot above, can look a little daunting and look as if you have made mistakes! Don't worry you have not broken anything, my biggest tip here is this process is there to help you and the maintainers of the project. If you have made a mistake at least from my experience the maintainer will contact and advise on what to do next.
Otra cosa a tener en cuenta aquí es que el rojo en la captura de pantalla anterior, puede parecer un poco desalentador, parece como si hubieras cometido errores. Nada más lejos, no te preocupes, no has roto nada, mi mayor consejo aquí es que este proceso está ahí para ayudarte a ti y a los mantenedores del proyecto. Si usted ha cometido un error, al menos desde mi experiencia, el mantenedor se pondrá en contacto y le aconsejará sobre qué hacer a continuación.
This pull request is now public for everyone to see [added Kanister presentation/resource #1237](https://github.com/kanisterio/kanister/pull/1237)
![](Images/Day41_Git16.png)
I am going to publish this before the merge and pull requests are accepted so maybe we can get a little prize for anyone that is still following along and can add a picture of the successful PR?
Este pull request es ahora público para que todo el mundo lo vea: [added Kanister presentation/resource #1237](https://github.com/kanisterio/kanister/pull/1237)
1. Fork this repository to your own GitHub account
2. Add your picture and possibly text
3. Push the changes to your forked repository
4. Create a PR that I will see and approve.
5. I will think of some sort of prize
Con esto terminamos nuestro repaso a Git y GitHub. A continuación nos sumergiremos en los contenedores, que comienza con una visión general de cómo y por qué contenedores y también una mirada a la virtualización y cómo hemos llegado hasta aquí.
This then wraps up our look into Git and GitHub, next we are diving into containers which starts with a big picture look into how, and why containers and also a look into virtualisation and how we got here.
## Resources
## Recursos
- [Learn GitLab in 3 Hours | GitLab Complete Tutorial For Beginners](https://www.youtube.com/watch?v=8aV5AxJrHDg)
- [BitBucket Tutorials Playlist](https://www.youtube.com/watch?v=OMLh-5O6Ub8&list=PLaD4FvsFdarSyyGl3ooAm-ZyAllgw_AM5)
@ -123,5 +111,13 @@ This then wraps up our look into Git and GitHub, next we are diving into contain
- [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)
- [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 42](day42.md)
Nos vemos en el [Día 42](day42.md)

View File

@ -1,128 +1,129 @@
## The Big Picture: Containers
## El panorama: Contenedores
We are now starting the next section and this section is going to be focused on containers in particular we are going to be looking into Docker getting into some of the key areas to understand more about Containers.
Empezamos nueva sección en la que nos centraremos en los contenedores. En particular vamos a mirar Docker para entender algunas claves de los contenedores.
I will also be trying to get some hands-on here to create the container that we can use during this section but also in future sections later on in the challenge.
Pasaremos por un poco de práctica para crear el contenedor que utilizaremos durante esta sección y en futuras secciones del desafío.
As always this first post is going to be focused on the big picture of how we got here and what it all means.
Como siempre, este primer post se va a centrar en el panorama general de cómo hemos llegado hasta aquí y lo que todo esto significa.
#History of platforms and application development
#do we want to talk about Virtualisation & Containerisation
### ¿Por qué otra forma de ejecutar aplicaciones?
### Why another way to run applications?
Lo primero que tenemos que plantearnos es por qué necesitamos otra forma de ejecutar software o aplicaciones. La elección es grande, podemos ejecutar nuestras aplicaciones de muchas formas diferentes, por ejemplo, podríamos ver las aplicaciones desplegadas en hardware físico con un sistema operativo y una sola aplicación desplegada allí, y podríamos verlas en máquina virtual o instancias IaaS basadas en la nube ejecutando nuestra aplicación, que luego se integran en una base de datos de nuevo en una MV o como PaaS ofreciendo en la nube pública. O, como vamos a ver, podemos ver nuestras aplicaciones ejecutándose en contenedores.
The first thing we have to take a look at is why do we need another way to run our software or applications? Well it is just that choice is great, we can run our applications in many different forms, we might see applications deployed on physical hardware with an operating system and a single application deployed there, and we might see the virtual machine or cloud-based IaaS instances running our application which then integrate into a database again in a VM or as PaaS offering in the public cloud. Or we might see our applications running in containers.
Ninguna de las opciones anteriores es incorrecta o correcta, pero cada una tiene sus razones para escogerla y seguramente ninguna de ellas desaparecezca. He visto una gran cantidad de contenido sobre Contenedores vs Máquinas Virtuales y realmente no debería haber un argumento, ya que son como argumentos de manzanas vs peras en el que ambos son frutas (formas de ejecutar nuestras aplicaciones), pero no son lo mismo.
None of the above options is wrong or right, but they each have their reasons to exist and I also strongly believe that none of these is going away. I have seen a lot of content that walks into Containers vs Virtual Machines and there really should not be an argument as that is more like apples vs pears argument where they are both fruit (ways to run our applications) but they are not the same.
También diría que si estás empezando y estás desarrollando una aplicación deberías inclinarte hacia los contenedores, más adelante lo veremos en detalle pero en resumen se trata de eficiencia, velocidad y tamaño. Pero esto tiene un precio, si no tienes ni idea de contenedores va a ser una curva de aprendizaje demasiado inclinada, te obligará a entender el por qué y entrar en esta mentalidad. Si has desarrollado tus aplicaciones de una forma particular o no estás en un entorno totalmente nuevo, puede que tengas que enfrentarte a más problemas incluso antes de considerar los contenedores.
I would also say that if you were starting and you were developing an application you should lean towards containers simply because we will get into some of these areas later, but it's about efficiency, speed and size. But that also comes with a price, if you have no idea about containers then it's going to be a learning curve to force yourself to understand the why and get into that mindset. If you have developed your applications a particular way or you are not in a greenfield environment then you might have more pain points to deal with before even considering containers.
We have many different choices then when it comes to downloading a given piece of software, there are a variety of different operating systems that we might be using. And specific instructions for what we need to do to install our applications.
Tenemos muchas opciones diferentes a la hora de descargar un determinado software, hay una variedad de sistemas operativos diferentes que podríamos utilizar. E instrucciones específicas sobre lo que tenemos que hacer para instalar nuestras aplicaciones.
![](Images/Day42_Containers1.png)
More and more recently I am finding that the applications we might have once needed a full server OS, A VM, Physical or cloud instance are now releasing container-based versions of their software. I find this interesting as this opens the world of containers and then Kubernetes to everyone and not just a focus on application developers.
Cada vez nos encontramos más que las aplicaciones que una vez podrían haber necesitado un sistema operativo de servidor completo (una MV, instancia física o en la nube), ahora están lanzando versiones su software basadas en contenedores. Es interesante ya que esto abre las posibilidades de los contenedores y de Kubernetes a todo el mundo, y no sólo un enfoque en los desarrolladores de aplicaciones.
![](Images/Day42_Containers2.png)
As you can probably tell as I have said before, I am not going to advocate that the answer is containers, what's the question! But I would like to discuss how this is another option for us to be aware of when we deploy our applications.
Podrás deducir por lo que se ha dicho antes que no se va defender los contenedores como el mejor sistema para desplegar aplicaciones, pero desde luego existe el espacio para el debate.
![](Images/Day42_Containers4.png)
We have had container technology for a long time, so why now over the last say 10 years has this become popular, I would say even more popular in the last 5. We have had containers for decades. It comes down to the challenge of containers or should I say images as well, to how we distribute our software, because if we just have container technology, then we still will have many of the same problems we've had with software management.
Hemos tenido la tecnología de contenedores durante mucho tiempo, así que ¿por qué en los últimos 10 años se ha hecho tan popular? Diría que incluso mucho más populares en los últimos 5.
If we think about Docker as a tool, the reason that it took off, is because of the ecosystem of images that are easy to find and use. Simple to get on your systems and get up and running. A major part of this is consistency across the entire space, of all these different challenges that we face with software. It doesn't matter if it's MongoDB or nodeJS, the process to get either of those up and running will be the same. The process to stop either of those is the same. All of these issues will still exist, but the nice thing is, when we bring good container and image technology together, we now have a single set of tools to help us tackle all of these different problems. Some of those issues are listed below:
Hemos tenido contenedores durante décadas. ¿Se reduce al desafío de los contenedores o debería decir imágenes también? Porque si sólo tenemos la tecnología de contenedores, entonces todavía tendremos muchos de los mismos problemas que hemos tenido con la gestión de software.
- We first have to find software on the internet.
- We then have to download this software.
- Do we trust the source?
- Do we then need a license? Which License?
- Is it compatible with different platforms?
- What is the package? binary? Executable? Package manager?
- How do we configure the software?
- Dependencies? Did the overall download have us covered or do we need them as well?
- Dependencies of Dependencies?
- How do we start the application?
- How do we stop the application?
- Will it auto-restart?
- Start on boot?
- Resource conflicts?
- Conflicting libraries?
- Port Conflicts
- Security for the software?
- Software updates?
- How can I remove the software?
Si pensamos en Docker como una herramienta, la razón por la que despegó es al ecosistema de imágenes que son fáciles de conseguir y de poner en marcha. Una parte importante de esto es la coherencia en todo el espacio, de todos estos diferentes desafíos que enfrentamos con el software. No importa si es MongoDB o nodeJS, el proceso para poner en marcha cualquiera de ellos será el mismo. El proceso para detener cualquiera de ellos es el mismo. Todos estos problemas seguirán existiendo, pero lo bueno es que, cuando unimos una buena tecnología de contenedores e imágenes conseguiremos un único conjunto de herramientas para ayudarnos a abordar todos estos problemas diferentes. Algunos de esos problemas son:
We can split the above into 3 areas of the complexity of the software that containers and images do help with these.
- Primero tenemos que encontrar software en Internet.
- Luego tenemos que descargarlo.
- ¿Confiamos en la fuente?
- ¿Necesitamos una licencia? ¿Qué licencia?
- ¿Es compatible con diferentes plataformas?
- ¿Cuál es el paquete? ¿Binario? ¿Ejecutable? ¿Gestor de paquetes?
- ¿Cómo se configura el software?
- ¿Dependencias? ¿La descarga general nos ha cubierto o también las necesitamos?
- ¿Dependencias de dependencias?
- ¿Cómo iniciamos la aplicación?
- ¿Cómo detenemos la aplicación?
- ¿Se reiniciará automáticamente?
- ¿Se iniciará al arrancar?
- ¿Conflictos de recursos?
- ¿Conflictos de librerías?
- Conflictos de puertos
- ¿Seguridad del software?
- ¿Actualizaciones del software?
- ¿Cómo puedo eliminar el software?
| Distribution | Installation | Operation |
| ------------ | ------------- | ------------------ |
| Find | Install | Start |
| Download | Configuration | Security |
| License | Uninstall | Ports |
| Package | Dependencies | Resource Conflicts |
| Trust | Platform | Auto-Restart |
| Find | Libraries | Updates |
Podemos dividir lo anterior en 3 áreas de la complejidad del software que los contenedores y las imágenes ayudan con estos.
Containers and images are going to help us remove some of these challenges that we have with possibly other software and applications.
| Distribución | Instalación | Funcionamiento |
| ------------ | -------------- | ------------------- |
| Buscar | Instalar | Iniciar |
| Descargar | Configuración | Seguridad |
| Licencia | Desinstalación | Puertos |
| Paquete | Dependencias | Conflictos Recursos |
| Confianza | Plataforma | Reinicio automático |
| Buscar | Bibliotecas | Actualizaciones |
At a high level we could move installation and operation into the same list, Images are going to help us from a distribution point of view and containers help with the installation and operations.
Los contenedores y las imágenes nos van a ayudar a eliminar algunos de estos retos que tenemos posiblemente con otro software y aplicaciones.
Ok, probably sounds great and exciting but we still need to understand what is a container and now I have mentioned images so let's cover those areas next.
En un alto nivel podríamos mover la instalación y el funcionamiento en la misma lista, las imágenes nos van a ayudar desde el punto de vista de la distribución y los contenedores ayudan con la instalación y las operaciones.
Another thing you might have seen a lot when we talk about Containers for software development is the analogy used alongside shipping containers, shipping containers are used to ship various goods across the seas using large vessels.
Ok, probablemente suena muy bien y emocionante, pero todavía tenemos que entender lo que es un contenedor y ahora he mencionado imágenes así que vamos a verlo a continuación.
Otra cosa que habrás visto a menudo cuando hablamos de contenedores para el desarrollo de software es la analogía utilizada con los contenedores marítimos, los contenedores marítimos se utilizan para transportar diversas mercancías a través de los mares utilizando grandes buques.
![](Images/Day42_Containers5.png)
What does this have to do with our topic of containers? Think about the code that software developers write, how can we ship that particular code from one machine to another machine?
¿Qué tiene que ver con nuestro tema de los contenedores? Piensa en el código que escriben los desarrolladores de software, ¿cómo podemos enviar ese código concreto de una máquina a otra?
If we think about what we touched on before about software distribution, installation and operations but now we start to build this out into an environment visual. We have hardware and an operating system where you will run multiple applications. For example, nodejs has certain dependencies and needs certain libraries. If you then want to install MySQL then it needs its required libraries and dependencies. Each software application will have its library and dependency. We might be massively lucky and not have any conflicts between any of our applications where specific libraries and dependencies are clashing causing issues but the more applications the more chance or risk of conflicts. However, this is not about that one deployment when everything fixes your software applications are going to be updated and then we can also introduce these conflicts.
Si pensamos en lo que hemos tocado antes sobre la distribución de software, instalación y operaciones, pero ahora empezamos a construir esto en un entorno visual. Tenemos hardware y un sistema operativo donde se ejecutarán múltiples aplicaciones. Por ejemplo, nodejs tiene ciertas dependencias y necesita ciertas bibliotecas. Si a continuación, desea instalar MySQL entonces necesita sus bibliotecas y sus dependencias propias. Cada aplicación de software tendrá sus bibliotecas y dependencias. Podríamos tener mucha suerte y no tener ningún conflicto entre cualquiera de nuestras aplicaciones donde las bibliotecas y dependencias específicas están chocando causando problemas, pero cuantas más aplicaciones más posibilidades o riesgo de conflictos. Sin embargo, se trata de que un despliegue se producirá muchas veces, y no puede esperar a que todo este arreglado, porque en cada actualización se podrían introducir estos conflictos.
![](Images/Day42_Containers6.png)
Containers can help solve this problem. Containers help **build** your application, **ship** the application, **deploy** and **scale** these applications with ease independently. let's look at the architecture, you will have hardware and operating system then on top of it you will have a container engine like docker which we will cover later. The container engine software helps create containers that package the libraries and dependencies along with it so that you can move this container seamlessly from one machine to another machine without worrying about the libraries and dependencies since they come as a part of a package which is nothing but the container so you can have different containers this container can be moved across the systems without worrying about the underlying dependencies that the application
needs to run because everything the application needs to run is packaged as
a container that you can move.
Los contenedores pueden ayudar a resolver este problema. Los contenedores ayudan a **construir**, a **enviar**, a **desplegar** y a **escalar** estas aplicaciones con facilidad de forma independiente. echemos un vistazo a la arquitectura, tendrás hardware y sistema operativo y luego encima tendrás un motor de contenedores como docker que veremos en breve. El software de motor de contenedores ayuda a crear contenedores que empaquetan las bibliotecas y dependencias junto con él para que pueda mover este contenedor sin problemas de una máquina a otra sin preocuparse por las bibliotecas y dependencias, ya que vienen como parte de un paquete en el contenedor. Con lo cual, se puede mover a través de los sistemas sin preocuparse por las dependencias subyacentes que la aplicación necesita para funcionar.
![](Images/Day42_Containers7.png)
### The advantages of these containers
### Las ventajas de estos contenedores
- Containers help package all the dependencies within the container and
isolate it.
- Los contenedores ayudan a empaquetar todas las dependencias dentro del contenedor y aislarlas.
- It is easy to manage the containers
- Es fácil gestionar.
- The ability to move from one system to another.
- Se puede pasar de un sistema a otro.
- Containers help package the software and you can easily ship it without any duplicate efforts
- Los contenedores ayudan a empaquetar el software y se puede enviar fácilmente sin duplicar esfuerzos.
- Containers are easily scalable.
- Los contenedores son fácilmente escalables.
Using containers you can scale independent containers and use a load balancer
or a service which helps split the traffic and you can scale the applications horizontally. Containers offer a lot of flexibility and ease in how you manage your applications
Usando contenedores puedes escalar contenedores independientes y usar un equilibrador de carga
o un servicio que ayude a dividir el tráfico y puedas escalar las aplicaciones horizontalmente. Los contenedores ofrecen mucha flexibilidad y facilidad a la hora de gestionar las aplicaciones.
### What is a container?
### ¿Qué es un contenedor?
When we run applications on our computer, this could be the web browser or VScode that you are using to read this post. That application is running as a process or what is known as a process. On our laptops or systems, we tend to run multiple applications or as we said processes. When we open a new application or click on the application icon this is an application we would like to run, sometimes this application might be a service that we just want to run in the background, our operating system is full of services that are running in the background providing you with the user experience you get with your system.
Cuando ejecutamos aplicaciones en nuestro ordenador, podría ser en el navegador o en el VScode que quizá estés utilizando para leer este post, esa aplicación se ejecuta como un proceso. En nuestros portátiles o sistemas tendemos a ejecutar múltiples aplicaciones o, como hemos dicho, procesos. Cuando abrimos una nueva aplicación o hacemos clic en el icono de la aplicación, a veces podría ser un servicio que sólo queremos ejecutar en segundo plano, nuestro sistema operativo está lleno de servicios que se ejecutan en segundo plano y que proporcionan la experiencia de usuario final.
That application icon represents a link to an executable somewhere on your file system, the operating system then loads that executable into memory. Interestingly, that executable is sometimes referred to as an image when we're talking about a process.
Ese icono de aplicación representa un enlace a un ejecutable en algún lugar de tu sistema de archivos, el sistema operativo entonces carga ese ejecutable en la memoria. Curiosamente, a veces nos referimos a ese ejecutable como una imagen cuando hablamos de un proceso.
Containers are processes, A container is a standard unit of software that packages up code and all its dependencies so the application runs quickly and reliably from one computing environment to another.
Un contenedor es una unidad estándar de software que empaqueta el código y todas sus dependencias para que la aplicación se ejecute de forma rápida y fiable de un entorno informático a otro como lo hacen las aplicaciones.
Containerised software will always run the same, regardless of the infrastructure. Containers isolate software from its environment and ensure that it works uniformly despite differences for instance between development and staging.
El software en contenedores siempre se ejecutará igual, independientemente de la infraestructura. Los contenedores aíslan el software en su entorno mínimo viable y garantizan que funcione de manera uniforme a pesar de las diferencias, por ejemplo, entre el desarrollo y la puesta en escena.
I mentioned images in the last section when it comes to how and why containers and images combined made containers popular in our ecosystem.
He mencionado las imágenes en la última sección cuando se trata de cómo y por qué la combinación de contenedores e imágenes ha hecho que los contenedores sean populares en nuestro ecosistema.
### What is an Image?
### ¿Qué es una imagen?
A container image is a lightweight, standalone, executable package of software that includes everything needed to run an application: code, runtime, system tools, system libraries and settings. Container images become containers at runtime.
Una imagen de contenedor es un paquete de software ligero, independiente y ejecutable que incluye todo lo necesario para ejecutar una aplicación: código, tiempo de ejecución, herramientas del sistema, bibliotecas del sistema y configuraciones. Las imágenes de contenedor se convierten en contenedores en tiempo de ejecución.
## Resources
## Recursos
- [TechWorld with Nana - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=3c-iBn73dDE)
- [Programming with Mosh - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=pTFZFxd4hOI)
- [Docker Tutorial for Beginners - What is Docker? Introduction to Containers](https://www.youtube.com/watch?v=17Bl31rlnRM&list=WL&index=128&t=61s)
- [Introduction to Container By Red Hat](https://www.redhat.com/en/topics/containers)
- [En español] En los [apuntes](https://vergaracarmona.es/apuntes/) del traductor:
- [Preparación de entorno de pruebas local para docker](https://vergaracarmona.es/preparacion-de-entorno-de-pruebas-local-para-docker/)
- [Uso básico de docker](https://vergaracarmona.es/uso-basico-de-docker/)
- [Una breve historia sobre contenedores](https://vergaracarmona.es/breve-historia-de-contenedores/)
- [Desplegar con docker-compose los servicios Traefik y Portainer](https://vergaracarmona.es/desplegar-con-docker-compose-los-servicios-traefik-y-portainer/)
See you on [Day 43](day43.md)
Nos vemos en el [Día 43](day43.md)

View File

@ -1,62 +1,67 @@
## What is Docker & Getting installed
## Qué es Docker y cómo instalarlo
In the previous post, I mentioned Docker at least once and that is because Docker is innovative in making containers popular even though they have been around for such a long time.
En el post anterior, he mencionado Docker al menos una vez y eso es porque Docker es el culpable en gran parte de la popularización de los contenedores, a pesar de que han existido desde hace mucho tiempo.
We are going to be using and explaining docker here but we should also mention the [Open Container Initiative (OCI)](https://www.opencontainers.org/) which is an industry standards organization that encourages innovation while avoiding the danger of vendor lock-in. Thanks to the OCI, we have a choice when choosing a container toolchain, including Docker, [CRI-O](https://cri-o.io/), [Podman](http://podman.io/), [LXC](https://linuxcontainers.org/), and others.
Vamos a utilizar y explicar un poco Docker, pero también debemos mencionar la [Open Container Initiative (OCI)](https://www.opencontainers.org/), que es una organización de estándares de la industria que fomenta la innovación, evitando el peligro de la dependencia del proveedor. Gracias a la OCI, tenemos donde elegir entre las herramientas de contenedores, incluyendo Docker, [CRI-O](https://cri-o.io/), [Podman](http://podman.io/), [LXC](https://linuxcontainers.org/), entre otros.
Docker is a software framework for building, running, and managing containers. The term "docker" may refer to either the tools (the commands and a daemon) or the Dockerfile file format.
Docker es un framework de software para construir, ejecutar y gestionar contenedores. El término "docker" puede referirse tanto a las herramientas (los comandos y un daemon) como al formato de archivo Dockerfile.
We are going to be using Docker Personal here which is free (for education and learning). This includes all the essentials that we need to cover to get a good foundation of knowledge of containers and tooling.
Utilizaremos Docker Personal, que es gratuito (para la educación y el aprendizaje). Esto incluye todo lo esencial que necesitamos para obtener una buena base de conocimientos de los contenedores y herramientas.
It is probably worth breaking down some of the "docker" tools that we will be using and what they are used for. The term docker can be referring to the docker project overall, which is a platform for devs and admins to develop, ship and run applications. It might also be a reference to the docker daemon process running on the host which manages images and containers also called Docker Engine.
Probablemente vale la pena desglosar algunas de las herramientas "docker" para saber por qué se utilizan. El término docker puede referirse al proyecto docker en general, que es una plataforma para que los desarrolladores y administradores desarrollen, envíen y ejecuten aplicaciones. También puede ser una referencia al daemon Docker que se ejecuta en el host que gestiona las imágenes y contenedores también llamado Docker Engine.
### Docker Engine
Docker Engine is an open-source containerization technology for building and containerizing your applications. Docker Engine acts as a client-server application with:
Docker Engine es una tecnología de contenerización de código abierto para construir y contenerizar tus aplicaciones. Docker Engine actúa como una aplicación cliente-servidor con:
- A server with a long-running daemon process dockerd.
- APIs specify interfaces that programs can use to talk to and instruct the Docker daemon.
- A command line interface (CLI) client docker.
- Un servidor con un proceso demonio de larga ejecución dockerd.
- Las API especifican interfaces que los programas pueden utilizar para hablar con el demonio Docker y darle instrucciones.
- Una interfaz de línea de comandos (CLI) docker cliente.
The above was taken from the official Docker documentation and the specific [Docker Engine Overview](https://docs.docker.com/engine/)
Lo anterior fue tomado de la documentación oficial de Docker y el específico [Docker Engine Overview](https://docs.docker.com/engine/)
### Docker Desktop
We have a docker desktop for both Windows and macOS systems. An easy-to-install, lightweight docker development environment. A native OS application that leverages virtualisation capabilities on the host operating system.
Disponemos de un Docker Desktop para sistemas Windows y macOS. Un entorno de desarrollo docker ligero y fácil de instalar. Una aplicación nativa del sistema operativo que aprovecha las capacidades de virtualización en el sistema operativo anfitrión. Nadie lo utiliza, pero es una buena opción para comenzar.
Its the best solution if you want to build, debug, test, package, and ship Dockerized applications on Windows or macOS.
Puedes construir, depurar, probar, empaquetar y enviar aplicaciones Dockerizadas en Windows o macOS.
On Windows, we can also take advantage of WSL2 and Microsoft Hyper-V. We will cover some of the WSL2 benefits as we go through.
En Windows, también podemos aprovechar WSL2 y Microsoft Hyper-V. Veremos algunas de las ventajas de WSL2 a medida que avancemos, ya que como Windows no llega lo mejor es utilizar las opciones Linux.
Because of the integration with hypervisor capabilities on the host operating system docker provides the ability to run your containers with Linux Operating systems.
Debido a la difícil integración con las capacidades del hipervisor en el sistema operativo anfitrión, docker proporciona la capacidad de ejecutar sus contenedores con sistemas operativos Linux que no dan tantos problemas.
### Docker Compose
Docker compose is a tool that allows you to run more complex apps over multiple containers. With the benefit of being able to use a single file and command to spin up your application.
Docker compose es una herramienta que te permite ejecutar aplicaciones más complejas sobre múltiples contenedores. Con la ventaja de ser capaz de utilizar un único archivo y comando para hacer girar su aplicación. Es el principio de la orquestación de contenedores, un concepto que tendremos que interiorizar para dejar de tratar a nuestras máquinas como mascotas y comenzar a verlas como ganado.
### Docker Hub
A centralised resource for working with Docker and its components. Most commonly known as a registry to host docker images. But there are a lot of additional services here which can be used in part with automation or integrated into GitHub as well as security scanning.
Un recurso centralizado para trabajar con Docker y sus componentes, un registro de imágenes que nos facilitará mucho la existencia. Hay un montón de servicios adicionales que pueden ser utilizados en parte con la automatización o integrados en GitHub, así como el escaneo de seguridad.
### Dockerfile
A dockerfile is a text file that contains commands you would normally execute manually to build a docker image. Docker can build images automatically by reading the instructions we have in our dockerfile.
Un dockerfile es un archivo de texto que contiene comandos que también se pueden ejecutar manualmente para construir una imagen docker. Docker puede construir imágenes automáticamente leyendo las instrucciones que tenemos en nuestro dockerfile gracias al lenguaje declarativo.
## Installing Docker Desktop
## Instalando Docker Desktop
The [docker documenation](https://docs.docker.com/engine/install/) is amazing and if you are only just diving in then you should take a look and have a read-through. We will be using Docker Desktop on Windows with WSL2. I had already run through the installation on the machine we are using here.
La [documenación de Docker](https://docs.docker.com/engine/install/) es asombrosa y si quieres aprender de verdad deberías echarle un vistazo y tenerla como referencia. Vamos a utilizar Docker Desktop en Windows con WSL2. Ya he ejecutado la instalación en la máquina que estamos utilizando.
![](Images/Day43_Containers1.png)
Take note before you go ahead and install at the system requirements, [Install Docker Desktop on Windows](https://docs.docker.com/desktop/windows/install/) if you are using macOS including the M1-based CPU architecture you can also take a look at [Install Docker Desktop on macOS](https://docs.docker.com/desktop/mac/install/)
Toma nota antes de seguir adelante en los requisitos del sistema antes de [Instalar Docker Desktop en Windows](https://docs.docker.com/desktop/windows/install/). Si estás usando macOS, inclusive para la arquitectura de CPU basada en M1, puedes echar un vistazo a [Instalar Docker Desktop en macOS](https://docs.docker.com/desktop/mac/install/). Linux también puede ejecutar Docker Desktop virtualizado: https://docs.docker.com/desktop/install/linux-install/
I will run through the Docker Desktop installation for Windows on another Windows Machine and log the process down below.
Voy a ejecutar a través de la instalación de Docker Desktop para Windows en otra máquina Windows y registrar el proceso de abajo.
## Resources
## Recursos
- [TechWorld with Nana - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=3c-iBn73dDE)
- [Programming with Mosh - Docker Tutorial for Beginners](https://www.youtube.com/watch?v=pTFZFxd4hOI)
- [Docker Tutorial for Beginners - What is Docker? Introduction to Containers](https://www.youtube.com/watch?v=17Bl31rlnRM&list=WL&index=128&t=61s)
- [WSL 2 with Docker getting started](https://www.youtube.com/watch?v=5RQbdMn04Oc)
- [En español] En los [apuntes](https://vergaracarmona.es/apuntes/) del traductor:
- [Preparación de entorno de pruebas local para docker](https://vergaracarmona.es/preparacion-de-entorno-de-pruebas-local-para-docker/)
- [Uso básico de docker](https://vergaracarmona.es/uso-basico-de-docker/)
- [Una breve historia sobre contenedores](https://vergaracarmona.es/breve-historia-de-contenedores/)
- [Desplegar con docker-compose los servicios Traefik y Portainer](https://vergaracarmona.es/desplegar-con-docker-compose-los-servicios-traefik-y-portainer/)
See you on [Day 44](day44.md)
Nos vemos en el [Día 44](day44.md)