diff --git a/book/09-git-and-other-scms/sections/import-custom.asc b/book/09-git-and-other-scms/sections/import-custom.asc index b463ac59..80f983b7 100644 --- a/book/09-git-and-other-scms/sections/import-custom.asc +++ b/book/09-git-and-other-scms/sections/import-custom.asc @@ -1,18 +1,18 @@ [[_custom_importer]] -==== A Custom Importer +==== Un importador personalizado (((git commands, fast-import))) (((Importing, from others))) -If your system isn't one of the above, you should look for an importer online – quality importers are available for many other systems, including CVS, Clear Case, Visual Source Safe, even a directory of archives. -If none of these tools works for you, you have a more obscure tool, or you otherwise need a more custom importing process, you should use `git fast-import`. -This command reads simple instructions from stdin to write specific Git data. -It's much easier to create Git objects this way than to run the raw Git commands or try to write the raw objects (see <<_git_internals>> for more information). -This way, you can write an import script that reads the necessary information out of the system you're importing from and prints straightforward instructions to stdout. -You can then run this program and pipe its output through `git fast-import`. +Si su sistema no es uno de los anteriores, debe buscar un importador en línea: los importadores de calidad están disponibles para muchos otros sistemas, incluidos CVS, Clear Case, Visual Source Safe e incluso un directorio de archivos. +Si ninguna de estas herramientas funciona para usted, tiene una herramienta más oscura, o si no necesita un proceso de importación más personalizado, debe usar `git fast-import`. +Este comando lee instrucciones simples de stdin para escribir datos específicos de Git. +Es mucho más fácil crear objetos Git de esta manera que ejecutar los comandos Git sin formato o intentar escribir los objetos sin procesar (ver << _ git_internals >> para más información). +De esta forma, puede escribir un script de importación que lea la información necesaria del sistema desde el que está importando e imprima instrucciones sencillas para la salida estándar. +A continuación, puede ejecutar este programa y canalizar su salida a través de `git fast-import`. -To quickly demonstrate, you'll write a simple importer. -Suppose you work in `current`, you back up your project by occasionally copying the directory into a time-stamped `back_YYYY_MM_DD` backup directory, and you want to import this into Git. -Your directory structure looks like this: +Para demostrarlo rápidamente, escribirás un importador simple. +Supongamos que trabaja en `current`, hace una copia de seguridad de su proyecto copiando ocasionalmente el directorio en un directorio de copia de seguridad` back_YYYY_MM_DD` con marca de tiempo y quiere importarlo a Git. +Su estructura de directorios se vería así: [source,console] ---- @@ -24,18 +24,18 @@ back_2014_02_03 current ---- -In order to import a Git directory, you need to review how Git stores its data. -As you may remember, Git is fundamentally a linked list of commit objects that point to a snapshot of content. -All you have to do is tell `fast-import` what the content snapshots are, what commit data points to them, and the order they go in. -Your strategy will be to go through the snapshots one at a time and create commits with the contents of each directory, linking each commit back to the previous one. +Para importar un directorio de Git, necesita revisar cómo Git almacena sus datos. +Como recordarán, Git es fundamentalmente una lista vinculada de objetos de compromiso que apuntan a una instantánea del contenido. +Todo lo que tiene que hacer es decirle al `fast-import` qué son las instantáneas de su contenido, qué datos de los puntos de confirmaciones y el orden en que ingresarán. +Su estrategia será pasar a través de las instantáneas de a una por vez y crear compromisos con los contenidos de cada directorio, vinculando cada compromiso con el anterior. -As we did in <<_an_example_git_enforced_policy>>, we'll write this in Ruby, because it's what we generally work with and it tends to be easy to read. -You can write this example pretty easily in anything you're familiar with – it just needs to print the appropriate information to `stdout`. -And, if you are running on Windows, this means you'll need to take special care to not introduce carriage returns at the end your lines – git fast-import is very particular about just wanting line feeds (LF) not the carriage return line feeds (CRLF) that Windows uses. +Como hicimos en << _ an_example_git_enforced_policy >>, escribiremos esto en Ruby, porque es con lo que generalmente trabajamos y tiende a ser fácil de leer. +Puede escribir este ejemplo con bastante facilidad en cualquier cosa con la que esté familiarizado; solo necesita imprimir la información adecuada en `stdout`. +Y, si está ejecutando en Windows, esto significa que tendrá que tener especial cuidado de no presentar retornos de carrete al final de sus líneas - git fast-import es muy particular acerca de querer feed lines (LF) y no el carriage Return Line Feed (CRLF) que usa Windows. -To begin, you'll change into the target directory and identify every subdirectory, each of which is a snapshot that you want to import as a commit. -You'll change into each subdirectory and print the commands necessary to export it. -Your basic main loop looks like this: +Para comenzar, cambiará al directorio de destino e identificará cada subdirectorio, cada uno de los cuales es una instantánea que desea importar como una confirmación. +Cambiará a cada subdirectorio e imprimirá los comandos necesarios para exportarlo. +Su ciclo principal básico se ve así: [source,ruby] ---- @@ -54,17 +54,17 @@ Dir.chdir(ARGV[0]) do end ---- -You run `print_export` inside each directory, which takes the manifest and mark of the previous snapshot and returns the manifest and mark of this one; that way, you can link them properly. -``Mark'' is the `fast-import` term for an identifier you give to a commit; as you create commits, you give each one a mark that you can use to link to it from other commits. -So, the first thing to do in your `print_export` method is generate a mark from the directory name: +Ejecuta `print_export` dentro de cada directorio, que toma el manifiesto y la marca de la instantánea anterior y devuelve el manifiesto y la marca de este; de esa manera, puedes vincularlos adecuadamente. +`` Mark '' es el término `fast-import` para un identificador que le das a una confirmación; a medida que crea confirmaciones, le da a cada una una marca que puede usar para vincularla con otras confirmaciones. +Entonces, lo primero que debe hacer en su método `print_export` es generar una marca desde el nombre del directorio: [source,ruby] ---- mark = convert_dir_to_mark(dir) ---- -You'll do this by creating an array of directories and using the index value as the mark, because a mark must be an integer. -Your method looks like this: +Lo hará creando una matriz de directorios y utilizando el valor del índice como la marca, porque una marca debe ser un número entero. +Tu método se ve así: [source,ruby] ---- @@ -77,16 +77,16 @@ def convert_dir_to_mark(dir) end ---- -Now that you have an integer representation of your commit, you need a date for the commit metadata. -Because the date is expressed in the name of the directory, you'll parse it out. -The next line in your `print_export` file is +Ahora que tiene una representación entera de su confirmación, necesita una fecha para los metadatos de confirmación. +Como la fecha se expresa en el nombre del directorio, lo analizará. +La siguiente línea en su archivo `print_export` es [source,ruby] ---- date = convert_dir_to_date(dir) ---- -where `convert_dir_to_date` is defined as +donde `convert_dir_to_date` se define como [source,ruby] ---- @@ -101,17 +101,17 @@ def convert_dir_to_date(dir) end ---- -That returns an integer value for the date of each directory. -The last piece of meta-information you need for each commit is the committer data, which you hardcode in a global variable: +Eso devuelve un valor entero para la fecha de cada directorio. +La última parte de metainformación que necesita para cada confirmación es la información del confirmador, que se codifica en una variable global: [source,ruby] ---- $author = 'John Doe ' ---- -Now you're ready to begin printing out the commit data for your importer. -The initial information states that you're defining a commit object and what branch it's on, followed by the mark you've generated, the committer information and commit message, and then the previous commit, if any. -The code looks like this: +Ahora está listo para comenzar a imprimir los datos de confirmación para su importador. +La información inicial indica que está definiendo un objeto de confirmación y en qué rama está, seguido de la marca que ha generado, la información del confirmador y el mensaje de confirmación, y luego la confirmación anterior, si corresponde. +El código se ve así: [source,ruby] ---- @@ -123,17 +123,17 @@ export_data('imported from ' + dir) puts 'from :' + last_mark if last_mark ---- -You hardcode the time zone (-0700) because doing so is easy. -If you're importing from another system, you must specify the time zone as an offset. -The commit message must be expressed in a special format: +Usted codifica la zona horaria (-0700) porque hacerlo así será más fácil. +Si está importando desde otro sistema, debe especificar la zona horaria como un desplazamiento. +El mensaje de confirmación debe expresarse en un formato especial: [source] ---- data (size)\n(contents) ---- -The format consists of the word data, the size of the data to be read, a newline, and finally the data. -Because you need to use the same format to specify the file contents later, you create a helper method, `export_data`: +El formato consiste en la palabra datos, el tamaño de los datos a leer, una nueva línea y finalmente los datos. +Debido a que necesita usar el mismo formato para especificar el contenido del archivo más adelante, crea un método auxiliar, `export_data`: [source,ruby] ---- @@ -142,9 +142,9 @@ def export_data(string) end ---- -All that's left is to specify the file contents for each snapshot. -This is easy, because you have each one in a directory – you can print out the `deleteall` command followed by the contents of each file in the directory. -Git will then record each snapshot appropriately: +Lo único que queda es especificar el contenido del archivo para cada instantánea. +Esto es fácil, porque tiene cada uno en un directorio: puede imprimir el comando `deleteall` seguido de los contenidos de cada archivo en el directorio. +Git luego grabará cada instantánea apropiadamente: [source,ruby] ---- @@ -155,11 +155,11 @@ Dir.glob("**/*").each do |file| end ---- -Note: Because many systems think of their revisions as changes from one commit to another, fast-import can also take commands with each commit to specify which files have been added, removed, or modified and what the new contents are. -You could calculate the differences between snapshots and provide only this data, but doing so is more complex – you may as well give Git all the data and let it figure it out. -If this is better suited to your data, check the `fast-import` man page for details about how to provide your data in this manner. +Nota: Debido a que muchos sistemas piensan en sus revisiones como cambios de una confirmación a otra, la importación rápida también puede tomar comandos con cada confirmación para especificar qué archivos se han agregado, eliminado o modificado y cuáles son los contenidos nuevos. +Puede calcular las diferencias entre las instantáneas y proporcionar solo estos datos, pero hacerlo es más complejo; también puede darle todos los datos a Git y dejar que se resuelva. +Si esto se adapta mejor a sus datos, consulte la página del comando `fast-import` para obtener detalles sobre cómo proporcionar sus datos de esta manera. -The format for listing the new file contents or specifying a modified file with the new contents is as follows: +El formato para listar los nuevos contenidos del archivo o especificar un archivo modificado con los nuevos contenidos es el siguiente: [source] ---- @@ -168,8 +168,8 @@ data (size) (file contents) ---- -Here, 644 is the mode (if you have executable files, you need to detect and specify 755 instead), and inline says you'll list the contents immediately after this line. -Your `inline_data` method looks like this: +Aquí, 644 es el modo (si tiene archivos ejecutables, necesita detectar y especificar 755 en su lugar), y en línea dice que listará el contenido inmediatamente después de esta línea. +Su método `inline_data` tiene este aspecto: [source,ruby] ---- @@ -180,20 +180,20 @@ def inline_data(file, code = 'M', mode = '644') end ---- -You reuse the `export_data` method you defined earlier, because it's the same as the way you specified your commit message data. +Reutilizas el método `export_data` que definiste antes, porque es igual a la forma en que especificaste los datos del mensaje de confirmación. -The last thing you need to do is to return the current mark so it can be passed to the next iteration: +Lo último que debe hacer es devolver la marca actual para que pueda pasarla a la siguiente iteración: [source,ruby] ---- return mark ---- -[NOTE] +[NOTA] ==== -If you are running on Windows you'll need to make sure that you add one extra step. -As mentioned before, Windows uses CRLF for new line characters while git fast-import expects only LF. -To get around this problem and make git fast-import happy, you need to tell ruby to use LF instead of CRLF: +Si está ejecutando en Windows, deberá asegurarse de agregar un paso adicional. +Como se mencionó anteriormente, Windows usa CRLF para nuevos caracteres de línea mientras que git fast-import solo espera LF. +Para evitar este problema y hacer que git sea rápido, importe feliz, necesita decirle a ruby que use LF en lugar de CRLF: [source,ruby] ---- @@ -201,8 +201,8 @@ $stdout.binmode ---- ==== -That's it. -Here's the script in its entirety: +Eso es. +Aquí está todo el script. [source,ruby] @@ -274,7 +274,7 @@ Dir.chdir(ARGV[0]) do end ---- -If you run this script, you'll get content that looks something like this: +Si ejecuta este script, obtendrá un contenido que se ve así: [source,console] ---- @@ -304,8 +304,8 @@ M 644 inline README.md (...) ---- -To run the importer, pipe this output through `git fast-import` while in the Git directory you want to import into. -You can create a new directory and then run `git init` in it for a starting point, and then run your script: +Para ejecutar el importador, canalice esta salida a través de `git fast-import` mientras esté en el directorio de Git que desea importar. +Puede crear un nuevo directorio y luego ejecutar `git init` en él para un punto de partida, y luego ejecutar su secuencia de comandos: [source,console] ---- @@ -337,9 +337,9 @@ pack_report: pack_mapped = 1457 / 1457 --------------------------------------------------------------------- ---- -As you can see, when it completes successfully, it gives you a bunch of statistics about what it accomplished. -In this case, you imported 13 objects total for 4 commits into 1 branch. -Now, you can run `git log` to see your new history: +Como puede ver, cuando se completa con éxito, le da un montón de estadísticas sobre lo que logró. +En este caso, importó 13 objetos en total para 4 confirmaciones en 1 rama. +Ahora, puede ejecutar `git log` para ver su nuevo historial: [source,console] ---- @@ -357,9 +357,9 @@ Date: Mon Feb 3 01:00:00 2014 -0700 imported from back_2014_02_03 ---- -There you go – a nice, clean Git repository. -It's important to note that nothing is checked out – you don't have any files in your working directory at first. -To get them, you must reset your branch to where `master` is now: +Aquí tienes: un repositorio de Git agradable y limpio. +Es importante tener en cuenta que nada está desprotegido; al principio no tiene ningún archivo en su directorio de trabajo. +Para obtenerlos, debe restablecer su sucursal a donde es ahora `master`: [source,console] ---- @@ -370,5 +370,5 @@ $ ls README.md main.rb ---- -You can do a lot more with the `fast-import` tool – handle different modes, binary data, multiple branches and merging, tags, progress indicators, and more. -A number of examples of more complex scenarios are available in the `contrib/fast-import` directory of the Git source code. +Puede hacer mucho más con la herramienta `importación rápida`: maneja diferentes modos, datos binarios, múltiples ramas y combinaciones, etiquetas, indicadores de progreso y más. +Hay varios ejemplos de escenarios más complejos disponibles en el directorio `contrib / fast-import` del código fuente de Git.