From f108d53ec12cfdd9ada637ce0c3852aa25c3d3e1 Mon Sep 17 00:00:00 2001 From: Guilherme <69608661+BalakaDEV@users.noreply.github.com> Date: Wed, 4 Dec 2024 17:22:07 -0300 Subject: [PATCH] Update maintaining.asc MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit tradução pt-br --- .../sections/maintaining.asc | 462 +++++++++--------- 1 file changed, 232 insertions(+), 230 deletions(-) diff --git a/book/05-distributed-git/sections/maintaining.asc b/book/05-distributed-git/sections/maintaining.asc index 3309758c..5ec4896f 100644 --- a/book/05-distributed-git/sections/maintaining.asc +++ b/book/05-distributed-git/sections/maintaining.asc @@ -1,59 +1,59 @@ -=== Maintaining a Project +=== Mantendo um Projeto -(((maintaining a project))) -In addition to knowing how to contribute effectively to a project, you'll likely need to know how to maintain one. -This can consist of accepting and applying patches generated via `format-patch` and emailed to you, or integrating changes in remote branches for repositories you've added as remotes to your project. -Whether you maintain a canonical repository or want to help by verifying or approving patches, you need to know how to accept work in a way that is clearest for other contributors and sustainable by you over the long run. +(((mantendo um projeto))) +Além de saber como contribuir efetivamente para um projeto, é provável que você precise saber como manter um. +Isso pode consistir em aceitar e aplicar patches gerados via `format-patch` e enviados por e-mail para você, ou integrar mudanças em branches remotas para repositórios que você adicionou como remotos ao seu projeto. +Seja mantendo um repositório canônico ou querendo ajudar verificando ou aprovando patches, você precisa saber como aceitar o trabalho de uma maneira que seja mais clara para outros colaboradores e sustentável para você a longo prazo. -==== Working in Topic Branches +==== Trabalhando em Branches de Tópico -(((branches, topic))) -When you're thinking of integrating new work, it's generally a good idea to try it out in a _topic branch_ -- a temporary branch specifically made to try out that new work. -This way, it's easy to tweak a patch individually and leave it if it's not working until you have time to come back to it. -If you create a simple branch name based on the theme of the work you're going to try, such as `ruby_client` or something similarly descriptive, you can easily remember it if you have to abandon it for a while and come back later. -The maintainer of the Git project tends to namespace these branches as well -- such as `sc/ruby_client`, where `sc` is short for the person who contributed the work. -As you'll remember, you can create the branch based off your `master` branch like this: +(((branches, tópico))) +Quando você está pensando em integrar um novo trabalho, geralmente é uma boa ideia testá-lo em uma _branch de tópico_ — uma branch temporária feita especificamente para testar esse novo trabalho. +Dessa forma, fica fácil ajustar um patch individualmente e deixá-lo de lado se não estiver funcionando, até que você tenha tempo de voltar a ele. +Se você criar um nome simples para a branch com base no tema do trabalho que vai testar, como `ruby_client` ou algo semelhante e descritivo, será fácil lembrá-lo caso precise abandoná-lo por um tempo e voltar mais tarde. +O mantenedor do projeto Git tende a dar nomes a essas branches também — como `sc/ruby_client`, onde `sc` é uma abreviação da pessoa que contribuiu com o trabalho. +Como você deve lembrar, pode criar a branch a partir da sua branch `master` assim: [source,console] ---- $ git branch sc/ruby_client master ---- -Or, if you want to also switch to it immediately, you can use the `checkout -b` option: +Ou, se você também quiser alternar para ela imediatamente, pode usar a opção `checkout -b`: [source,console] ---- $ git checkout -b sc/ruby_client master ---- -Now you're ready to add the contributed work that you received into this topic branch and determine if you want to merge it into your longer-term branches. +Agora você está pronto para adicionar o trabalho contribuído que recebeu nesta branch de tópico e decidir se quer mesclá-lo nas suas branches de longo prazo. -[[r_patches_from_email]] -==== Applying Patches from Email -(((email, applying patches from))) -If you receive a patch over email that you need to integrate into your project, you need to apply the patch in your topic branch to evaluate it. -There are two ways to apply an emailed patch: with `git apply` or with `git am`. +==== Aplicando Patches por Email -===== Applying a Patch with apply +(((email, aplicando patches por))) +Se você receber um patch por e-mail que precisa integrar ao seu projeto, você deve aplicar o patch na sua branch de tópico para avaliá-lo. +Existem duas maneiras de aplicar um patch enviado por e-mail: com `git apply` ou com `git am`. -(((git commands, apply))) -If you received the patch from someone who generated it with `git diff` or some variation of the Unix `diff` command (which is not recommended; see the next section), you can apply it with the `git apply` command. -Assuming you saved the patch at `/tmp/patch-ruby-client.patch`, you can apply the patch like this: +===== Aplicando um Patch com apply + +(((comandos git, apply))) +Se você recebeu o patch de alguém que o gerou com `git diff` ou alguma variação do comando Unix `diff` (o que não é recomendado; veja a próxima seção), você pode aplicá-lo com o comando `git apply`. +Assumindo que você salvou o patch em `/tmp/patch-ruby-client.patch`, você pode aplicar o patch assim: [source,console] ---- $ git apply /tmp/patch-ruby-client.patch ---- -This modifies the files in your working directory. -It's almost identical to running a `patch -p1` command to apply the patch, although it's more paranoid and accepts fewer fuzzy matches than patch. -It also handles file adds, deletes, and renames if they're described in the `git diff` format, which `patch` won't do. -Finally, `git apply` is an ``apply all or abort all'' model where either everything is applied or nothing is, whereas `patch` can partially apply patchfiles, leaving your working directory in a weird state. -`git apply` is overall much more conservative than `patch`. -It won't create a commit for you -- after running it, you must stage and commit the changes introduced manually. +Isso modifica os arquivos no seu diretório de trabalho. +É quase idêntico a rodar o comando `patch -p1` para aplicar o patch, embora seja mais cuidadoso e aceite menos correspondências imprecisas do que o `patch`. +Também lida com adições, exclusões e renomeações de arquivos se elas forem descritas no formato `git diff`, o que o `patch` não faria. +Por fim, o `git apply` é um modelo de "aplicar tudo ou abortar tudo", onde ou tudo é aplicado ou nada é. Já o `patch` pode aplicar parcialmente os arquivos de patch, deixando seu diretório de trabalho em um estado estranho. +O `git apply` é, de maneira geral, muito mais conservador que o `patch`. +Ele não criará um commit para você — após executá-lo, você deve preparar e fazer o commit das mudanças manualmente. -You can also use `git apply` to see if a patch applies cleanly before you try actually applying it -- you can run `git apply --check` with the patch: +Você também pode usar o `git apply` para verificar se um patch pode ser aplicado corretamente antes de tentar aplicá-lo de fato — basta rodar `git apply --check` com o patch: [source,console] ---- @@ -62,20 +62,19 @@ error: patch failed: ticgit.gemspec:1 error: ticgit.gemspec: patch does not apply ---- -If there is no output, then the patch should apply cleanly. -This command also exits with a non-zero status if the check fails, so you can use it in scripts if you want. +Se não houver saída, o patch deve ser aplicado corretamente. +Este comando também sai com um status diferente de zero se a verificação falhar, então você pode usá-lo em scripts, caso queira. -[[r_git_am]] -===== Applying a Patch with `am` +===== Aplicando um Patch com `am` -(((git commands, am))) -If the contributor is a Git user and was good enough to use the `format-patch` command to generate their patch, then your job is easier because the patch contains author information and a commit message for you. -If you can, encourage your contributors to use `format-patch` instead of `diff` to generate patches for you. -You should only have to use `git apply` for legacy patches and things like that. +(((comandos git, am))) +Se o contribuidor for um usuário Git e foi bom o suficiente para usar o comando `format-patch` para gerar seu patch, seu trabalho será mais fácil, pois o patch contém informações do autor e uma mensagem de commit para você. +Se possível, incentive seus contribuidores a usar o `format-patch` em vez de `diff` para gerar patches para você. +Você só precisará usar o `git apply` para patches legados e coisas do tipo. -To apply a patch generated by `format-patch`, you use `git am` (the command is named `am` as it is used to "apply a series of patches from a mailbox"). -Technically, `git am` is built to read an mbox file, which is a simple, plain-text format for storing one or more email messages in one text file. -It looks something like this: +Para aplicar um patch gerado pelo `format-patch`, você usa o `git am` (o comando é nomeado `am` porque é usado para "aplicar uma série de patches de uma caixa de correio"). +Tecnicamente, o `git am` foi criado para ler um arquivo mbox, que é um formato simples de texto para armazenar uma ou mais mensagens de e-mail em um arquivo de texto. +Ele se parece com isso: [source,console] ---- @@ -87,11 +86,11 @@ Subject: [PATCH 1/2] Add limit to log function Limit log functionality to the first 20 ---- -This is the beginning of the output of the `git format-patch` command that you saw in the previous section; it also represents a valid mbox email format. -If someone has emailed you the patch properly using `git send-email`, and you download that into an mbox format, then you can point `git am` to that mbox file, and it will start applying all the patches it sees. -If you run a mail client that can save several emails out in mbox format, you can save entire patch series into a file and then use `git am` to apply them one at a time. +Este é o começo da saída do comando `git format-patch` que você viu na seção anterior; também representa um formato de e-mail mbox válido. +Se alguém lhe enviou o patch corretamente usando `git send-email`, e você o baixou no formato mbox, então você pode apontar o `git am` para esse arquivo mbox e ele começará a aplicar todos os patches que encontrar. +Se você usar um cliente de e-mail que possa salvar vários e-mails no formato mbox, pode salvar uma série de patches em um arquivo e depois usar o `git am` para aplicá-los um por um. -However, if someone uploaded a patch file generated via `git format-patch` to a ticketing system or something similar, you can save the file locally and then pass that file saved on your disk to `git am` to apply it: +No entanto, se alguém enviou um arquivo de patch gerado via `git format-patch` para um sistema de tickets ou algo similar, você pode salvá-lo localmente e depois passar esse arquivo salvo no seu disco para o `git am` para aplicá-lo: [source,console] ---- @@ -99,9 +98,9 @@ $ git am 0001-limit-log-function.patch Applying: Add limit to log function ---- -You can see that it applied cleanly and automatically created the new commit for you. -The author information is taken from the email's `From` and `Date` headers, and the message of the commit is taken from the `Subject` and body (before the patch) of the email. -For example, if this patch was applied from the mbox example above, the commit generated would look something like this: +Você verá que ele foi aplicado corretamente e criou automaticamente o novo commit para você. +As informações do autor são retiradas dos cabeçalhos `From` e `Date` do e-mail, e a mensagem do commit é retirada do `Subject` e do corpo (antes do patch) do e-mail. +Por exemplo, se este patch foi aplicado a partir do exemplo mbox acima, o commit gerado seria algo como: [source,console] ---- @@ -117,12 +116,12 @@ CommitDate: Thu Apr 9 09:19:06 2009 -0700 Limit log functionality to the first 20 ---- -The `Commit` information indicates the person who applied the patch and the time it was applied. -The `Author` information is the individual who originally created the patch and when it was originally created. +A informação de `Commit` indica quem aplicou o patch e o momento em que ele foi aplicado. +A informação de `Author` é a pessoa que originalmente criou o patch e quando ele foi criado. -But it's possible that the patch won't apply cleanly. -Perhaps your main branch has diverged too far from the branch the patch was built from, or the patch depends on another patch you haven't applied yet. -In that case, the `git am` process will fail and ask you what you want to do: +Mas é possível que o patch não seja aplicado corretamente. +Talvez sua branch principal tenha divergido muito da branch de onde o patch foi gerado, ou o patch dependa de outro patch que você ainda não aplicou. +Nesse caso, o processo `git am` falhará e perguntará o que você deseja fazer: [source,console] ---- @@ -136,20 +135,20 @@ If you would prefer to skip this patch, instead run "git am --skip". To restore the original branch and stop patching run "git am --abort". ---- -This command puts conflict markers in any files it has issues with, much like a conflicted merge or rebase operation. -You solve this issue much the same way -- edit the file to resolve the conflict, stage the new file, and then run `git am --resolved` to continue to the next patch: +Este comando coloca marcadores de conflito em qualquer arquivo que tenha problemas, de forma similar a uma operação de merge ou rebase em conflito. +Você resolve esse problema da mesma maneira — edita o arquivo para resolver o conflito, prepara o novo arquivo e depois executa `git am --resolved` para continuar com o próximo patch: [source,console] ---- -$ (fix the file) +$ (conserte o arquivo) $ git add ticgit.gemspec $ git am --resolved Applying: See if this helps the gem ---- -If you want Git to try a bit more intelligently to resolve the conflict, you can pass a `-3` option to it, which makes Git attempt a three-way merge. -This option isn't on by default because it doesn't work if the commit the patch says it was based on isn't in your repository. -If you do have that commit -- if the patch was based on a public commit -- then the `-3` option is generally much smarter about applying a conflicting patch: +Se você quiser que o Git tente resolver o conflito de forma mais inteligente, pode passar a opção `-3` para ele, o que faz o Git tentar um merge de três vias. +Esta opção não é ativada por padrão porque não funciona se o commit em que o patch foi baseado não estiver no seu repositório. +Se você tiver esse commit — se o patch foi baseado em um commit público — então a opção `-3` é geralmente mais inteligente para aplicar um patch conflitante: [source,console] ---- @@ -162,10 +161,10 @@ Falling back to patching base and 3-way merge... No changes -- Patch already applied. ---- -In this case, without the `-3` option the patch would have been considered as a conflict. -Since the `-3` option was used the patch applied cleanly. +Neste caso, sem a opção `-3`, o patch seria considerado um conflito. +Como a opção `-3` foi usada, o patch foi aplicado corretamente. -If you're applying a number of patches from an mbox, you can also run the `am` command in interactive mode, which stops at each patch it finds and asks if you want to apply it: +Se você estiver aplicando vários patches de um mbox, também pode rodar o comando `am` em modo interativo, que para em cada patch que encontrar e pergunta se você deseja aplicá-lo: [source,console] ---- @@ -177,37 +176,35 @@ See if this helps the gem Apply? [y]es/[n]o/[e]dit/[v]iew patch/[a]ccept all ---- -This is nice if you have a number of patches saved, because you can view the patch first if you don't remember what it is, or not apply the patch if you've already done so. +Isso é útil se você tem vários patches salvos, porque você pode visualizar o patch primeiro se não se lembrar do que se trata, ou não aplicá-lo se já o tiver feito. -When all the patches for your topic are applied and committed into your branch, you can choose whether and how to integrate them into a longer-running branch. +Quando todos os patches para o seu tópico forem aplicados e commitados na sua branch, você pode escolher como e se integrá-los em uma branch de longo prazo. -[[r_checking_out_remotes]] -==== Checking Out Remote Branches +==== Verificando Branches Remotas -(((branches, remote))) -If your contribution came from a Git user who set up their own repository, pushed a number of changes into it, and then sent you the URL to the repository and the name of the remote branch the changes are in, you can add them as a remote and do merges locally. +(((branches, remoto))) +Se a sua contribuição veio de um usuário Git que configurou seu próprio repositório, fez várias alterações nele e depois lhe enviou a URL do repositório e o nome da branch remota em que as mudanças estão, você pode adicioná-los como remoto e fazer merges localmente. -For instance, if Jessica sends you an email saying that she has a great new feature in the `ruby-client` branch of her repository, you can test it by adding the remote and checking out that branch locally: +Por exemplo, se a Jessica lhe enviar um e-mail dizendo que ela tem um ótimo novo recurso na branch `ruby-client` do repositório dela em `git@example.com:ruby-client.git`, você pode fazer o seguinte: [source,console] ---- -$ git remote add jessica git://github.com/jessica/myproject.git +$ git remote add jessica git@example.com:ruby-client.git $ git fetch jessica -$ git checkout -b rubyclient jessica/ruby-client +$ git checkout -b ruby-client jessica/ruby-client ---- +Se ela lhe enviar outro e-mail mais tarde com outra branch contendo um ótimo novo recurso, você pode simplesmente fazer `fetch` e `checkout` porque já tem o remoto configurado. -If she emails you again later with another branch containing another great feature, you could directly `fetch` and `checkout` because you already have the remote setup. - -This is most useful if you're working with a person consistently. -If someone only has a single patch to contribute once in a while, then accepting it over email may be less time consuming than requiring everyone to run their own server and having to continually add and remove remotes to get a few patches. -You're also unlikely to want to have hundreds of remotes, each for someone who contributes only a patch or two. -However, scripts and hosted services may make this easier -- it depends largely on how you develop and how your contributors develop. +Isso é mais útil se você estiver trabalhando consistentemente com uma pessoa. +Se alguém tem apenas um único patch para contribuir de vez em quando, então aceitá-lo por e-mail pode ser menos demorado do que exigir que todos rodem seus próprios servidores e tenham que adicionar e remover remotos constantemente para obter alguns patches. +Além disso, você provavelmente não vai querer ter centenas de remotos, cada um para alguém que contribui com apenas um patch ou dois. +No entanto, scripts e serviços hospedados podem facilitar isso — depende muito de como você desenvolve e como seus contribuintes desenvolvem. -The other advantage of this approach is that you get the history of the commits as well. -Although you may have legitimate merge issues, you know where in your history their work is based; a proper three-way merge is the default rather than having to supply a `-3` and hope the patch was generated off a public commit to which you have access. +A outra vantagem dessa abordagem é que você também obtém o histórico dos commits. +Embora você possa ter problemas legítimos de merge, você sabe em qual parte do seu histórico o trabalho deles está baseado; um merge de três vias adequado é o padrão, em vez de ter que fornecer um `-3` e torcer para que o patch tenha sido gerado a partir de um commit público ao qual você tem acesso. -If you aren't working with a person consistently but still want to pull from them in this way, you can provide the URL of the remote repository to the `git pull` command. -This does a one-time pull and doesn't save the URL as a remote reference: +Se você não está trabalhando com uma pessoa de forma constante, mas ainda assim quer puxar dela dessa maneira, pode fornecer a URL do repositório remoto para o comando `git pull`. +Isso faz um pull único e não salva a URL como uma referência remota: [source,console] ---- @@ -217,18 +214,23 @@ From https://github.com/onetimeguy/project Merge made by the 'recursive' strategy. ---- + + + + + [[r_what_is_introduced]] -==== Determining What Is Introduced +==== Determinando o que é introduzido (((branches, diffing))) -Now you have a topic branch that contains contributed work. -At this point, you can determine what you'd like to do with it. -This section revisits a couple of commands so you can see how you can use them to review exactly what you'll be introducing if you merge this into your main branch. +Agora você tem um branch de tópico que contém o trabalho contribuído. +Neste ponto, você pode determinar o que gostaria de fazer com ele. +Esta seção revisita alguns comandos para que você possa ver como usá-los para revisar exatamente o que será introduzido se você fizer o merge deste branch no seu branch principal. -It's often helpful to get a review of all the commits that are in this branch but that aren't in your `master` branch. -You can exclude commits in the `master` branch by adding the `--not` option before the branch name. -This does the same thing as the `master..contrib` format that we used earlier. -For example, if your contributor sends you two patches and you create a branch called `contrib` and applied those patches there, you can run this: +Frequentemente, é útil revisar todos os commits que estão neste branch, mas que não estão no seu branch `master`. +Você pode excluir os commits no branch `master` adicionando a opção `--not` antes do nome do branch. +Isso faz a mesma coisa que o formato `master..contrib` que usamos anteriormente. +Por exemplo, se seu colaborador te enviar dois patches e você criar um branch chamado `contrib` e aplicar esses patches lá, você pode rodar o seguinte: [source,console] ---- @@ -237,36 +239,36 @@ commit 5b6235bd297351589efc4d73316f0a68d484f118 Author: Scott Chacon Date: Fri Oct 24 09:53:59 2008 -0700 - See if this helps the gem + Veja se isso ajuda o gem commit 7482e0d16d04bea79d0dba8988cc78df655f16a0 Author: Scott Chacon Date: Mon Oct 22 19:38:36 2008 -0700 - Update gemspec to hopefully work better + Atualizar gemspec para funcionar melhor ---- -To see what changes each commit introduces, remember that you can pass the `-p` option to `git log` and it will append the diff introduced to each commit. +Para ver as alterações que cada commit introduziu, lembre-se de que você pode passar a opção `-p` para o `git log` e ele irá adicionar o diff introduzido em cada commit. -To see a full diff of what would happen if you were to merge this topic branch with another branch, you may have to use a weird trick to get the correct results. -You may think to run this: +Para ver um diff completo do que aconteceria se você fizesse o merge deste branch de tópico com outro branch, pode ser necessário usar um truque para obter os resultados corretos. +Você pode pensar em rodar isso: [source,console] ---- $ git diff master ---- -This command gives you a diff, but it may be misleading. -If your `master` branch has moved forward since you created the topic branch from it, then you'll get seemingly strange results. -This happens because Git directly compares the snapshots of the last commit of the topic branch you're on and the snapshot of the last commit on the `master` branch. -For example, if you've added a line in a file on the `master` branch, a direct comparison of the snapshots will look like the topic branch is going to remove that line. +Esse comando te dá um diff, mas pode ser enganoso. +Se o seu branch `master` avançou desde que você criou o branch de tópico a partir dele, você obterá resultados aparentemente estranhos. +Isso acontece porque o Git compara diretamente os snapshots do último commit do branch de tópico que você está e o snapshot do último commit no branch `master`. +Por exemplo, se você adicionou uma linha em um arquivo no branch `master`, uma comparação direta dos snapshots vai parecer que o branch de tópico vai remover essa linha. -If `master` is a direct ancestor of your topic branch, this isn't a problem; but if the two histories have diverged, the diff will look like you're adding all the new stuff in your topic branch and removing everything unique to the `master` branch. +Se o `master` for um ancestral direto do seu branch de tópico, isso não é um problema; mas se os dois históricos divergiram, o diff vai parecer que você está adicionando todas as novas alterações no seu branch de tópico e removendo tudo que é único no branch `master`. -What you really want to see are the changes added to the topic branch -- the work you'll introduce if you merge this branch with `master`. -You do that by having Git compare the last commit on your topic branch with the first common ancestor it has with the `master` branch. +O que você realmente quer ver são as alterações adicionadas ao branch de tópico -- o trabalho que você vai introduzir se fizer o merge deste branch com `master`. +Você faz isso fazendo o Git comparar o último commit do seu branch de tópico com o primeiro ancestral comum que ele tem com o branch `master`. -Technically, you can do that by explicitly figuring out the common ancestor and then running your diff on it: +Tecnicamente, você pode fazer isso descobrindo explicitamente o ancestral comum e então rodando o diff sobre ele: [source,console] ---- @@ -275,187 +277,186 @@ $ git merge-base contrib master $ git diff 36c7db ---- -or, more concisely: +ou, de maneira mais concisa: [source,console] ---- $ git diff $(git merge-base contrib master) ---- -However, neither of those is particularly convenient, so Git provides another shorthand for doing the same thing: the triple-dot syntax. -In the context of the `git diff` command, you can put three periods after another branch to do a `diff` between the last commit of the branch you're on and its common ancestor with another branch: +No entanto, nenhum desses métodos é particularmente conveniente, então o Git fornece uma outra forma mais curta de fazer a mesma coisa: a sintaxe de três pontos. +No contexto do comando `git diff`, você pode colocar três pontos depois de outro branch para fazer um `diff` entre o último commit do branch em que você está e seu ancestral comum com outro branch: [source,console] ---- $ git diff master...contrib ---- -This command shows you only the work your current topic branch has introduced since its common ancestor with `master`. -That is a very useful syntax to remember. +Este comando te mostra apenas o trabalho que o seu branch de tópico atual introduziu desde seu ancestral comum com o `master`. +Essa é uma sintaxe muito útil para lembrar. -==== Integrating Contributed Work +==== Integrando o Trabalho Contribuído (((integrating work))) -When all the work in your topic branch is ready to be integrated into a more mainline branch, the question is how to do it. -Furthermore, what overall workflow do you want to use to maintain your project? -You have a number of choices, so we'll cover a few of them. +Quando todo o trabalho no seu branch de tópico estiver pronto para ser integrado em um branch mais principal, a pergunta é como fazer isso. +Além disso, qual fluxo de trabalho geral você deseja usar para manter seu projeto? +Você tem várias opções, então vamos cobrir algumas delas. -===== Merging Workflows +===== Fluxos de Trabalho de Merge (((workflows, merging))) -One basic workflow is to simply merge all that work directly into your `master` branch. -In this scenario, you have a `master` branch that contains basically stable code. -When you have work in a topic branch that you think you've completed, or work that someone else has contributed and you've verified, you merge it into your master branch, delete that just-merged topic branch, and repeat. +Um fluxo de trabalho básico é simplesmente fazer o merge de todo aquele trabalho diretamente no seu branch `master`. +Neste cenário, você tem um branch `master` que contém basicamente o código estável. +Quando você tem trabalho em um branch de tópico que acha que está completo, ou trabalho que outra pessoa contribuiu e você verificou, você faz o merge dele no seu branch master, exclui o branch de tópico que acabou de ser integrado, e repete. -For instance, if we have a repository with work in two branches named `ruby_client` and `php_client` that looks like <>, and we merge `ruby_client` followed by `php_client`, your history will end up looking like <>. +Por exemplo, se temos um repositório com trabalho em dois branches chamados `ruby_client` e `php_client` que se parece com <>, e fazemos o merge de `ruby_client` seguido de `php_client`, seu histórico vai ficar assim <>. [[rmerwf_a]] -.History with several topic branches -image::images/merging-workflows-1.png[History with several topic branches] +.Histórico com vários branches de tópico +image::images/merging-workflows-1.png[Histórico com vários branches de tópico] [[rmerwf_b]] -.After a topic branch merge -image::images/merging-workflows-2.png[After a topic branch merge] +.Depois de um merge de branch de tópico +image::images/merging-workflows-2.png[Depois de um merge de branch de tópico] -That is probably the simplest workflow, but it can possibly be problematic if you're dealing with larger or more stable projects where you want to be really careful about what you introduce. +Esse é provavelmente o fluxo de trabalho mais simples, mas pode ser problemático se você estiver lidando com projetos maiores ou mais estáveis, onde você quer ser realmente cuidadoso com o que introduz. -If you have a more important project, you might want to use a two-phase merge cycle. -In this scenario, you have two long-running branches, `master` and `develop`, in which you determine that `master` is updated only when a very stable release is cut and all new code is integrated into the `develop` branch. -You regularly push both of these branches to the public repository. -Each time you have a new topic branch to merge in (<>), you merge it into `develop` (<>); then, when you tag a release, you fast-forward `master` to wherever the now-stable `develop` branch is (<>). +Se você tem um projeto mais importante, talvez queira usar um ciclo de merge em duas fases. +Neste cenário, você tem dois branches de longa duração, `master` e `develop`, onde você determina que o `master` só será atualizado quando uma versão muito estável for criada e todo o novo código for integrado no branch `develop`. +Você empurra regularmente ambos os branches para o repositório público. +Cada vez que você tiver um novo branch de tópico para integrar (<>), você faz o merge dele no `develop` (<>); depois, quando você marcar uma versão, você faz o fast-forward do `master` para onde o `develop` agora está (<>). [[rmerwf_c]] -.Before a topic branch merge -image::images/merging-workflows-3.png[Before a topic branch merge] +.Antes de um merge de branch de tópico +image::images/merging-workflows-3.png[Antes de um merge de branch de tópico] [[rmerwf_d]] -.After a topic branch merge -image::images/merging-workflows-4.png[After a topic branch merge] +.Depois de um merge de branch de tópico +image::images/merging-workflows-4.png[Depois de um merge de branch de tópico] [[rmerwf_e]] -.After a project release -image::images/merging-workflows-5.png[After a topic branch release] +.Depois de uma versão do projeto +image::images/merging-workflows-5.png[Depois de uma versão do projeto] -This way, when people clone your project's repository, they can either check out `master` to build the latest stable version and keep up to date on that easily, or they can check out `develop`, which is the more cutting-edge content. -You can also extend this concept by having an `integrate` branch where all the work is merged together. -Then, when the codebase on that branch is stable and passes tests, you merge it into a `develop` branch; and when that has proven itself stable for a while, you fast-forward your `master` branch. +Assim, quando as pessoas clonam o repositório do seu projeto, elas podem verificar o `master` para construir a versão estável mais recente e se manter atualizadas sobre isso facilmente, ou podem verificar o `develop`, que contém o conteúdo mais recente. +Você também pode estender esse conceito criando um branch `integrate` onde todo o trabalho é integrado. +Depois, quando o código nesse branch estiver estável e passar nos testes, você faz o merge dele no branch `develop`; e quando esse branch se provar estável por um tempo, você faz o fast-forward do seu branch `master`. -===== Large-Merging Workflows +===== Fluxos de Trabalho de Merge Grande (((workflows, "merging (large)"))) -The Git project has four long-running branches: `master`, `next`, and `seen` (formerly 'pu' -- proposed updates) for new work, and `maint` for maintenance backports. -When new work is introduced by contributors, it's collected into topic branches in the maintainer's repository in a manner similar to what we've described (see <>). -At this point, the topics are evaluated to determine whether they're safe and ready for consumption or whether they need more work. -If they're safe, they're merged into `next`, and that branch is pushed up so everyone can try the topics integrated together. +O projeto Git tem quatro branches de longa duração: `master`, `next`, e `seen` (anteriormente 'pu' -- atualizações propostas) para novo trabalho, e `maint` para manutenção de patches. +Quando um novo trabalho é introduzido por colaboradores, ele é coletado em branches de tópico no repositório do mantenedor de uma maneira semelhante ao que descrevemos (veja <>). +Neste ponto, os tópicos são avaliados para determinar se estão seguros e prontos para consumo ou se precisam de mais trabalho. +Se estão seguros, eles são integrados no `next`, e esse branch é empurrado para que todos possam tentar os tópicos integrados. [[rmerwf_f]] -.Managing a complex series of parallel contributed topic branches -image::images/large-merges-1.png[Managing a complex series of parallel contributed topic branches] +.Gerenciando uma série complexa de branches de tópico paralelos contribuídos +image::images/large-merges-1.png[Gerenciando uma série complexa de branches de tópico paralelos contribuídos] -If the topics still need work, they're merged into `seen` instead. -When it's determined that they're totally stable, the topics are re-merged into `master`. -The `next` and `seen` branches are then rebuilt from the `master`. -This means `master` almost always moves forward, `next` is rebased occasionally, and `seen` is rebased even more often: +Se os tópicos ainda precisarem de trabalho, eles são integrados no `seen`. +Quando for determinado que estão totalmente estáveis, os tópicos são re-integrados no `master`. +Os branches `next` e `seen` então são reconstruídos a partir do `master`. +Isso significa que o `master` quase sempre avança, o `next` é rebaseado ocasionalmente, e o `seen` é rebaseado ainda mais frequentemente: -.Merging contributed topic branches into long-term integration branches -image::images/large-merges-2.png[Merging contributed topic branches into long-term integration branches] +.Merging contribuições de tópicos em branches de integração de longo prazo +image::images/large-merges-2.png[Merging contribuições de tópicos em branches de integração de longo prazo] -When a topic branch has finally been merged into `master`, it's removed from the repository. -The Git project also has a `maint` branch that is forked off from the last release to provide backported patches in case a maintenance release is required. -Thus, when you clone the Git repository, you have four branches that you can check out to evaluate the project in different stages of development, depending on how cutting edge you want to be or how you want to contribute; and the maintainer has a structured workflow to help them vet new contributions. -The Git project's workflow is specialized. -To clearly understand this you could check out the https://github.com/git/git/blob/master/Documentation/howto/maintain-git.txt[Git Maintainer's guide]. +Quando um branch de tópico finalmente for integrado no `master`, ele é removido do repositório. +O projeto Git também tem um branch `maint` que é derivado da última versão para fornecer patches retrocedidos caso seja necessária uma versão de manutenção. +Assim, quando você clona o repositório do Git, você tem quatro branches que pode verificar para avaliar o projeto em diferentes estágios de desenvolvimento, dependendo do quão avançado você quer estar ou como deseja contribuir; e o mantenedor tem um fluxo de trabalho estruturado para ajudá-lo a verificar novas contribuições. O fluxo de trabalho do projeto Git é especializado. +Para entender isso claramente, você pode conferir o https://github.com/git/git/blob/master/Documentation/howto/maintain-git.txt[Guia do Mantenedor do Git]. [[r_rebase_cherry_pick]] -===== Rebasing and Cherry-Picking Workflows +===== Fluxos de Trabalho de Rebase e Cherry-Pick -(((workflows, rebasing and cherry-picking))) -Other maintainers prefer to rebase or cherry-pick contributed work on top of their `master` branch, rather than merging it in, to keep a mostly linear history. -When you have work in a topic branch and have determined that you want to integrate it, you move to that branch and run the rebase command to rebuild the changes on top of your current `master` (or `develop`, and so on) branch. -If that works well, you can fast-forward your `master` branch, and you'll end up with a linear project history. +(((fluxos de trabalho, rebase e cherry-pick))) +Outros mantenedores preferem fazer rebase ou cherry-pick do trabalho contribuído em cima de seu ramo `master`, em vez de mesclá-lo, para manter um histórico mais linear. +Quando você tem trabalho em um ramo de tópico e determinou que quer integrá-lo, você se move para esse ramo e executa o comando de rebase para reconstruir as mudanças em cima de seu ramo atual `master` (ou `develop`, e assim por diante). +Se isso funcionar bem, você pode avançar rapidamente seu ramo `master`, e acabará com um histórico de projeto linear. -(((git commands, cherry-pick))) -The other way to move introduced work from one branch to another is to cherry-pick it. -A cherry-pick in Git is like a rebase for a single commit. -It takes the patch that was introduced in a commit and tries to reapply it on the branch you're currently on. -This is useful if you have a number of commits on a topic branch and you want to integrate only one of them, or if you only have one commit on a topic branch and you'd prefer to cherry-pick it rather than run rebase. -For example, suppose you have a project that looks like this: +(((comandos git, cherry-pick))) +A outra maneira de mover o trabalho introduzido de um ramo para outro é fazer cherry-pick. +Um cherry-pick no Git é como um rebase para um único commit. +Ele pega o patch que foi introduzido em um commit e tenta reaplicá-lo no ramo em que você está atualmente. +Isso é útil se você tiver vários commits em um ramo de tópico e quiser integrar apenas um deles, ou se você tiver apenas um commit em um ramo de tópico e preferir fazer cherry-pick ao invés de rodar o rebase. +Por exemplo, suponha que você tenha um projeto que se parece com isto: -.Example history before a cherry-pick -image::images/rebasing-1.png[Example history before a cherry-pick] +.Exemplo de histórico antes de um cherry-pick +imagem::images/rebasing-1.png[Exemplo de histórico antes de um cherry-pick] -If you want to pull commit `e43a6` into your `master` branch, you can run: +Se você quiser puxar o commit `e43a6` para o seu ramo `master`, você pode executar: [source,console] ---- $ git cherry-pick e43a6 Finished one cherry-pick. -[master]: created a0a41a9: "More friendly message when locking the index fails." - 3 files changed, 17 insertions(+), 3 deletions(-) +[master]: created a0a41a9: "Mensagem mais amigável ao falhar ao bloquear o índice." + 3 arquivos alterados, 17 inserções(+), 3 exclusões(-) ---- -This pulls the same change introduced in `e43a6`, but you get a new commit SHA-1 value, because the date applied is different. -Now your history looks like this: +Isso puxa a mesma mudança introduzida em `e43a6`, mas você recebe um novo valor SHA-1 de commit, pois a data de aplicação é diferente. +Agora, seu histórico se parece com isto: -.History after cherry-picking a commit on a topic branch -image::images/rebasing-2.png[History after cherry-picking a commit on a topic branch] +.Histórico após o cherry-pick de um commit em um ramo de tópico +imagem::images/rebasing-2.png[Histórico após o cherry-pick de um commit em um ramo de tópico] -Now you can remove your topic branch and drop the commits you didn't want to pull in. +Agora você pode remover seu ramo de tópico e descartar os commits que você não queria puxar. ===== Rerere -(((git commands, rerere)))(((rerere))) -If you're doing lots of merging and rebasing, or you're maintaining a long-lived topic branch, Git has a feature called ``rerere'' that can help. +(((comandos git, rerere)))(((rerere))) +Se você está fazendo muitos merges e rebases, ou está mantendo um ramo de tópico de longa duração, o Git tem um recurso chamado ``rerere'' que pode ajudar. -Rerere stands for ``reuse recorded resolution'' -- it's a way of shortcutting manual conflict resolution. -When rerere is enabled, Git will keep a set of pre- and post-images from successful merges, and if it notices that there's a conflict that looks exactly like one you've already fixed, it'll just use the fix from last time, without bothering you with it. +Rerere significa ``reuse recorded resolution'' -- é uma maneira de agilizar a resolução manual de conflitos. +Quando o rerere está habilitado, o Git mantém um conjunto de imagens pré e pós de merges bem-sucedidos, e se notar que há um conflito que se parece exatamente com um que você já corrigiu, ele simplesmente usará a correção da última vez, sem incomodá-lo com isso. -This feature comes in two parts: a configuration setting and a command. -The configuration setting is `rerere.enabled`, and it's handy enough to put in your global config: +Este recurso vem em duas partes: uma configuração e um comando. +A configuração é `rerere.enabled`, e é conveniente colocá-la na sua configuração global: [source,console] ---- $ git config --global rerere.enabled true ---- -Now, whenever you do a merge that resolves conflicts, the resolution will be recorded in the cache in case you need it in the future. +Agora, sempre que você fizer um merge que resolva conflitos, a resolução será gravada no cache caso você precise dela no futuro. -If you need to, you can interact with the rerere cache using the `git rerere` command. -When it's invoked alone, Git checks its database of resolutions and tries to find a match with any current merge conflicts and resolve them (although this is done automatically if `rerere.enabled` is set to `true`). -There are also subcommands to see what will be recorded, to erase specific resolution from the cache, and to clear the entire cache. -We will cover rerere in more detail in <>. +Se necessário, você pode interagir com o cache do rerere usando o comando `git rerere`. +Quando invocado sozinho, o Git verifica seu banco de dados de resoluções e tenta encontrar uma correspondência com quaisquer conflitos de merge atuais e resolvê-los (embora isso seja feito automaticamente se `rerere.enabled` estiver definido como `true`). +Também existem subcomandos para ver o que será gravado, apagar uma resolução específica do cache e limpar o cache inteiro. +Nós cobriremos o rerere em mais detalhes em <>. [[r_tagging_releases]] -==== Tagging Your Releases +==== Marcando Suas Releases (((tags)))(((tags, signing))) -When you've decided to cut a release, you'll probably want to assign a tag so you can re-create that release at any point going forward. -You can create a new tag as discussed in <>. -If you decide to sign the tag as the maintainer, the tagging may look something like this: +Quando você decidir cortar uma release, provavelmente você vai querer atribuir uma tag para poder recriar essa release a qualquer momento no futuro. +Você pode criar uma nova tag como discutido em <>. +Se você decidir assinar a tag como mantenedor, a marcação pode se parecer com isto: [source,console] ---- -$ git tag -s v1.5 -m 'my signed 1.5 tag' -You need a passphrase to unlock the secret key for -user: "Scott Chacon " -1024-bit DSA key, ID F721C45A, created 2009-02-09 +$ git tag -s v1.5 -m 'minha tag 1.5 assinada' +Você precisa de uma senha para desbloquear a chave secreta para +usuário: "Scott Chacon " +Chave DSA de 1024 bits, ID F721C45A, criada em 09-02-2009 ---- -If you do sign your tags, you may have the problem of distributing the public PGP key used to sign your tags. -The maintainer of the Git project has solved this issue by including their public key as a blob in the repository and then adding a tag that points directly to that content. -To do this, you can figure out which key you want by running `gpg --list-keys`: +Se você assinar suas tags, pode ter o problema de distribuir a chave pública PGP usada para assinar suas tags. +O mantenedor do projeto Git resolveu esse problema incluindo sua chave pública como um blob no repositório e depois adicionando uma tag que aponta diretamente para esse conteúdo. +Para fazer isso, você pode descobrir qual chave você quer executando `gpg --list-keys`: [source,console] ---- $ gpg --list-keys /Users/schacon/.gnupg/pubring.gpg --------------------------------- -pub 1024D/F721C45A 2009-02-09 [expires: 2010-02-09] +pub 1024D/F721C45A 2009-02-09 [expira: 2010-02-09] uid Scott Chacon -sub 2048g/45D02282 2009-02-09 [expires: 2010-02-09] +sub 2048g/45D02282 2009-02-09 [expira: 2010-02-09] ---- -Then, you can directly import the key into the Git database by exporting it and piping that through `git hash-object`, which writes a new blob with those contents into Git and gives you back the SHA-1 of the blob: +Então, você pode importar diretamente a chave para o banco de dados do Git exportando-a e passando-a por `git hash-object`, o que grava um novo blob com esse conteúdo no Git e retorna o SHA-1 do blob: [source,console] ---- @@ -463,30 +464,30 @@ $ gpg -a --export F721C45A | git hash-object -w --stdin 659ef797d181633c87ec71ac3f9ba29fe5775b92 ---- -Now that you have the contents of your key in Git, you can create a tag that points directly to it by specifying the new SHA-1 value that the `hash-object` command gave you: +Agora que você tem o conteúdo da sua chave no Git, pode criar uma tag que aponte diretamente para ela especificando o novo valor SHA-1 que o comando `hash-object` forneceu: [source,console] ---- $ git tag -a maintainer-pgp-pub 659ef797d181633c87ec71ac3f9ba29fe5775b92 ---- -If you run `git push --tags`, the `maintainer-pgp-pub` tag will be shared with everyone. -If anyone wants to verify a tag, they can directly import your PGP key by pulling the blob directly out of the database and importing it into GPG: +Se você executar `git push --tags`, a tag `maintainer-pgp-pub` será compartilhada com todos. +Se alguém quiser verificar uma tag, pode importar diretamente sua chave PGP puxando o blob diretamente do banco de dados e importando-o para o GPG: [source,console] ---- $ git show maintainer-pgp-pub | gpg --import ---- -They can use that key to verify all your signed tags. -Also, if you include instructions in the tag message, running `git show ` will let you give the end user more specific instructions about tag verification. +Eles podem usar essa chave para verificar todas as suas tags assinadas. +Além disso, se você incluir instruções na mensagem da tag, ao executar `git show `, você poderá fornecer ao usuário final instruções mais específicas sobre a verificação da tag. [[r_build_number]] -==== Generating a Build Number +==== Gerando um Número de Build -(((build numbers)))(((git commands, describe))) -Because Git doesn't have monotonically increasing numbers like 'v123' or the equivalent to go with each commit, if you want to have a human-readable name to go with a commit, you can run `git describe` on that commit. -In response, Git generates a string consisting of the name of the most recent tag earlier than that commit, followed by the number of commits since that tag, followed finally by a partial SHA-1 value of the commit being described (prefixed with the letter "g" meaning Git): +(((números de build)))(((comandos git, describe))) +Como o Git não possui números que aumentam monotonamente como 'v123' ou o equivalente para cada commit, se você quiser ter um nome legível para o ser humano junto a um commit, pode executar `git describe` nesse commit. +Em resposta, o Git gera uma string composta pelo nome da tag mais recente anterior a esse commit, seguida pelo número de commits desde essa tag, seguido finalmente por um valor parcial de SHA-1 do commit descrito (prefixado com a letra "g" significando Git): [source,console] ---- @@ -494,46 +495,46 @@ $ git describe master v1.6.2-rc1-20-g8c5b85c ---- -This way, you can export a snapshot or build and name it something understandable to people. -In fact, if you build Git from source code cloned from the Git repository, `git --version` gives you something that looks like this. -If you're describing a commit that you have directly tagged, it gives you simply the tag name. +Dessa forma, você pode exportar um snapshot ou build e nomeá-lo de uma maneira compreensível para as pessoas. +Na verdade, se você construir o Git a partir do código fonte clonado do repositório Git, `git --version` lhe dará algo assim. +Se você estiver descrevendo um commit que você tenha marcado diretamente, ele simplesmente dará o nome da tag. -By default, the `git describe` command requires annotated tags (tags created with the `-a` or `-s` flag); if you want to take advantage of lightweight (non-annotated) tags as well, add the `--tags` option to the command. -You can also use this string as the target of a `git checkout` or `git show` command, although it relies on the abbreviated SHA-1 value at the end, so it may not be valid forever. -For instance, the Linux kernel recently jumped from 8 to 10 characters to ensure SHA-1 object uniqueness, so older `git describe` output names were invalidated. +Por padrão, o comando `git describe` requer tags anotadas (tags criadas com a flag `-a` ou `-s`); se você quiser aproveitar tags leves (não anotadas) também, adicione a opção `--tags` ao comando. +Você também pode usar essa string como alvo de um comando `git checkout` ou `git show`, embora dependa do valor abreviado de SHA-1 no final, então talvez não seja válido para sempre. +Por exemplo, o kernel do Linux recentemente passou de 8 para 10 caracteres para garantir a unicidade do objeto SHA-1, portanto, os nomes mais antigos do `git describe` foram invalidados. [[r_preparing_release]] -==== Preparing a Release +==== Preparando uma Release -(((releasing)))(((git commands, archive))) -Now you want to release a build. -One of the things you'll want to do is create an archive of the latest snapshot of your code for those poor souls who don't use Git. -The command to do this is `git archive`: +(((releases)))(((comandos git, archive))) +Agora você quer liberar uma build. +Uma das coisas que você vai querer fazer é criar um arquivo do último snapshot do seu código para aquelas almas perdidas que não usam Git. +O comando para fazer isso é o git archive: [source,console] ---- -$ git archive master --prefix='project/' | gzip > `git describe master`.tar.gz +$ git archive master --prefix='project/' | gzip > git describe master.tar.gz $ ls *.tar.gz v1.6.2-rc1-20-g8c5b85c.tar.gz ---- -If someone opens that tarball, they get the latest snapshot of your project under a `project` directory. -You can also create a zip archive in much the same way, but by passing the `--format=zip` option to `git archive`: +Se alguém abrir esse arquivo tar, eles obterão o último snapshot do seu projeto dentro de um diretório chamado "project". +Você também pode criar um arquivo zip de forma semelhante, mas passando a opção --format=zip para o git archive: [source,console] ---- -$ git archive master --prefix='project/' --format=zip > `git describe master`.zip +$ git archive master --prefix='project/' --format=zip > git describe master.zip ---- -You now have a nice tarball and a zip archive of your project release that you can upload to your website or email to people. +Agora você tem um arquivo tarball e um arquivo zip da release do seu projeto que pode carregar para o seu site ou enviar por email. [[r_the_shortlog]] -==== The Shortlog +==== O Shortlog -(((git commands, shortlog))) -It's time to email your mailing list of people who want to know what's happening in your project. -A nice way of quickly getting a sort of changelog of what has been added to your project since your last release or email is to use the `git shortlog` command. -It summarizes all the commits in the range you give it; for example, the following gives you a summary of all the commits since your last release, if your last release was named v1.0.1: +(((comandos git, shortlog))) +Agora é hora de enviar um e-mail para a lista de pessoas que querem saber o que está acontecendo no seu projeto. +Uma boa maneira de obter rapidamente um tipo de changelog do que foi adicionado ao seu projeto desde a sua última release ou e-mail é usar o comando git shortlog. +Ele resume todos os commits no intervalo que você especificar; por exemplo, o seguinte dá um resumo de todos os commits desde a sua última release, se sua última release foi nomeada v1.0.1: [source,console] ---- @@ -543,7 +544,7 @@ Chris Wanstrath (6): Add packed-refs annotated tag support. Add Grit::Commit#to_patch Update version and History.txt - Remove stray `puts` + Remove stray puts Make ls_tree ignore nils Tom Preston-Werner (4): @@ -553,4 +554,5 @@ Tom Preston-Werner (4): Regenerated gemspec for version 1.0.2 ---- -You get a clean summary of all the commits since v1.0.1, grouped by author, that you can email to your list. +Você recebe um resumo limpo de todos os commits desde v1.0.1, agrupados por autor, que você pode enviar por e-mail para sua lista. +