En este breve artículo explico cómo visualizar desde línea de comandos los cambios introducidos por un commit en git.
Supongamos que estamos trabajando sobre un repositorio remoto compartido por varios desarrolladores, y hemos hecho git pull
para actualizar nuestra copia de trabajo y traer los cambios introducidos por el resto de los desarrolladores. Si hay nuevos cambios, en la salida del comando git pull
veremos los archivos que son modificados/actualizados y aquellos creados/eliminados.
Ahora bien, ¿de qué forma es posible ver exactamente cuales fueron las modificaciones realizadas sobre cada archivo? Es decir, ¿qué líneas se agregaron/modificaron/eliminaron sobre cada archivo?. Simple: recurriendo al comando git log
.
Veamos algunos ejemplos.
Ver los últimos x commits
Es posible indicar a git log
la cantidad de commits a visualizar pasando un número como parámetro:
root@linuxito:~/git.devuan/Upgrade-Install-Devuan# git log -3 commit c7a2335be9d8b966709d0310710f947fe42b7061 Author: g4570n <g4570nmb0x@linuxito.com> Date: Sat May 19 01:29:40 2018 +0200 An small typo correction on README.md commit e119e774caf54cb2ca72123b9ac05b3d2bc7004a Author: linuxitux <linuxito@linuxito.com> Date: Fri May 18 10:38:23 2018 -0400 Should say debootstrap instead of bootstrap commit 83b516f39010e011bf67e15bca07b01b759d19d7 Merge: 58e8ada 62bd568 Author: dev1fanboy <chillfan@linuxito.com> Date: Thu May 17 02:24:40 2018 +0200 Merge branch 'es' into 'master' Es See merge request !36
Ver los commits de los últimos x días:
También es posible filtrar por fecha, por ejemplo si queremos recuperar sólo los commits de los últimos 10 días:
root@linuxito:~/git.devuan/Upgrade-Install-Devuan# git log --since="10 days" commit c7a2335be9d8b966709d0310710f947fe42b7061 Author: g4570n <g4570nmb0x@linuxito.com> Date: Sat May 19 01:29:40 2018 +0200 An small typo correction on README.md commit e119e774caf54cb2ca72123b9ac05b3d2bc7004a Author: linuxitux <linuxito@linuxito.com> Date: Fri May 18 10:38:23 2018 -0400 Should say debootstrap instead of bootstrap
Ver los cambios introducidos por un commit
En las salidas anteriores, por cada commit se muestra el autor, fecha y descripción. Sin embargo no se muestra qué archivos fueron modificados, ni cuáles fueron las modificaciones.
A fin de poder visualizar las modificaciones realizadas sobre los archivos, es necesario generar el parche (patch
) correspondiente a cada commit. Para ello se debe recurrir a la opción -p
.
Por ejemplo, si deseamos ver las modificaciones introducidas por el último (-1
) commit:
root@linuxito:~/git.devuan/Upgrade-Install-Devuan# git log -p -1 commit c7a2335be9d8b966709d0310710f947fe42b7061 Author: g4570n <g4570nmb0x@linuxito.com> Date: Sat May 19 01:29:40 2018 +0200 An small typo correction on README.md diff --git a/es/README.md b/es/README.md index 9b093a7..d624d4a 100644 --- a/es/README.md +++ b/es/README.md @@ -26,7 +26,7 @@ instalación más mínima. ## Traducciones -Las traduciones están disponibles gracias al equipo de la wiki. +Las traducciones están disponibles gracias al equipo de la wiki. [Auf Deutsch lesen](https://git.devuan.org/dev1fanboy/Upgrade-Install-Devuan/tree/de/de/) **|** [Διαβάστε στα Ελληνικά]
En esta salida se observa que se ha modificado el archivo README.md
(desde una instancia "a" hacia otra "b"), y la línea:
Las traduciones están disponibles gracias al equipo de la wiki.
Se ha cambiado por:
Las traducciones están disponibles gracias al equipo de la wiki.
En definitiva se ha cambiado "traduciones" por "traducciones".
Seleccionar un commit por su descripción
Generalmente es posible seleccionar o filtrar commmits por fecha o cantidad. Para ello se recomienda ver las opciones --since
, --after
, --until
y --before
en la página de manual de git log
(man git-log
).
Sin embargo es posible seleccionar uno o varios commits según su descripción o autor. La opción --grep
permite filtrar commits de tal forma:
root@linuxito:~/git.devuan/Upgrade-Install-Devuan# git log --grep "An small typo correction" -p commit c7a2335be9d8b966709d0310710f947fe42b7061 Author: g4570n g4570n <g4570nmb0x@linuxito.com> Date: Sat May 19 01:29:40 2018 +0200 An small typo correction on README.md diff --git a/es/README.md b/es/README.md index 9b093a7..d624d4a 100644 --- a/es/README.md +++ b/es/README.md @@ -26,7 +26,7 @@ instalación más mínima. ## Traducciones -Las traduciones están disponibles gracias al equipo de la wiki. +Las traducciones están disponibles gracias al equipo de la wiki. [Auf Deutsch lesen](https://git.devuan.org/dev1fanboy/Upgrade-Install-Devuan/tree/de/de/) **|** [Διαβάστε στα Ελληνικά]
En este caso hemos obtenido los commits que contengan la cadena "An small typo correction", obteniendo sólo 1 resultado.
Listar los commits de forma compacta
Es posible listar los commits de forma compacta a través de la opción --pretty=oneline
:
root@linuxito:~/git.devuan/Upgrade-Install-Devuan# git log -5 --pretty=oneline c7a2335be9d8b966709d0310710f947fe42b7061 An small typo correction on README.md e119e774caf54cb2ca72123b9ac05b3d2bc7004a Should say debootstrap instead of bootstrap 83b516f39010e011bf67e15bca07b01b759d19d7 Merge branch 'es' into 'master' 58e8adaec684959af9ef5b380b8af9ef06ced0fe Merge branch 'it-credits' into 'master' c4ea836d62094aea904bd5a4ee5050b6f4e75973 Update devuan-install.md
Además de estos ejemplos git-log
tiene infinidad de posibilidades y permite obtener mucha más información de lo que se aprecia en una interfaz Web como GitHub o GitLab. Sin dudas todo desarrollador o administrador de sistemas debe, más que conocer, ser un experto en estas herramientas desde línea de comandos, las cuales abren un mundo de posibilidades en comparación de las herramientas GUI.
Recomiendo una pasada por la página de manual de git-log
(la cual tiene unas 1359 líneas en la versión 1.7.10.4
), al igual que por el resto de las páginas de manual de git
:
root@linuxito:~/git.devuan/Upgrade-Install-Devuan# apropos git- git-add (1) - Add file contents to the index git-am (1) - Apply a series of patches from a mailbox git-annotate (1) - Annotate file lines with commit information git-apply (1) - Apply a patch to files and/or to the index git-archive (1) - Create an archive of files from a named tree git-bisect (1) - Find by binary search the change that introduced a bug git-blame (1) - Show what revision and author last modified each line of a file git-branch (1) - List, create, or delete branches git-bundle (1) - Move objects and refs by archive git-cat-file (1) - Provide content or type and size information for repository objects git-check-attr (1) - Display gitattributes information git-check-ref-format (1) - Ensures that a reference name is well formed git-checkout (1) - Checkout a branch or paths to the working tree git-checkout-index (1) - Copy files from the index to the working tree git-cherry (1) - Find commits not merged upstream git-cherry-pick (1) - Apply the changes introduced by some existing commits git-clean (1) - Remove untracked files from the working tree git-clone (1) - Clone a repository into a new directory git-commit (1) - Record changes to the repository git-commit-tree (1) - Create a new commit object git-config (1) - Get and set repository or global options git-count-objects (1) - Count unpacked number of objects and their disk consumption git-credential-cache (1) - helper to temporarily store passwords in memory git-credential-cache--daemon (1) - temporarily store user credentials in memory git-credential-store (1) - helper to store credentials on disk git-daemon (1) - A really simple server for git repositories git-describe (1) - Show the most recent tag that is reachable from a commit git-diff (1) - Show changes between commits, commit and working tree, etc git-diff-files (1) - Compares files in the working tree and the index git-diff-index (1) - Compares content and mode of blobs between the index and repository git-diff-tree (1) - Compares the content and mode of blobs found via two tree objects git-difftool (1) - Show changes using common diff tools git-fast-export (1) - Git data exporter git-fast-import (1) - Backend for fast Git data importers git-fetch (1) - Download objects and refs from another repository git-fetch-pack (1) - Receive missing objects from another repository git-filter-branch (1) - Rewrite branches git-fmt-merge-msg (1) - Produce a merge commit message git-for-each-ref (1) - Output information on each ref git-format-patch (1) - Prepare patches for e-mail submission git-fsck (1) - Verifies the connectivity and validity of the objects in the database git-fsck-objects (1) - Verifies the connectivity and validity of the objects in the database git-gc (1) - Cleanup unnecessary files and optimize the local repository git-get-tar-commit-id (1) - Extract commit ID from an archive created using git-archive git-grep (1) - Print lines matching a pattern git-hash-object (1) - Compute object ID and optionally creates a blob from a file git-help (1) - display help information about git git-http-backend (1) - Server side implementation of Git over HTTP git-http-fetch (1) - Download from a remote git repository via HTTP git-http-push (1) - Push objects over HTTP/DAV to another repository git-imap-send (1) - Send a collection of patches from stdin to an IMAP folder git-index-pack (1) - Build pack index file for an existing packed archive git-init (1) - Create an empty git repository or reinitialize an existing one git-init-db (1) - Creates an empty git repository git-instaweb (1) - Instantly browse your working repository in gitweb git-log (1) - Show commit logs git-lost-found (1) - Recover lost refs that luckily have not yet been pruned git-ls-files (1) - Show information about files in the index and the working tree git-ls-remote (1) - List references in a remote repository git-ls-tree (1) - List the contents of a tree object git-mailinfo (1) - Extracts patch and authorship from a single e-mail message git-mailsplit (1) - Simple UNIX mbox splitter program git-merge (1) - Join two or more development histories together git-merge-base (1) - Find as good common ancestors as possible for a merge git-merge-file (1) - Run a three-way file merge git-merge-index (1) - Run a merge for files needing merging git-merge-one-file (1) - The standard helper program to use with git-merge-index git-merge-tree (1) - Show three-way merge without touching index git-mergetool (1) - Run merge conflict resolution tools to resolve merge conflicts git-mergetool--lib (1) - Common git merge tool shell scriptlets git-mktag (1) - Creates a tag object git-mktree (1) - Build a tree-object from ls-tree formatted text git-mv (1) - Move or rename a file, a directory, or a symlink git-name-rev (1) - Find symbolic names for given revs git-notes (1) - Add or inspect object notes git-p4 (1) - Import from and submit to Perforce repositories git-pack-objects (1) - Create a packed archive of objects git-pack-redundant (1) - Find redundant pack files git-pack-refs (1) - Pack heads and tags for efficient repository access git-parse-remote (1) - Routines to help parsing remote repository access parameters git-patch-id (1) - Compute unique ID for a patch git-peek-remote (1) - List the references in a remote repository git-prune (1) - Prune all unreachable objects from the object database git-prune-packed (1) - Remove extra objects that are already in pack files git-pull (1) - Fetch from and merge with another repository or a local branch git-push (1) - Update remote refs along with associated objects git-quiltimport (1) - Applies a quilt patchset onto the current branch git-read-tree (1) - Reads tree information into the index git-rebase (1) - Forward-port local commits to the updated upstream head git-receive-pack (1) - Receive what is pushed into the repository git-reflog (1) - Manage reflog information git-relink (1) - Hardlink common objects in local repositories git-remote (1) - manage set of tracked repositories git-remote-ext (1) - Bridge smart transport to external command. git-remote-fd (1) - Reflect smart transport stream back to caller git-remote-helpers (1) - Helper programs to interact with remote repositories git-remote-testgit (1) - Example remote-helper git-repack (1) - Pack unpacked objects in a repository git-replace (1) - Create, list, delete refs to replace objects git-repo-config (1) - Get and set repository or global options git-request-pull (1) - Generates a summary of pending changes git-rerere (1) - Reuse recorded resolution of conflicted merges git-reset (1) - Reset current HEAD to the specified state git-rev-list (1) - Lists commit objects in reverse chronological order git-rev-parse (1) - Pick out and massage parameters git-revert (1) - Revert some existing commits git-rm (1) - Remove files from the working tree and from the index git-send-pack (1) - Push objects over git protocol to another repository git-sh-i18n (1) - Git's i18n setup code for shell scripts git-sh-i18n--envsubst (1) - Git's own envsubst(1) for i18n fallbacks git-sh-setup (1) - Common git shell script setup code git-shell (1) - Restricted login shell for Git-only SSH access git-shortlog (1) - Summarize 'git log' output git-show (1) - Show various types of objects git-show-branch (1) - Show branches and their commits git-show-index (1) - Show packed archive index git-show-ref (1) - List references in a local repository git-stage (1) - Add file contents to the staging area git-stash (1) - Stash the changes in a dirty working directory away git-status (1) - Show the working tree status git-stripspace (1) - Remove unnecessary whitespace git-submodule (1) - Initialize, update or inspect submodules git-symbolic-ref (1) - Read and modify symbolic refs git-tag (1) - Create, list, delete or verify a tag object signed with GPG git-tar-tree (1) - Create a tar archive of the files in the named tree object git-unpack-file (1) - Creates a temporary file with a blob's contents git-unpack-objects (1) - Unpack objects from a packed archive git-update-index (1) - Register file contents in the working tree to the index git-update-ref (1) - Update the object name stored in a ref safely git-update-server-info (1) - Update auxiliary info file to help dumb servers git-upload-archive (1) - Send archive back to git-archive git-upload-pack (1) - Send objects packed back to git-fetch-pack git-var (1) - Show a git logical variable git-verify-pack (1) - Validate packed git archive files git-verify-tag (1) - Check the GPG signature of tags git-web--browse (1) - git helper script to launch a web browser git-whatchanged (1) - Show logs with difference each commit introduces git-write-tree (1) - Create a tree object from the current index
Bueno al final el artículo no fue muy breve y terminé mostrando cualquier otra cosa respecto a lo que dice el título. EMOSIDO ENGAÑADO.
Referencias