Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 20 additions & 20 deletions book/07-git-tools/sections/searching.asc
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
[[_searching]]
=== Searching
=== Búsqueda

With just about any size codebase, you'll often need to find where a function is called or defined, or find the history of a method. Git provides a couple of useful tools for looking through the code and commits stored in it's database quickly and easily. We'll go through a few of them.
Con casi cualquier código base de tamaño, a menudo necesitarás encontrar dónde se nombra o define una función, o encontrar el historial de un método. Git proporciona un par de herramientas útiles para la búsqueda a lo largo del código y de los cambios consignados permanentemente en su base de datos rápida y fácilmente. Veremos algunos de ellos.

[[_git_grep]]
==== Git Grep

Git ships with a command called `grep` that allows you to easily search through any committed tree or the working directory for a string or regular expression. For these examples, we'll look through the Git source code itself.
Git hace ship con un comando llamado "grep" que te permine buscar fácilmente a lo largo de cualquier árbol consignado permanentemente o de el directorio de trabajo para una cadena o expresión regular. Para estos ejemplos, miraremos a través de el propio código fuente de Git.

By default, it will look through the files in your working directory. You can pass `-n` to print out the line numbers where Git has found matches.
Por defecto, mirará a través de los archivos en tu directorio de trabajo. Puedes poner "-n" para resaltar los números de línea donde Git ha encontrado coincidencias.

[source,console]
----
Expand All @@ -25,9 +25,9 @@ git-compat-util.h:721:struct tm *git_gmtime_r(const time_t *, struct tm *);
git-compat-util.h:723:#define gmtime_r git_gmtime_r
----

There are a number of interesting options you can provide the `grep` command.
Hay una serie de opciones interesantes que puedes obtener del comando "grep".

For instance, instead of the previous call, you can have Git summarize the output by just showing you which files matched and how many matches there were in each file with the `--count` option:
Por ejemplo, en lugar de la llamada anterior, puedes tener que Git sintetiza la salida sólo con mostrate los archivos que coincideron y cuántas coincidencias hubo en cada archivo con la opción "--count":

[source,console]
----
Expand All @@ -39,7 +39,7 @@ date.c:2
git-compat-util.h:2
----

If you want to see what method or function it thinks it has found a match in, you can pass `-p`:
Si quieres ver qué método o función piensa que ha encontrado un emparejamiento, puedes poner "-p":

[source,console]
----
Expand All @@ -50,11 +50,11 @@ date.c=static int match_digit(const char *date, struct tm *tm, int *offset, int
date.c: if (gmtime_r(&time, tm)) {
----

So here we can see that `gmtime_r` is called in the `match_multi_number` and `match_digit` functions in the date.c file.
Así que aquí podemos ver que "gmtime_r" es nombrado en las funciones "match_multi_number" y "match_digit" en el archivo date.c.

You can also look for complex combinations of strings with the `--and` flag, which makes sure that multiple matches are in the same line. For instance, let's look for any lines that define a constant with either the strings ``LINK'' or ``BUF_MAX'' in them in the Git codebase in an older 1.8.0 version.
Puedes también ir tras combinaciones complejas de cadenas con la flag "--and", la que asegura que múltiples coincidencias están en la misma línea. Por ejemplo, busquemos líneas que definan una constante con cualquiera de las cadenas "LINK" o "BUF_MAX" en ellas en el código base de Git en una versión anterior a la 1.8.0.

Here we'll also use the `--break` and `--heading` options which help split up the output into a more readable format.
Aquí también usamos las opciones "--break" y "--heading", las que ayudan a dividiar la salida en formatos más fáciles de leer.

[source,console]
----
Expand All @@ -81,13 +81,13 @@ v1.8.0:zlib.c
31:#define ZLIB_BUF_MAX ((uInt) 1024 * 1024 * 1024) /* 1GB */
----

The `git grep` command has a few advantages over normal searching commands like `grep` and `ack`. The first is that it's really fast, the second is that you can search through any tree in Git, not just the working directory. As we saw in the above example, we looked for terms in an older version of the Git source code, not the version that was currently checked out.
El comando "git grep" tiene unas pocas ventajas sobre comandos de búsqueda normales como "grep" y "ack". La primera es que es realmente rápido, la segunda es que puedes buscar a lo largo de cualquier árbol en Git, no sólo el directorio de trabajo. Como vimos en el ejemplo anterior, buscamos términos en una versión anterior del código fuente de Git, no la versión actual.

==== Git Log Searching
==== Búsqueda Git Log

Perhaps you're looking not for **where** a term exists, but **when** it existed or was introduced. The `git log` command has a number of powerful tools for finding specific commits by the content of their messages or even the content of the diff they introduce.
Quizás no estás buscando **where** existe un término, sino **when** existió o fue introducido. El comando "git log" tiene una serie de heramientas poderosas para buscar commits específicos por el contenido de sus mensajes o incluso por el contenido del diff que ellos introducen.

If we want to find out for example when the `ZLIB_BUF_MAX` constant was originally introduced, we can tell Git to only show us the commits that either added or removed that string with the `-S` option.
Si queremos encontrar, por ejemplo, cuando la constante "ZLIB_BUF_MAX" fue introducida originalmente, podemos decirle a Git que sólo nos muestre los commits que agreagaron o eliminaros esa cadena con la opción "-S".

[source,console]
----
Expand All @@ -96,15 +96,15 @@ e01503b zlib: allow feeding more than 4GB in one go
ef49a7a zlib: zlib can only process 4GB at a time
----

If we look at the diff of those commits we can see that in `ef49a7a` the constant was introduced and in `e01503b` it was modified.
Si nos fijamos en los diff de esos commits, podemos ver que en la constante "ef49a7a" fue introducida y en "e01503b" fue modificada.

If you need to be more specific, you can provide a regular expression to search for with the `-G` option.
Si necesitas ser más específico, puedes proporcionar una expresicón regular para buscar con la opción "-G".

===== Line Log Search
===== Búsqueda de Línea Log

Another fairly advanced log search that is insanely useful is the line history search. This is a fairly recent addition and not very well known, but it can be really helpful. It is called with the `-L` option to `git log` and will show you the history of a function or line of code in your codebase.
Otro más o menos avanzado log de búsqueda que es increíblemente útil es la línea búsqueda en historial. Esta es una incorporación más o menos reciente y no muy conocida, pero puede ser realmente de ayuda. Es llamada con la opción "-L" a "git log" y te mostrará el historial de una función o línea de código en tu código base.

For example, if we wanted to see every change made to the function `git_deflate_bound` in the `zlib.c` file, we could run `git log -L :git_deflate_bound:zlib.c`. This will try to figure out what the bounds of that function are and then look through the history and show us every change that was made to the function as a series of patches back to when the function was first created.
Por ejemplo, si queríamos ver cada cambio hecho para la función "git_deflate_bound" en el archivo "zlib.c", podíamos ejecutar "git log -L :git_deflate_bound:zlib.c". Esto intentará resolver lo que son las raíces de esa función y luego buscar entre el historial y mostrarnos cada cambio que fue hecho a la función, como una serie de parches de vuelta a cuando la función fue creada primero.

[source,console]
----
Expand Down Expand Up @@ -144,4 +144,4 @@ diff --git a/zlib.c b/zlib.c
+
----

If Git can't figure out how to match a function or method in your programming language, you can also provide it a regex. For example, this would have done the same thing: `git log -L '/unsigned long git_deflate_bound/',/^}/:zlib.c`. You could also give it a range of lines or a single line number and you'll get the same sort of output.
Si Git no puede decifrar como emparejar una función o un método en tu lenguaje de programación, puedes proveerle tambien una expresión regular (regex). Por ejemplo, esto habría hecho lo mismo: "git log -L '/unsigned long git_deflate_bound/',/^}/:zlib.c". Podrías también darle un rango de líneas o un sólo número de línea y obtendrías el mismo tipo de salida.