diff --git a/book/02-git-basics/sections/recording-changes.asc b/book/02-git-basics/sections/recording-changes.asc index 7648cfa6..18535b7d 100644 --- a/book/02-git-basics/sections/recording-changes.asc +++ b/book/02-git-basics/sections/recording-changes.asc @@ -1,10 +1,12 @@ -=== Gravando Alterações Em Seu Repositório +=== Gravando Alterações em Seu Repositório Você tem um verdadeiro repositório Git e um "checkout" ou cópia de trabalho dos arquivos para aquele projeto. Você precisa fazer algumas alterações e adicionar commits dessas alterações em seu repositório a cada vez que o projeto chegar a um estado que você queira registrar. Lembre-se que cada arquivo em seu diretório de trabalho pode estar em um dos seguintes estados: rastreado e não-rastreado. Arquivos rastreados são arquivos que foram incluídos no último _snapshot_; eles podem ser não modificados, modificados ou preparados (adicionados ao _stage_). +Em resumo, arquivos rastreados são os arquivos que o Git conhece. + Arquivos não rastreados são todos os outros - quaisquer arquivos em seu diretório de trabalho que não foram incluídos em seu último snapshot e não estão na área de stage. Quando você clona um repositório pela primeira vez, todos os seus arquivos serão rastreados e não modificados já que o Git acabou de obtê-los e você ainda não editou nada. @@ -31,7 +33,6 @@ nothing to commit, working directory clean Isso significa que você tem um diretório de trabalho limpo - em outras palavras, nenhum de seus arquivos rastreados foi modificado. Git também não está vendo nenhum arquivo não rastreado, senão eles estariam listados aqui. Finalmente, o comando lhe diz qual o branch que você está e diz que ele não divergiu do mesmo branch no servidor. - Por enquanto, esse branch é sempre ``master'', que é o padrão; você não precisa se preocupar com isso agora. <> vai abordar branches e referências em detalhe. @@ -256,16 +257,26 @@ doc/**/*.pdf O GitHub mantém uma lista bem abrangente com bons exemplos de arquivo `.gitignore` para vários projetos e linguagens em https://github.com/github/gitignore[], se você quiser um ponto de partida para o seu projeto. ==== +[NOTE] +==== +Em casos simples, um repositório deve ter um único arquivo `.gitignore` em seu diretório raiz, o qual é aplicado recursivamente a todo o repositório. +Contudo, também é possível ter arquivos `.gitignore` adicionais em subdiretórios. +As regras definidas nesses `.gitignore` internos se aplicam somente aos arquivos contidos no diretório em que eles estão localizados. +(O repositório do kernel do Linux tem 206 arquivos `.gitignore`.) + +Está fora do escopo deste livro explicar os detalhes de múltiplos arquivos `.gitignore`; veja `man gitignore` para mais informações. +==== + [[r_git_diff_staged]] -==== Viewing Your Staged and Unstaged Changes +==== Visualizando Suas Alterações Dentro e Fora do Stage -If the `git status` command is too vague for you – you want to know exactly what you changed, not just which files were changed – you can use the `git diff` command.(((git commands, diff))) -We'll cover `git diff` in more detail later, but you'll probably use it most often to answer these two questions: What have you changed but not yet staged? -And what have you staged that you are about to commit? -Although `git status` answers those questions very generally by listing the file names, `git diff` shows you the exact lines added and removed – the patch, as it were. +Se o comando `git status` for vago demais para você -- você quer saber exatamente o que você alterou, não apenas quais arquivos foram alterados -- você pode usar o comando `git diff`.(((git commands, diff))) +Nós explicaremos o `git diff` em detalhes mais tarde, mas provavelmente você vai usá-lo com maior frequência para responder a essas duas perguntas: O que você alterou mas ainda não mandou para o _stage_ (estado preparado)? +E o que está no _stage_, pronto para o _commit_? +Apesar de o `git status` responder a essas perguntas de forma genérica, listando os nomes dos arquivos, o `git diff` exibe exatamente as linhas que foram adicionadas e removidas -- o _patch_, como costumava se chamar. -Let's say you edit and stage the `README` file again and then edit the `CONTRIBUTING.md` file without staging it. -If you run your `git status` command, you once again see something like this: +Digamos que você altere o arquivo `README` e o mande para o _stage_ e então altere o arquivo `CONTRIBUTING.md` sem mandá-lo para o _stage_. +Se você executar o comando `git status`, você verá mais uma vez alguma coisa como o seguinte: [source,console] ---- @@ -284,7 +295,7 @@ Changes not staged for commit: modified: CONTRIBUTING.md ---- -To see what you've changed but not yet staged, type `git diff` with no other arguments: +Para ver o que você alterou mas ainda não mandou para o _stage_, digite o comando `git diff` sem nenhum argumento: [source,console] ---- @@ -305,11 +316,11 @@ index 8ebb991..643e24f 100644 that highlights your work in progress (and note in the PR title that it's ---- -That command compares what is in your working directory with what is in your staging area. -The result tells you the changes you've made that you haven't yet staged. +Esse comando compara o que está no seu diretório de trabalho com o que está no _stage_. +O resultado permite que você saiba quais alterações você fez que ainda não foram mandadas para o _stage_. -If you want to see what you've staged that will go into your next commit, you can use `git diff --staged`. -This command compares your staged changes to your last commit: +Se você quiser ver as alterações que você mandou para o _stage_ e que entrarão no seu próximo _commit_, você pode usar `git diff --staged`. +Este comando compara as alterações que estão no seu _stage_ com o seu último _commit_: [source,console] ---- @@ -323,11 +334,11 @@ index 0000000..03902a1 +My Project ---- -It's important to note that `git diff` by itself doesn't show all changes made since your last commit – only changes that are still unstaged. -This can be confusing, because if you've staged all of your changes, `git diff` will give you no output. +É importante notar que o `git diff` sozinho não mostra todas as alterações feitas desde o seu último _commit_ -- apenas as alterações que ainda não estão no _stage_ (não-preparado). +Isso pode ser confuso porque, se você já tiver mandado todas as suas alterações para o _stage_, a saída do `git diff` vai ser vazia. -For another example, if you stage the `CONTRIBUTING.md` file and then edit it, you can use `git diff` to see the changes in the file that are staged and the changes that are unstaged. -If our environment looks like this: +Um outro exemplo: se você mandar o arquivo `CONTRIBUTING.md` para o _stage_ e então alterá-lo, você pode usar o `git diff` para ver as alterações no arquivo que estão no _stage_ e também as que não estão. +Se o nosso ambiente se parecer com isso: [source,console] ---- @@ -348,7 +359,7 @@ Changes not staged for commit: modified: CONTRIBUTING.md ---- -Now you can use `git diff` to see what is still unstaged: +Agora você poderá usar o `git diff` para ver o que ainda não foi mandado para o _stage_: [source,console] ---- @@ -364,7 +375,7 @@ index 643e24f..87f08c8 100644 +# test line ---- -and `git diff --cached` to see what you've staged so far (`--staged` and `--cached` are synonyms): +e `git diff --cached` para ver o que você já mandou para o _stage_ até agora (`--staged` e `--cached` são sinônimos): [source,console] ---- @@ -386,32 +397,36 @@ index 8ebb991..643e24f 100644 ---- [NOTE] -.Git Diff in an External Tool +.Git Diff em uma Ferramenta Externa ==== -We will continue to use the `git diff` command in various ways throughout the rest of the book. -There is another way to look at these diffs if you prefer a graphical or external diff viewing program instead. -If you run `git difftool` instead of `git diff`, you can view any of these diffs in software like emerge, vimdiff and many more (including commercial products). -Run `git difftool --tool-help` to see what is available on your system. +Nós continuaremos usando o comando `git diff` de várias maneiras pelo resto do livro. +Há outra maneira de ver essas diferenças, se você preferir usar uma ferramenta gráfica ou um programa externo. +Se você executar `git difftool` em vez de `git diff`, você pode ver qualquer dessas diferenças em um software como emerge, vimdiff e muitos outros (incluindo produtos comerciais). +Execute `git difftool --tool-help` para ver o que há disponível em seu sistema. ==== [[r_committing_changes]] -==== Committing Your Changes +==== Fazendo Commit das Suas Alterações -Now that your staging area is set up the way you want it, you can commit your changes. -Remember that anything that is still unstaged – any files you have created or modified that you haven't run `git add` on since you edited them – won't go into this commit. -They will stay as modified files on your disk. -In this case, let's say that the last time you ran `git status`, you saw that everything was staged, so you're ready to commit your changes.(((git commands, status))) -The simplest way to commit is to type `git commit`:(((git commands, commit))) +Agora que sua área de _stage_ está preparada do jeito que você quer, você pode fazer _commit_ das suas alterações. +Lembre-se que qualquer coisa que ainda não sido mandada para o _stage_ -- qualquer arquivo que você tenha criado ou alterado e que ainda não tenha sido adicionado com `git add` -- não entrará nesse _commit_. +Esses arquivos permanecerão no seu disco como arquivos alterados. +Nesse caso, digamos que, da última vez que você executou `git status`, você viu que tudo estava no _stage_, então você está pronto para fazer _commit_ de suas alterações.(((git commands, status))) +O jeito mais simples de fazer _commit_ é digitar `git commit`:(((git commands, commit))) [source,console] ---- $ git commit ---- -Doing so launches your editor of choice. -(This is set by your shell's `$EDITOR` environment variable – usually vim or emacs, although you can configure it with whatever you want using the `git config --global core.editor` command as you saw in <>).(((editor, changing default)))(((git commands, config))) +Fazendo isso, será aberto o editor de sua escolha. + +[NOTE] +==== +O editor é determinado pela variável de ambiente `EDITOR` -- normalmente o vim ou emacs, mas você pode escolher qualquer editor que quiser usando o comando `git config --global core.editor` como você viu em <>.(((editor, changing default)))(((git commands, config))) +==== -The editor displays the following text (this example is a Vim screen): +O editor mostra o seguinte texto (este é um exemplo da tela do Vim): [source] ---- @@ -431,13 +446,18 @@ The editor displays the following text (this example is a Vim screen): ".git/COMMIT_EDITMSG" 9L, 283C ---- -You can see that the default commit message contains the latest output of the `git status` command commented out and one empty line on top. -You can remove these comments and type your commit message, or you can leave them there to help you remember what you're committing. -(For an even more explicit reminder of what you've modified, you can pass the `-v` option to `git commit`. -Doing so also puts the diff of your change in the editor so you can see exactly what changes you're committing.) -When you exit the editor, Git creates your commit with that commit message (with the comments and diff stripped out). +Você pode ver que a mensagem de _commit_ padrão contém a saída mais recente do comando `git status`, comentada, e uma linha em branco no topo. +Você pode remover esses comentários e digitar sua mensagem de _commit_, ou você pode deixá-los lá para ajudá-lo a lembrar o que faz parte do _commit_. + +[NOTE] +==== +Para um lembrete ainda mais explícito do que você alterou, você pode passar a opção `-v` para o `git commit`. +Isso inclui as diferenças (_diff_) da sua alteração no editor, para que você possa ver exatamente quais alterações estão entrando no _commit_. +==== + +Quando você sair do editor, o Git criará seu _commit_ com essa mensagem (com os comentários e diferenças removidos). -Alternatively, you can type your commit message inline with the `commit` command by specifying it after a `-m` flag, like this: +Alternativamente, você pode digitar sua mensagem de _commit_ diretamente na linha de comando, depois da opção `-m` do comando `commit`, assim: [source,console] ---- @@ -447,19 +467,19 @@ $ git commit -m "Story 182: Fix benchmarks for speed" create mode 100644 README ---- -Now you've created your first commit! -You can see that the commit has given you some output about itself: which branch you committed to (`master`), what SHA-1 checksum the commit has (`463dc4f`), how many files were changed, and statistics about lines added and removed in the commit. +Você acaba de criar seu primeiro _commit_! +Veja que a saída do comando fornece algumas informações: em qual _branch_ foi feito o _commit_ (`master`), seu _checksum_ SHA-1 (`463dc4f`), quantos arquivos foram alterados e estatísticas sobre o número de linhas adicionadas e removidas. -Remember that the commit records the snapshot you set up in your staging area. -Anything you didn't stage is still sitting there modified; you can do another commit to add it to your history. -Every time you perform a commit, you're recording a snapshot of your project that you can revert to or compare to later. +Lembre-se de que o _commit_ grava o _snapshot_ que você deixou na área de _stage_. +Qualquer alteração que você não tiver mandado para o _stage_ permanecerá como estava, em seu lugar; você pode executar outro _commit_ para adicioná-la ao seu histórico. +Toda vez que você executa um _commit_, você está gravando um _snapshot_ do seu projeto que você pode usar posteriormente para fazer comparações, ou mesmo restaurá-lo. -==== Skipping the Staging Area +==== Pulando a Área de Stage (((staging area, skipping))) -Although it can be amazingly useful for crafting commits exactly how you want them, the staging area is sometimes a bit more complex than you need in your workflow. -If you want to skip the staging area, Git provides a simple shortcut. -Adding the `-a` option to the `git commit` command makes Git automatically stage every file that is already tracked before doing the commit, letting you skip the `git add` part: +Mesmo sendo incrivelmente útil para preparar _commits_ exatamente como você quer, a área de _stage_ algumas vezes é um pouco mais complexa do que o necessário. +Se você quiser pular a área de _stage_, o Git fornece um atalho simples. +A opção `-a`, do comando `git commit`, faz o Git mandar todos arquivos rastreados para o _stage_ automaticamente, antes de fazer o _commit_, permitindo que você pule a parte do `git add`: [source,console] ---- @@ -478,18 +498,18 @@ $ git commit -a -m 'added new benchmarks' 1 file changed, 5 insertions(+), 0 deletions(-) ---- -Notice how you don't have to run `git add` on the `CONTRIBUTING.md` file in this case before you commit. -That's because the `-a` flag includes all changed files. -This is convenient, but be careful; sometimes this flag will cause you to include unwanted changes. +Perceba que, nesse caso, você não tem que executar `git add` antes, para adicionar o arquivo `CONTRIBUTING.md` ao _commit_. +Isso ocorre porque a opção `-a` inclui todos os arquivos alterados. +Isso é conveniente, mas cuidado; algumas vezes esta opção fará você incluir alterações indesejadas. [[r_removing_files]] -==== Removing Files +==== Removendo Arquivos (((files, removing))) -To remove a file from Git, you have to remove it from your tracked files (more accurately, remove it from your staging area) and then commit. -The `git rm` command does that, and also removes the file from your working directory so you don't see it as an untracked file the next time around. +Para remover um arquivo do Git, você tem que removê-lo dos seus arquivos rastreados (mais precisamente, removê-lo da sua área de _stage_) e então fazer um _commit_. +O comando `git rm` faz isso, e também remove o arquivo do seu diretório de trabalho para que você não o veja como um arquivo não-rastreado nas suas próximas interações. -If you simply remove the file from your working directory, it shows up under the ``Changed but not updated'' (that is, _unstaged_) area of your `git status` output: +Se você simplesmente remover o arquivo do seu diretório, ele aparecerá sob a área ``Changes not staged for commit'' (isto é, fora do _stage_) da saída do seu `git status`: [source,console] ---- @@ -506,7 +526,7 @@ Changes not staged for commit: no changes added to commit (use "git add" and/or "git commit -a") ---- -Then, if you run `git rm`, it stages the file's removal: +Mas, se você executar `git rm`, o arquivo será preparado para remoção (retirado do _stage_): [source,console] ---- @@ -521,58 +541,58 @@ Changes to be committed: deleted: PROJECTS.md ---- -The next time you commit, the file will be gone and no longer tracked. -If you modified the file and added it to the index already, you must force the removal with the `-f` option. -This is a safety feature to prevent accidental removal of data that hasn't yet been recorded in a snapshot and that can't be recovered from Git. +Da próxima vez que você fizer um _commit_, o arquivo será eliminado e não será mais rastreado. +Se o arquivo tiver sido alterado ou se já tiver adicionado à área de _stage_, você terá que forçar a remoção com a opção `-f`. +Essa é uma medida de segurança para prevenir a exclusão acidental de dados que ainda não tenham sido gravados em um _snapshot_ e que não poderão ser recuperados do histórico. -Another useful thing you may want to do is to keep the file in your working tree but remove it from your staging area. -In other words, you may want to keep the file on your hard drive but not have Git track it anymore. -This is particularly useful if you forgot to add something to your `.gitignore` file and accidentally staged it, like a large log file or a bunch of `.a` compiled files. -To do this, use the `--cached` option: +Outra coisa útil que você pode querer fazer é manter o arquivo no seu diretório de trabalho, mas removê-lo da sua área de _stage_. +Em outras palavras, você pode querer manter o arquivo no seu disco rígido, mas não deixá-lo mais sob controle do Git. +Isso é particularmente útil se você esquecer de adicionar alguma coisa ao seu arquivo `.gitignore` e, acidentalmente, mandá-la para o _stage_, como um grande arquivo de _log_ ou um monte de arquivos compilados `.a`. +Para fazer isso, use a opção `--cached`: [source,console] ---- $ git rm --cached README ---- -You can pass files, directories, and file-glob patterns to the `git rm` command. -That means you can do things such as: +Você pode passar arquivos, diretórios e padrões de nomes para o comando `git rm`. +Isso quer dizer que você pode fazer coisas como: [source,console] ---- $ git rm log/\*.log ---- -Note the backslash (`\`) in front of the `*`. -This is necessary because Git does its own filename expansion in addition to your shell's filename expansion. -This command removes all files that have the `.log` extension in the `log/` directory. -Or, you can do something like this: +Note a barra invertida (`\`) na frente do `*`. +Isso é necessário porque o Git faz sua própria expansão de nomes de arquivos em adição a que é feita pela sua _shell_. +Esse comando remove todos os arquivos que tenham a extensão `.log` do diretório `log/`. +Ou, você pode fazer algo como o seguinte: [source,console] ---- $ git rm \*~ ---- -This command removes all files whose names end with a `~`. +Esse comando remove todos os arquivos cujos nomes terminem com um `~`. [[r_git_mv]] -==== Moving Files +==== Movendo Arquivos (((files, moving))) -Unlike many other VCS systems, Git doesn't explicitly track file movement. -If you rename a file in Git, no metadata is stored in Git that tells it you renamed the file. -However, Git is pretty smart about figuring that out after the fact – we'll deal with detecting file movement a bit later. +Diferentemente de outros sistemas de controle de versão, o Git não rastreia explicitamente a movimentação de arquivos. +Se você renomear um arquivo no Git, ele não armazena metadados indicando que determinado arquivo foi renomeado. +Porém, o Git é bastante esperto para perceber isso depois do fato ocorrido -- nós trataremos de movimentação de arquivos daqui a pouco. -Thus it's a bit confusing that Git has a `mv` command. -If you want to rename a file in Git, you can run something like: +Assim, é um pouco confuso o fato de o Git ter um comando `mv`. +Se você quiser renomear um arquivo no Git, você pode executar alguma coisa como: [source,console] ---- -$ git mv file_from file_to +$ git mv arq_origem arq_destino ---- -and it works fine. -In fact, if you run something like this and look at the status, you'll see that Git considers it a renamed file: +e vai funcionar bem. +Na verdade, se você executar alguma coisa assim e verificar o _status_, você vai ver que o Git considera que arquivo foi renomeado: [source,console] ---- @@ -586,7 +606,7 @@ Changes to be committed: renamed: README.md -> README ---- -However, this is equivalent to running something like this: +Contudo, isso é equivalente a executar algo como: [source,console] ---- @@ -595,6 +615,6 @@ $ git rm README.md $ git add README ---- -Git figures out that it's a rename implicitly, so it doesn't matter if you rename a file that way or with the `mv` command. -The only real difference is that `git mv` is one command instead of three – it's a convenience function. -More importantly, you can use any tool you like to rename a file, and address the add/rm later, before you commit. +O Git percebe que, implicitamente, se trata de um arquivo renomeado, de maneira que não importa se você renomear um arquivo desse jeito ou com o comando `mv`. +A única diferença real é que `git mv` é um comando em vez de três -- é uma função de conveniência. +Mais importante, você pode usar qualquer ferramenta que quiser para renomear um arquivo e cuidar do `add`/`rm` depois, antes de fazer o _commit_.