From df7d8ea36cdf8709cef1fa2d5411058b649e592e Mon Sep 17 00:00:00 2001 From: Flavio V Filho Date: Tue, 12 Jan 2021 10:27:19 -0300 Subject: [PATCH 1/2] traduzir-capitulo-5.2 --- .../sections/contributing.asc | 590 +++++++++--------- 1 file changed, 295 insertions(+), 295 deletions(-) diff --git a/book/05-distributed-git/sections/contributing.asc b/book/05-distributed-git/sections/contributing.asc index 07c256b4..c582ac88 100644 --- a/book/05-distributed-git/sections/contributing.asc +++ b/book/05-distributed-git/sections/contributing.asc @@ -2,177 +2,177 @@ === Contributing to a Project (((contributing))) -The main difficulty with describing how to contribute to a project are the numerous variations on how to do that. -Because Git is very flexible, people can and do work together in many ways, and it's problematic to describe how you should contribute -- every project is a bit different. -Some of the variables involved are active contributor count, chosen workflow, your commit access, and possibly the external contribution method. - -The first variable is active contributor count -- how many users are actively contributing code to this project, and how often? -In many instances, you'll have two or three developers with a few commits a day, or possibly less for somewhat dormant projects. -For larger companies or projects, the number of developers could be in the thousands, with hundreds or thousands of commits coming in each day. -This is important because with more and more developers, you run into more issues with making sure your code applies cleanly or can be easily merged. -Changes you submit may be rendered obsolete or severely broken by work that is merged in while you were working or while your changes were waiting to be approved or applied. -How can you keep your code consistently up to date and your commits valid? - -The next variable is the workflow in use for the project. -Is it centralized, with each developer having equal write access to the main codeline? -Does the project have a maintainer or integration manager who checks all the patches? -Are all the patches peer-reviewed and approved? -Are you involved in that process? -Is a lieutenant system in place, and do you have to submit your work to them first? - -The next variable is your commit access. -The workflow required in order to contribute to a project is much different if you have write access to the project than if you don't. -If you don't have write access, how does the project prefer to accept contributed work? -Does it even have a policy? -How much work are you contributing at a time? -How often do you contribute? - -All these questions can affect how you contribute effectively to a project and what workflows are preferred or available to you. -We'll cover aspects of each of these in a series of use cases, moving from simple to more complex; you should be able to construct the specific workflows you need in practice from these examples. +A principal dificuldade em descrever como contribuir com um projeto é a numerosa quantidade de maneiras de contribuir. +Já que Git é muito flexível, as pessoas podem e trabalham juntas de muitas maneiras, sendo problemático descrever como você deve contribuir -- cada projeto é um pouco diferente. +Algumas das variáveis envolvidas são a quantidade de colaboradores ativos, o fluxo de trabalho escolhido, sua permissão para fazer commit, e possivelmente o método de contribuição externa. + +A primeira variável é a quantidade de colaboradores ativos -- quantos usuários estão ativamente contribuindo para o código deste projeto, e em que frequência? +Em muitas circunstâncias você terá dois ou três desenvolvedores com alguns commites por dia, ou possivelmente menos em projetos meio dormentes. +Para grandes companhias ou projetos, o número de desenvolvedores pode estar nas centenas, com centenas ou milhares de commites chegando todos os dias. +Isto é importante porque com mais e mais desenvolvedores, você se depara com mais problemas para certificar-se que seu código é aplicado diretamente ou pode ser facilmente integrado. +Alterações que você entrega podem se tornar obsoletas ou severamente quebrar pelo trabalho que é mesclado enquanto você trabalha ou enquanto suas mudanças estão esperando para serem aprovadas e aplicadas. +Como você pode manter seu código consistentemente atualizado e seus commites válidos? + +A próxima variável é o fluxo de trabalho em uso no projeto. +Ele é centralizado, com cada desenvolvedor tendo permissões de escrita iguais para o código principal? +O projeto tem um mantenedor ou coordenador que checa todos os patches? +Todos os patches são revisados e aprovados pelos colegas? +Você está envolvido neste processo? +Um sistema de tenentes está estabelecido, e você tem que enviar seu trabalho para eles antes? + +A próxima variável é sua permissão de commit. +O fluxo de trabalho necessário para contribuir ao projeto é muito diferente se você tem permissão de escrita ao projeto ou não tem. +Se você não tem permissão de escrita, como o projeto costuma aceitar o trabalho dos colaboradores? +Existe algum tipo de norma? +Quanto trabalho você está enviando por vez? +Com que frequência? + +Todas estas questões podem afetar como você contribui efetivamente para o projeto e que fluxos de trabalho são adequados ou possíveis para você. +Iremos abordar aspectos de cada uma delas em uma série de estudos de caso, indo do simples ao mais complexo; você deve ser capaz de construir fluxos de trabalho específicos para suas necessidades com estes exemplos. [[r_commit_guidelines]] -==== Commit Guidelines +==== Diretrizes para Fazer Commites -Before we start looking at the specific use cases, here's a quick note about commit messages. -Having a good guideline for creating commits and sticking to it makes working with Git and collaborating with others a lot easier. -The Git project provides a document that lays out a number of good tips for creating commits from which to submit patches -- you can read it in the Git source code in the `Documentation/SubmittingPatches` file. +Antes de vermos estudos de casos específicos, uma observação rápida sobre mensagens de commit. +Ter uma boa diretriz para criar commites e a seguir facilita muito trabalhar com Git e colaborar com outros. +O projeto Git fornece um documento que dá várias dicas boas para criar commites ao enviar patches -- você pode lê-lo no código fonte do Git no arquivo `Documentation/SubmittingPatches`. (((git commands, diff, check))) -First, your submissions should not contain any whitespace errors. -Git provides an easy way to check for this -- before you commit, run `git diff --check`, which identifies possible whitespace errors and lists them for you. +Primeiro, seus envios não devem conter nenhum espaço em branco não proposital. +Git fornece uma maneira fácil de checar isto -- antes de você fazer um commit, execute `git diff --check`, que identifica possíveis espaços em branco indesejados e os lista pra você. -.Output of `git diff --check` +.Resultado de `git diff --check` image::images/git-diff-check.png[Output of `git diff --check`] -If you run that command before committing, you can tell if you're about to commit whitespace issues that may annoy other developers. +Se você executar este comando antes do commit, você perceberá se está prestes a enviar espaços em branco problemáticos que podem irritar os outros desenvolvedores. -Next, try to make each commit a logically separate changeset. -If you can, try to make your changes digestible -- don't code for a whole weekend on five different issues and then submit them all as one massive commit on Monday. -Even if you don't commit during the weekend, use the staging area on Monday to split your work into at least one commit per issue, with a useful message per commit. -If some of the changes modify the same file, try to use `git add --patch` to partially stage files (covered in detail in <>). -The project snapshot at the tip of the branch is identical whether you do one commit or five, as long as all the changes are added at some point, so try to make things easier on your fellow developers when they have to review your changes. +Depois tente fazer cada commit como um conjunto lógico de mudanças. +Se possível, tente digerir suas modificações -- não programe o final de semana inteiro em cinco diferentes problemas e então publique tudo em um commit massivo na segunda-feira. +Mesmo que você não publique durante o fim de semana, use a área de stage na segunda-feira para dividir seu trabalho em ao menos um commit por assunto, com uma mensagem útil em cada commit. +Se algumas alterações modificarem o mesmo arquivo, tente executar `git add --patch` para colocar na área de stage os arquivos parcialmente (explicado em detalhes em <>). +O retrato do projeto no final do branch é idêntico você fazendo um commit ou cinco, desde que todas as mudanças forem eventualmente adicionadas, então tente fazer as coisas mais fáceis para seus colegas desenvolvedores quando eles tiverem que revisar suas mudanças. -This approach also makes it easier to pull out or revert one of the changesets if you need to later. -<> describes a number of useful Git tricks for rewriting history and interactively staging files -- use these tools to help craft a clean and understandable history before sending the work to someone else. +Esta abordagem também facilita retirar ou reverter uma das alterações se você precisar depois. +<> descreve vários truques úteis do Git para reescrever o histórico e colocar interativamente arquivos na área de stage -- utilize estas ferramentas para criar um histórico limpo e compreensível antes de enviar o trabalho para alguém. -The last thing to keep in mind is the commit message. -Getting in the habit of creating quality commit messages makes using and collaborating with Git a lot easier. -As a general rule, your messages should start with a single line that's no more than about 50 characters and that describes the changeset concisely, followed by a blank line, followed by a more detailed explanation. -The Git project requires that the more detailed explanation include your motivation for the change and contrast its implementation with previous behavior -- this is a good guideline to follow. -Write your commit message in the imperative: "Fix bug" and not "Fixed bug" or "Fixes bug." -Here is a template you can follow, which we've lightly adapted from one https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html[originally written by Tim Pope]: +A última coisa para ter em mente é a mensagem do commit. +Manter o hábito de criar boas mensagens de commit facilita muito usar e colaborar com o Git. +Como regra geral, suas mensagens devem começar com uma única linha que não tem mais que 50 caracteres e descreve as alterações concisamente, seguida de uma linha em branco, seguida de uma explicação mais detalhada. +O projeto Git requer que esta explicação mais detalhada inclua sua motivação para a mudança e compare sua implementação com o comportamento anterior -- esta é uma boa diretriz para seguir. +Escreva sua mensagem de commit no imperativo: "Consertar o bug" e não "Bug consertado" ou "Conserta bug." +Tem um modelo que você pode seguir, que adaptamos ligeiramente daqui https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html[escrito originalmente por Tim Pope]: [source,text] ---- -Capitalized, short (50 chars or less) summary +Resumo curto (50 caracteres ou menos), com maiúsculas. -More detailed explanatory text, if necessary. Wrap it to about 72 -characters or so. In some contexts, the first line is treated as the -subject of an email and the rest of the text as the body. The blank -line separating the summary from the body is critical (unless you omit -the body entirely); tools like rebase will confuse you if you run the -two together. +Mais texto explicativo, se necessário. Desenvolva por 72 +caracteres aproximadamente. Em alguns contextos, a primeira linha é tratada como o +assunto do email e o resto do texto como o corpo. A linha +em branco separando o assunto do corpo é crítica (a não ser que você omita +o corpo inteiro); ferramentas como _rebase_ irão te confundir se você unir as +duas partes. -Write your commit message in the imperative: "Fix bug" and not "Fixed bug" -or "Fixes bug." This convention matches up with commit messages generated -by commands like git merge and git revert. +Escreva sua mensagem de commit no imperativo: "Consertar o bug" e não "Bug consertado" +ou "Conserta bug". Esta convenção combina com as mensagens de commit geradas +por comandos como `git merge` e `git revert`. -Further paragraphs come after blank lines. +Parágrafos seguintes veem depois de linhas em branco. -- Bullet points are okay, too +- Marcadores são ok, também -- Typically a hyphen or asterisk is used for the bullet, followed by a - single space, with blank lines in between, but conventions vary here +- Normalmente um hífen ou asterisco é usado para o marcador, seguido de um + único espaço, com linhas em branco entre eles, mas os protocolos podem variar aqui -- Use a hanging indent +- Utilize recuos alinhados ---- -If all your commit messages follow this model, things will be much easier for you and the developers with whom you collaborate. -The Git project has well-formatted commit messages -- try running `git log --no-merges` there to see what a nicely-formatted project-commit history looks like. +Se todas as suas mensagens de commit seguirem este modelo, as coisas serão muito mais fáceis para você e os desenvolvedores com que trabalha. +O projeto Git tem mensagens de commit bem formatadas - tente executar `git log --no-merges` nele para ver o que um projeto com histórico de commit bem feito se parece. [NOTE] -.Do as we say, not as we do. +.Faça o que digo, não faça o que faço. ==== -For the sake of brevity, many of the examples in this book don't have nicely-formatted commit messages like this; instead, we simply use the `-m` option to `git commit`. +Para o bem da concisão, muitos dos exemplos neste livro não tem mensagens de commit bem formatas como esta; ao invés, nós simplesmente usamos a opção `-m` do `git commit`. -In short, do as we say, not as we do. +Resumindo, faça o que digo, não faça o que faço. ==== [[r_private_team]] -==== Private Small Team +==== Time Pequeno Privado (((contributing, private small team))) -The simplest setup you're likely to encounter is a private project with one or two other developers. -``Private,'' in this context, means closed-source -- not accessible to the outside world. -You and the other developers all have push access to the repository. +A configuração mais simples que você deve encontrar é um projeto privado com um ou dois outros desenvolvedores. +``Privado,`` neste contexto, significa código fechado -- não acessível ao mundo exterior. +Você e os outros desenvolvedores têm permissão para publicar no repositório. -In this environment, you can follow a workflow similar to what you might do when using Subversion or another centralized system. -You still get the advantages of things like offline committing and vastly simpler branching and merging, but the workflow can be very similar; the main difference is that merges happen client-side rather than on the server at commit time. -Let's see what it might look like when two developers start to work together with a shared repository. -The first developer, John, clones the repository, makes a change, and commits locally. -The protocol messages have been replaced with `...` in these examples to shorten them somewhat. +Neste ambiente, você pode seguir um fluxo de trabalho similar ao que faria usando Subversion ou outro sistema centralizado. +Você ainda tem vantagens como fazer commites offline e fazer branches e mesclagens infinitamente mais simples, mas o fluxo de trabalho pode ser bastante semelhante; a principal diferença é que mesclar acontece no lado do cliente ao invés do servidor na hora do commit. +Veremos o que pode acontecer quando dois desenvolvedores começam a trabalhar juntos em um repositório compartilhado. +O primeiro desenvolvedor, John, clona o repositório, faz uma alteração e um commit localmente. +O protocolo de mensagens foi substituído por `...` nestes exemplos por simplificação. [source,console] ---- -# John's Machine +# Máquina do John $ git clone john@githost:simplegit.git Cloning into 'simplegit'... ... $ cd simplegit/ $ vim lib/simplegit.rb -$ git commit -am 'Remove invalid default value' -[master 738ee87] Remove invalid default value +$ git commit -am 'Remover valor padrão inválido' +[master 738ee87] Remover valor padrão inválido 1 files changed, 1 insertions(+), 1 deletions(-) ---- -The second developer, Jessica, does the same thing -- clones the repository and commits a change: +O segundo desenvolvedor, Jessica, faz a mesma coisa -- clona o repositório e faz um commit de uma alteração: [source,console] ---- -# Jessica's Machine +# Computador da Jessica $ git clone jessica@githost:simplegit.git Cloning into 'simplegit'... ... $ cd simplegit/ -$ vim TODO -$ git commit -am 'Add reset task' -[master fbff5bc] Add reset task +$ vim FAZER +$ git commit -am 'Adicionar tarefa para reiniciar' +[master fbff5bc] Adicionar tarefa para reiniciar 1 files changed, 1 insertions(+), 0 deletions(-) ---- -Now, Jessica pushes her work to the server, which works just fine: +Agora, Jessica dá um push do seu trabalho no servidor, o que funciona bem: [source,console] ---- -# Jessica's Machine +# Computador da Jessica $ git push origin master ... To jessica@githost:simplegit.git 1edee6b..fbff5bc master -> master ---- -The last line of the output above shows a useful return message from the push operation. -The basic format is `.. fromref -> toref`, where `oldref` means the old reference, `newref` means the new reference, `fromref` is the name of the local reference being pushed, and `toref` is the name of the remote reference being updated. -You'll see similar output like this below in the discussions, so having a basic idea of the meaning will help in understanding the various states of the repositories. -More details are available in the documentation for https://git-scm.com/docs/git-push[git-push]. +A última linha do resultado acima mostra uma mensagem de retorno útil da operação push. +O formato básico é `.. daref -> pararef`, onde `velharef` significa velha referência, `novaref` significa a nova referência, `daref` é o nome da referência local que está sendo publicada, e `pararef` é o nome da referência remota sendo atualizada. +Você verá resultados semelhantes como este nas discussões seguintes, então ter uma ideia básica do significado irá ajudá-lo entender os vários estados dos repositórios. +Mais detalhes estão disponíveis na documentação aqui https://git-scm.com/docs/git-push[git-push]. -Continuing with this example, shortly afterwards, John makes some changes, commits them to his local repository, and tries to push them to the same server: +Continuando com este exemplo, pouco depois, John faz algumas modificações, um commit no seu repositório local, e tenta dar um push no mesmo servidor: [source,console] ---- -# John's Machine +# Máquina do John $ git push origin master To john@githost:simplegit.git ! [rejected] master -> master (non-fast forward) error: failed to push some refs to 'john@githost:simplegit.git' ---- -In this case, John's push fails because of Jessica's earlier push of _her_ changes. -This is especially important to understand if you're used to Subversion, because you'll notice that the two developers didn't edit the same file. -Although Subversion automatically does such a merge on the server if different files are edited, with Git, you must _first_ merge the commits locally. -In other words, John must first fetch Jessica's upstream changes and merge them into his local repository before he will be allowed to push. +Neste caso, o push do John falhou por causa das alterações do push _que a Jessica fez_ antes. +Isto é especialmente importante de entender se você está acostumado ao Subversion, pois notará que os dois desenvolvedores não editaram o mesmo arquivo. +Embora Subversion automaticamente faz uma mesclagem no servidor se arquivos diferentes foram editados, com Git, você deve _primeiro_ mesclar os commites localmente. +Em outras palavras, John deve primeiro buscar (_fetch_) as modificações anteriores feitas pela Jessica e mesclá-las no seu repositório local antes que ele possa fazer o seu push. -As a first step, John fetches Jessica's work (this only _fetches_ Jessica's upstream work, it does not yet merge it into John's work): +Como um passo inicial, John busca o trabalho de Jessica (apenas buscar o trabalho da Jessica, ainda não mescla no trabalho do John): [source,console] ---- @@ -182,27 +182,27 @@ From john@githost:simplegit + 049d078...fbff5bc master -> origin/master ---- -At this point, John's local repository looks something like this: +Neste ponto, o repositório local do John se parece com isso: -.John's divergent history +.Histórico divergente do John image::images/small-team-1.png[John's divergent history] -Now John can merge Jessica's work that he fetched into his own local work: +Agora John pode mesclar com o trabalho da Jessica que ele buscou no seu local de trabalho: [source,console] ---- $ git merge origin/master Merge made by the 'recursive' strategy. - TODO | 1 + + FAZER | 1 + 1 files changed, 1 insertions(+), 0 deletions(-) ---- -As long as that local merge goes smoothly, John's updated history will now look like this: +Contanto que a mesclagem local seja tranquila, o histórico atualizado do John será parecido com isto: -.John's repository after merging `origin/master` +.Repositório do John depois de mesclar `origin/master` image::images/small-team-2.png[John's repository after merging `origin/master`] -At this point, John might want to test this new code to make sure none of Jessica's work affects any of his and, as long as everything seems fine, he can finally push the new merged work up to the server: +Neste ponto, John deve querer testar este código novo para se certificar que o trabalho da Jessica não afete o seu e, desde que tudo corra bem, ele pode finalmente publicar o novo trabalho combinado no servidor: [source,console] ---- @@ -212,36 +212,36 @@ To john@githost:simplegit.git fbff5bc..72bbc59 master -> master ---- -In the end, John's commit history will look like this: +No fim, o histórico de commit do John ficará assim: -.John's history after pushing to the `origin` server +.Histórico do John depois de publicar no servidor `origin` image::images/small-team-3.png[John's history after pushing to the `origin` server] -In the meantime, Jessica has created a new topic branch called `issue54`, and made three commits to that branch. -She hasn't fetched John's changes yet, so her commit history looks like this: +Enquanto isso, Jessica criou um novo branch chamado `issue54`, e fez três commites naquele branch. +Ela ainda não buscou as alterações do John, então o histórico de commites dela se parece com isso: -.Jessica's topic branch +.Branch atual da Jessica image::images/small-team-4.png[Jessica's topic branch] -Suddenly, Jessica learns that John has pushed some new work to the server and she wants to take a look at it, so she can fetch all new content from the server that she does not yet have with: +De repente, Jessica percebe que o John publicou um trabalho novo no servidor e ela quer dar uma olhada, então ela busca todo o novo conteúdo do servidor que ela ainda não tem: [source,console] ---- -# Jessica's Machine +# Máquina da Jessica $ git fetch origin ... From jessica@githost:simplegit fbff5bc..72bbc59 master -> origin/master ---- -That pulls down the work John has pushed up in the meantime. -Jessica's history now looks like this: +Isto baixa o trabalho que John publicou enquanto isso. +O histórico da Jessica agora fica assim: -.Jessica's history after fetching John's changes +.Histórico da Jessica depois de buscar as mudanças do John image::images/small-team-5.png[Jessica's history after fetching John's changes] -Jessica thinks her topic branch is ready, but she wants to know what part of John's fetched work she has to merge into her work so that she can push. -She runs `git log` to find out: +Jessica acha que seu branch atual está pronto, mas quer saber que parte do trabalho que buscou do John ela deve combinar com o seu para publicar. +Ela executa `git log` para encontrar: [source,console] ---- @@ -250,29 +250,29 @@ commit 738ee872852dfaa9d6634e0dea7a324040193016 Author: John Smith Date: Fri May 29 16:01:27 2009 -0700 - Remove invalid default value + Remover valor padrão inválido ---- -The `issue54..origin/master` syntax is a log filter that asks Git to display only those commits that are on the latter branch (in this case `origin/master`) that are not on the first branch (in this case `issue54`). -We'll go over this syntax in detail in <>. +A sintaxe `issue54..origin/master` é um filtro de log que pede ao Git mostrar apenas estes commites que estão no branch seguinte (neste caso `origin/master`) e não estão no primeiro branch (neste caso `issue54`). +Iremos cobrir esta sintaxe em detalhes em <>. -From the above output, we can see that there is a single commit that John has made that Jessica has not merged into her local work. -If she merges `origin/master`, that is the single commit that will modify her local work. +Do resultado acima, podemos ver que há um único commit que John fez e Jessica não mesclou no trabalho local dela. +Se ela mesclar `origin/master`, aquele é o único commit que irá modificar seu trabalho local. -Now, Jessica can merge her topic work into her `master` branch, merge John's work (`origin/master`) into her `master` branch, and then push back to the server again. +Agora, Jessica pode mesclar seu trabalho atual no branch `master` dela, mesclar o trabalho de John (`origin/master`) no seu branch `master`, e então publicar devolta ao servidor. -First (having committed all of the work on her `issue54` topic branch), Jessica switches back to her `master` branch in preparation for integrating all this work: +Primeiro (tendo feito commit de todo o trabalho no branch atual dela `issue54`), Jessica volta para o seu branch `master` preparando-se para a integração de todo este trabalho: [source,console] ---- $ git checkout master Switched to branch 'master' -Your branch is behind 'origin/master' by 2 commits, and can be fast-forwarded. +Your branch is behind 'origin/master' by 2 commites, and can be fast-forwarded. ---- -Jessica can merge either `origin/master` or `issue54` first -- they're both upstream, so the order doesn't matter. -The end snapshot should be identical no matter which order she chooses; only the history will be different. -She chooses to merge the `issue54` branch first: +Jessica pode mesclar tanto `origin/master` ou `issue54` primeiro -- ambos estão adiantados, então a ordem não importa. +O retrato final deve ser idêntico não importando a ordem que ela escolher; apenas o histórico será diferente. +Ela escolhe mesclar o branch `issue54` antes: [source,console] ---- @@ -284,8 +284,8 @@ Fast forward 2 files changed, 6 insertions(+), 1 deletions(-) ---- -No problems occur; as you can see it was a simple fast-forward merge. -Jessica now completes the local merging process by merging John's earlier fetched work that is sitting in the `origin/master` branch: +Nenhum problema ocorre; como você pode ver foi uma simples combinação direta. +Jessica agora completa o processo local de combinação integrando o trabalho de John buscado anteriormente que estava esperando no branch `origin/master`: [source,console] ---- @@ -296,12 +296,12 @@ Merge made by the 'recursive' strategy. 1 files changed, 1 insertions(+), 1 deletions(-) ---- -Everything merges cleanly, and Jessica's history now looks like this: +Tudo combina bem, e o histórico de Jessica agora se parece com isto: -.Jessica's history after merging John's changes +.Histórico de Jessica depois de integrar com as alterações de John image::images/small-team-6.png[Jessica's history after merging John's changes] -Now `origin/master` is reachable from Jessica's `master` branch, so she should be able to successfully push (assuming John hasn't pushed even more changes in the meantime): +Agora `origin/master` é acessível para o branch `master` de Jessica, então ela deve ser capaz de publicar com sucesso (assumindo que John não publicou nenhuma outra modificação enquanto isso): [source,console] ---- @@ -311,46 +311,46 @@ To jessica@githost:simplegit.git 72bbc59..8059c15 master -> master ---- -Each developer has committed a few times and merged each other's work successfully. +Cada desenvolvedor fez alguns commites e mesclou ao trabalho do outro com sucesso. -.Jessica's history after pushing all changes back to the server +.Histórico de Jessica depois de publicar todas alterações no servidor image::images/small-team-7.png[Jessica's history after pushing all changes back to the server] -That is one of the simplest workflows. -You work for a while (generally in a topic branch), and merge that work into your `master` branch when it's ready to be integrated. -When you want to share that work, you fetch and merge your `master` from `origin/master` if it has changed, and finally push to the `master` branch on the server. -The general sequence is something like this: +Este é um dos mais simples fluxos de trabalho. +Você trabalha um pouco (normalmente em um branch separado), e mescla este trabalho no seu branch `master` quando está pronto para ser integrado. +Quando você quiser compartilhar este trabalho, você busca e mescla seu `master` ao `origin/master` se houve mudanças, e finalmente publica no branch `master` do servidor. +A sequência comum é mais ou menos assim: -.General sequence of events for a simple multiple-developer Git workflow +.Sequência comum de eventos para um fluxo de trabalho simples no Git com múltiplos desenvolvedores image::images/small-team-flow.png[General sequence of events for a simple multiple-developer Git workflow] -==== Private Managed Team +==== Time Privado Gerenciado (((contributing, private managed team))) -In this next scenario, you'll look at contributor roles in a larger private group. -You'll learn how to work in an environment where small groups collaborate on features, after which those team-based contributions are integrated by another party. +No próximo cenário, você irá observar os papéis de um colaborador em um grande grupo privado. +Você irá aprender como trabalhar em um ambiente onde pequenos grupos colaboram em componentes, então as contribuições deste time são integradas por outra equipe. -Let's say that John and Jessica are working together on one feature (call this ``featureA''), while Jessica and a third developer, Josie, are working on a second (say, ``featureB''). -In this case, the company is using a type of integration-manager workflow where the work of the individual groups is integrated only by certain engineers, and the `master` branch of the main repo can be updated only by those engineers. -In this scenario, all work is done in team-based branches and pulled together by the integrators later. +Digamos que John e Jessica estão trabalhando juntos em um componente (chamado `featureA`), enquanto Jessica e uma terceira desenvolvedora, Josie, estão trabalhando num outro (digamos `featureB`). +Neste caso, a companhia está usando um tipo de fluxo de trabalho gerenciado onde o trabalho de grupos isolados é integrado apenas por certos engenheiros, e o branch `master` do repositório principal pode ser atualizado apenas por estes engenheiros. +Neste cenário, todo trabalho é feito em branches da equipe e publicados depois pelos coordenadores. -Let's follow Jessica's workflow as she works on her two features, collaborating in parallel with two different developers in this environment. -Assuming she already has her repository cloned, she decides to work on `featureA` first. -She creates a new branch for the feature and does some work on it there: +Vamos acompanhar o fluxo de trabalho da Jessica enquanto ela trabalha em seus dois componentes, colaborando em paralelo com dois desenvolvedores neste ambiente. +Assumindo que ela já tem seu repositório clonado, ela decide trabalhar no `featureA` antes. +Ela cria um novo branch para o componente e trabalha um pouco nele: [source,console] ---- -# Jessica's Machine +# Máquina da Jessica $ git checkout -b featureA Switched to a new branch 'featureA' $ vim lib/simplegit.rb -$ git commit -am 'Add limit to log function' -[featureA 3300904] Add limit to log function +$ git commit -am 'Adicionar limite a função log' +[featureA 3300904] Adicionar limite a função log 1 files changed, 1 insertions(+), 1 deletions(-) ---- -At this point, she needs to share her work with John, so she pushes her `featureA` branch commits up to the server. -Jessica doesn't have push access to the `master` branch -- only the integrators do -- so she has to push to another branch in order to collaborate with John: +Neste ponto, ela precisa compartilhar seu trabalho com John, então ela publica seus commites no branch `featureA` do servidor. +Jessica não tem permissão de publicar no branch `master` -- apenas os coordenadores tem -- então ela publica em outro branch para trabalhar com John: [source,console] ---- @@ -360,40 +360,40 @@ To jessica@githost:simplegit.git * [new branch] featureA -> featureA ---- -Jessica emails John to tell him that she's pushed some work into a branch named `featureA` and he can look at it now. -While she waits for feedback from John, Jessica decides to start working on `featureB` with Josie. -To begin, she starts a new feature branch, basing it off the server's `master` branch: +Jessica comunica John que publicou alguma coisa no branch chamado `featureA` e ele pode dar uma olhada agora. +Enquanto ela espera John responder, Jessica decide começar a trabalhar no `featureB` com Josie. +Para começar, ela cria um novo branch para o componente, baseando-se no branch `master` do servidor: [source,console] ---- -# Jessica's Machine +# Máquina da Jessica $ git fetch origin $ git checkout -b featureB origin/master Switched to a new branch 'featureB' ---- -Now, Jessica makes a couple of commits on the `featureB` branch: +Agora Jessica faz alguns commites no branch `featureB`: [source,console] ---- $ vim lib/simplegit.rb -$ git commit -am 'Make ls-tree function recursive' -[featureB e5b0fdc] Make ls-tree function recursive +$ git commit -am 'Tornar a função ls-tree recursiva' +[featureB e5b0fdc] Tornar a função ls-tree recursiva 1 files changed, 1 insertions(+), 1 deletions(-) $ vim lib/simplegit.rb -$ git commit -am 'Add ls-files' -[featureB 8512791] Add ls-files +$ git commit -am 'Adicionar ls-files' +[featureB 8512791] Adicionar ls-files 1 files changed, 5 insertions(+), 0 deletions(-) ---- -Jessica's repository now looks like this: +O repositório de Jessica agora fica assim: -.Jessica's initial commit history +.Histórico do commit inical de Jessica image::images/managed-team-1.png[Jessica's initial commit history] -She's ready to push her work, but gets an email from Josie that a branch with some initial ``featureB'' work on it was already pushed to the server as the `featureBee` branch. -Jessica needs to merge those changes with her own before she can push her work to the server. -Jessica first fetches Josie's changes with `git fetch`: +Ela já está pronta para publicar seu trabalho, mas recebe um email de Josie dizendo que um branch contendo um `featureB` inicial já foi publicado no servidor como `featureBee`. +Jessica precisa combinar estas alterações com as suas antes que ela possa publicar seu trabalho no servidor. +Jessica primeiro busca as mudanças de Josie com `git fetch`: [source,console] ---- @@ -403,7 +403,7 @@ From jessica@githost:simplegit * [new branch] featureBee -> origin/featureBee ---- -Assuming Jessica is still on her checked-out `featureB` branch, she can now merge Josie's work into that branch with `git merge`: +Assumindo que Jessica ainda está no seu branch `featureB`, ela pode agora incorporar o trabalho de Josie neste branch com `git merge`: [source,console] ---- @@ -414,8 +414,8 @@ Merge made by the 'recursive' strategy. 1 files changed, 4 insertions(+), 0 deletions(-) ---- -At this point, Jessica wants to push all of this merged ``featureB'' work back to the server, but she doesn't want to simply push her own `featureB` branch. -Rather, since Josie has already started an upstream `featureBee` branch, Jessica wants to push to _that_ branch, which she does with: +Neste ponto, Jessica quer publicar todo este `featureB` mesclado no servidor, mas ela não quer simplesmente publicar no seu branch `featureB`. +Ao invés disso, como Josie já começou um branch `featureBee`, Jessica quer publicar _neste_ branch, que ela faz assim: [source,console] ---- @@ -425,12 +425,12 @@ To jessica@githost:simplegit.git fba9af8..cd685d1 featureB -> featureBee ---- -This is called a _refspec_. -See <> for a more detailed discussion of Git refspecs and different things you can do with them. -Also notice the `-u` flag; this is short for `--set-upstream`, which configures the branches for easier pushing and pulling later. +Isto é chamado de _refspec_. +Veja <> para uma discussão mais detalhada sobre os refspecs do Git e as diferentes coisas que você pode fazer com eles. +Também perceba a flag `-u`; isto é abreviação de `--set-upstream`, que configura os branches para facilitar publicar e baixar depois. -Suddenly, Jessica gets email from John, who tells her he's pushed some changes to the `featureA` branch on which they are collaborating, and he asks Jessica to take a look at them. -Again, Jessica runs a simple `git fetch` to fetch _all_ new content from the server, including (of course) John's latest work: +De repente, Jessica recebe um email de John, contando que publicou algumas modificações no branch `featureA` no qual eles estavam colaborando, e ele pede a Jessica para dar uma olhada. +Denovo, Jessica executa um simples `git fetch` para buscar _todo_ novo conteúdo do servidor, incluindo (é claro) o último trabalho de John: [source,console] ---- @@ -440,7 +440,7 @@ From jessica@githost:simplegit 3300904..aad881d featureA -> origin/featureA ---- -Jessica can display the log of John's new work by comparing the content of the newly-fetched `featureA` branch with her local copy of the same branch: +Jessica pode exibir o log do novo trabalho de John comparando o conteúdo do branch `featureA` recentemente buscado com sua cópia local do mesmo branch: [source,console] ---- @@ -449,10 +449,10 @@ commit aad881d154acdaeb2b6b18ea0e827ed8a6d671e6 Author: John Smith Date: Fri May 29 19:57:33 2009 -0700 - Increase log output to 30 from 25 + Aumentar resultados do log para 30 de 25 ---- -If Jessica likes what she sees, she can merge John's new work into her local `featureA` branch with: +Se Jessica gostar do que vê, ela pode integrar o recente trabalho de John no seu branch `featureA` local com: [source,console] ---- @@ -465,12 +465,12 @@ Fast forward 1 files changed, 9 insertions(+), 1 deletions(-) ---- -Finally, Jessica might want to make a couple minor changes to all that merged content, so she is free to make those changes, commit them to her local `featureA` branch, and push the end result back to the server: +Finalmente, Jessica pode querer fazer algumas pequenas alterações de todo o conteúdo mesclado, então ela está livre para fazer estas mudanças, commitar elas no seu branch `featureA` local, e publicar o resultado de volta ao servidor: [source,console] ---- -$ git commit -am 'Add small tweak to merged content' -[featureA 774b3ed] Add small tweak to merged content +$ git commit -am 'Adicionar pequeno ajuste ao conteúdo mesclado' +[featureA 774b3ed] Adicionar pequeno ajuste ao conteúdo mesclado 1 files changed, 1 insertions(+), 1 deletions(-) $ git push ... @@ -478,208 +478,208 @@ To jessica@githost:simplegit.git 3300904..774b3ed featureA -> featureA ---- -Jessica's commit history now looks something like this: +O histórico de commites da Jessica agora está assim: -.Jessica's history after committing on a feature branch +.Histórico da Jessica depois dos commites em um branch de componentes image::images/managed-team-2.png[Jessica's history after committing on a feature branch] -At some point, Jessica, Josie, and John inform the integrators that the `featureA` and `featureBee` branches on the server are ready for integration into the mainline. -After the integrators merge these branches into the mainline, a fetch will bring down the new merge commit, making the history look like this: +Em algum ponto, Jessica, Josie e John informam os coordenadores que os branches `featureA` e `featureBee` no servidor estão prontos para serem integrados no código principal. +Depois dos coordenadores mesclarem estes branches no código principal, um _fetch_ trará o novo commit mesclado, deixando o histórico assim: -.Jessica's history after merging both her topic branches +.Histórico da Jessica depois de integrar ambos seus branches image::images/managed-team-3.png[Jessica's history after merging both her topic branches] -Many groups switch to Git because of this ability to have multiple teams working in parallel, merging the different lines of work late in the process. -The ability of smaller subgroups of a team to collaborate via remote branches without necessarily having to involve or impede the entire team is a huge benefit of Git. -The sequence for the workflow you saw here is something like this: +Muitos grupos migraram para o Git pela possibilidade de ter múltiplos times trabalhando em paralelo, combinando as diferentes frentes de trabalho mais tarde no processo. +A habilidade de pequenos subgrupos da equipe colaborar através de branches remotos sem necessariamente ter que envolver ou atrasar a equipe inteira é um benefício imenso do Git. +A sequência do fluxo de trabalho que você viu aqui é parecida com isto: -.Basic sequence of this managed-team workflow +.Sequencia básica deste fluxo de trabalho coordenado image::images/managed-team-flow.png[Basic sequence of this managed-team workflow] [[r_public_project]] -==== Forked Public Project +==== Fork de Projeto Público (((contributing, public small project))) -Contributing to public projects is a bit different. -Because you don't have the permissions to directly update branches on the project, you have to get the work to the maintainers some other way. -This first example describes contributing via forking on Git hosts that support easy forking. -Many hosting sites support this (including GitHub, BitBucket, repo.or.cz, and others), and many project maintainers expect this style of contribution. -The next section deals with projects that prefer to accept contributed patches via email. +Colaborando com projetos públicos é um pouco diferente. +Como você não tem as permissões para atualizar diretamente branches no projeto, você deve levar seu trabalho aos coordenadores de algum jeito diferente. +O primeiro exemplo descreve como contribuir através de _forks_ em um site de hospedagem Git que permite fazer forks facilmente. +Muitos sites de hospedagem suportam isto (incluindo GitHub, BitBucket, repo.or.cz, e outros), e muitos mantenedores de projetos esperam este estilo de contribuição. +A próxima seção lida com projetos que preferem aceitar patches de contribuição por email. -First, you'll probably want to clone the main repository, create a topic branch for the patch or patch series you're planning to contribute, and do your work there. -The sequence looks basically like this: +Primeiro, você provavelmente irá preferir clonar o repositório principal, criar um branch específico para o patch ou série de patchs que está planejando contribuir, e fazer o seu trabalho ali. +A sequência fica basicamente assim: [source,console] ---- $ git clone $ cd project $ git checkout -b featureA - ... work ... + ... trabalho ... $ git commit - ... work ... + ... trabalho ... $ git commit ---- [NOTE] ==== -You may want to use `rebase -i` to squash your work down to a single commit, or rearrange the work in the commits to make the patch easier for the maintainer to review -- see <> for more information about interactive rebasing. +Você pode querer usar `rebase -i` para resumir seu trabalho a um único commit, ou rearranjar o trabalho em commites que deixarão o trabalho mais fácil para os mantenedores revisarem -- veja <> para mais informações sobre rebase interativo. ==== -When your branch work is finished and you're ready to contribute it back to the maintainers, go to the original project page and click the ``Fork'' button, creating your own writable fork of the project. -You then need to add this repository URL as a new remote of your local repository; in this example, let's call it `myfork`: +Quando seu trabalho no branch é finalizado e você está pronto para mandá-lo para os mantenedores, vá para a página original do projeto e clique no botão ``Fork'', criando seu próprio fork editável do projeto. +Você precisa então adicionar a URL deste repositório como um novo repositório remoto do seu repositório local; neste exemplo, vamos chamá-lo `meufork`: [source,console] ---- -$ git remote add myfork +$ git remote add meufork ---- -You then need to push your new work to this repository. -It's easiest to push the topic branch you're working on to your forked repository, rather than merging that work into your `master` branch and pushing that. -The reason is that if your work isn't accepted or is cherry-picked, you don't have to rewind your `master` branch (the Git `cherry-pick` operation is covered in more detail in <>). -If the maintainers `merge`, `rebase`, or `cherry-pick` your work, you'll eventually get it back via pulling from their repository anyhow. +Você então precisa publicar seu trabalho neste repositório. +É mais fácil publicar o branch em que você está trabalhando no seu repositório fork, ao invés de mesclar este trabalho no seu branch `master` e publicar assim. +A razão é que se o seu trabalho não for aceito ou for selecionado a dedo (_cherry-pick_), você não tem que voltar seu branch `master` (a operação do Git `cherry-pick` é vista em mais detalhes em <>). +Se os mantenedores executarem um `merge`, `rebase` ou `cherry-pick` no seu trabalho, você irá eventualmente receber seu trabalho de novo através do repositório deles de qualquer jeito. -In any event, you can push your work with: +Em qualquer um dos casos, você pode publicar seu trabalho com: [source,console] ---- -$ git push -u myfork featureA +$ git push -u meufork featureA ---- (((git commands, request-pull))) -Once your work has been pushed to your fork of the repository, you need to notify the maintainers of the original project that you have work you'd like them to merge. -This is often called a _pull request_, and you typically generate such a request either via the website -- GitHub has its own ``Pull Request'' mechanism that we'll go over in <> -- or you can run the `git request-pull` command and email the subsequent output to the project maintainer manually. +Uma vez que seu trabalho tenha sido publicado no repositório do seu fork, você deve notificar os mantenedores do projeto original que você tem trabalho que gostaria que eles incorporassem no código. +Isto é comumente chamado de _pull request_, e você tipicamente gera esta requisição ou através do website -- GitHub tem seu próprio mecanismo de ``Pull Request'' que iremos abordar em #<># -- ou você pode executar o comando `git request-pull` e mandar um email com o resultado para o mantenedor do projeto manualmente. -The `git request-pull` command takes the base branch into which you want your topic branch pulled and the Git repository URL you want them to pull from, and produces a summary of all the changes you're asking to be pulled. -For instance, if Jessica wants to send John a pull request, and she's done two commits on the topic branch she just pushed, she can run this: +O comando `git request-pull` pega o branch base no qual você quer o seu branch atual publicado e a URL do repositório Git de onde você vai buscar, e produz um resumo de todas as mudanças que você está tentando publicar. +Por exemplo, se Jessica quer mandar a John uma pull request, e ela fez dois commites no branch que ela acabou de publicar, ela pode executar: [source,console] ---- -$ git request-pull origin/master myfork +$ git request-pull origin/master meufork The following changes since commit 1edee6b1d61823a2de3b09c160d7080b8d1b3a40: Jessica Smith (1): - Create new function + Criar nova função are available in the git repository at: git://githost/simplegit.git featureA Jessica Smith (2): - Add limit to log function - Increase log output to 30 from 25 + Adicionar limite para a função log + Aumentar a saída do log para 30 de 25 lib/simplegit.rb | 10 +++++++++- 1 files changed, 9 insertions(+), 1 deletions(-) ---- -This output can be sent to the maintainer -- it tells them where the work was branched from, summarizes the commits, and identifies from where the new work is to be pulled. +Este resultado pode ser mandado para os mantenedores -- ele diz de qual branch o trabalho vem, resume os commites, e identifica onde o novo trabalho será publicado. -On a project for which you're not the maintainer, it's generally easier to have a branch like `master` always track `origin/master` and to do your work in topic branches that you can easily discard if they're rejected. -Having work themes isolated into topic branches also makes it easier for you to rebase your work if the tip of the main repository has moved in the meantime and your commits no longer apply cleanly. -For example, if you want to submit a second topic of work to the project, don't continue working on the topic branch you just pushed up -- start over from the main repository's `master` branch: +Em um projeto em que você não é um mantenedor, é geralmente mais fácil ter um branch principal `master` sempre rastreando `origin/master` e fazer seu trabalho em branches separados que você pode facilmente descartar se eles forem rejeitados. +Tendo temas de trabalho isolados em branches próprios também facilita para você realocar seu trabalho se a ponta do repositório principal se mover enquanto trabalha e seus commites não mais puderem ser aplicados diretamente. +Por exemplo, se você quer publicar um segundo trabalho numa outra área do projeto, não continue trabalhando no branch que você acabou de publicar -- comece um novo branch apartir do branch no repositório principal `master`: [source,console] ---- $ git checkout -b featureB origin/master - ... work ... + ... trabalho ... $ git commit -$ git push myfork featureB -$ git request-pull origin/master myfork +$ git push meufork featureB +$ git request-pull origin/master meufork ... email generated request pull to maintainer ... $ git fetch origin ---- -Now, each of your topics is contained within a silo -- similar to a patch queue -- that you can rewrite, rebase, and modify without the topics interfering or interdepending on each other, like so: +Agora, cada um dos seus assuntos está contido em um casulo -- igual a um patch na fila -- que você pode reescrever, realocar, e modificar sem que os outros assuntos interfiram com ele, deste jeito: -.Initial commit history with `featureB` work +.Histórico de commites inicial com o trabalho `featureB` image::images/public-small-1.png[Initial commit history with `featureB` work] -Let's say the project maintainer has pulled in a bunch of other patches and tried your first branch, but it no longer cleanly merges. -In this case, you can try to rebase that branch on top of `origin/master`, resolve the conflicts for the maintainer, and then resubmit your changes: +Digamos que o mantenedor do projeto tenha integrado vários outros patches e, quando tentou seu primeiro branch, seu trabalho não mais combina facilmente. +Neste caso, você pode tentar realocar seu branch no topo de `origin/master`, resolver os conflitos para o mantenedor, e então republicar suas alterações: [source,console] ---- $ git checkout featureA $ git rebase origin/master -$ git push -f myfork featureA +$ git push -f meufork featureA ---- -This rewrites your history to now look like <>. +Isto reescreve seu histórico que agora fica assim <>. [[psp_b]] -.Commit history after `featureA` work +.Histórico de commites depois do trabalho em `featureA` image::images/public-small-2.png[Commit history after `featureA` work] -Because you rebased the branch, you have to specify the `-f` to your push command in order to be able to replace the `featureA` branch on the server with a commit that isn't a descendant of it. -An alternative would be to push this new work to a different branch on the server (perhaps called `featureAv2`). +Como você realocou seu branch, você deve especificar `-f` para seu comando push substituir o branch `featureA` no servidor com um commit que não é um descendente dele. +Uma alternativa seria publicar seu novo trabalho em um branch diferente no servidor (talvez chamado `featureAv2`). -Let's look at one more possible scenario: the maintainer has looked at work in your second branch and likes the concept but would like you to change an implementation detail. -You'll also take this opportunity to move the work to be based off the project's current `master` branch. -You start a new branch based off the current `origin/master` branch, squash the `featureB` changes there, resolve any conflicts, make the implementation change, and then push that as a new branch: +Vamos olhar um outro cenário possível: o mantenedor viu seu trabalho no seu branch secundário e gosta do conceito mas gostaria que você mudasse um detalhe de implementação. +Você aproveita esta oportunidade para basear seu trabalho no branch `master` do projeto atual. +Você inicia um novo branch baseado no branch `origin/master` atual, compacta (_squash_) as mudanças do `featureB` ali, resolve qualquer conflito, faz a mudança de implementação, e então publica isto como um novo branch: (((git commands, merge, squash))) [source,console] ---- $ git checkout -b featureBv2 origin/master $ git merge --squash featureB - ... change implementation ... + ... mudando implementação ... $ git commit -$ git push myfork featureBv2 +$ git push meufork featureBv2 ---- -The `--squash` option takes all the work on the merged branch and squashes it into one changeset producing the repository state as if a real merge happened, without actually making a merge commit. -This means your future commit will have one parent only and allows you to introduce all the changes from another branch and then make more changes before recording the new commit. -Also the `--no-commit` option can be useful to delay the merge commit in case of the default merge process. +A opção `--squash` pega todo o trabalho no branch mesclado e comprime em um novo conjunto gerando um novo estado de repositório como se uma mescla real tivesse acontecido, sem realmente mesclar os commites. +Isto significa que seu commit futuro terá um pai apenas e te permite introduzir todas as mudanças de um outro branch e então aplicar mais alterações antes de gravar seu novo commit. +A opção `--no-commit` também pode ser útil para atrasar a integração do commit no caso do processo de mesclagem padrão. -At this point, you can notify the maintainer that you've made the requested changes, and that they can find those changes in your `featureBv2` branch. +Neste ponto, você pode notificar os mantenedores que você já fez as mudanças pedidas, e que eles podem encontrá-las no branch `featureBv2`. -.Commit history after `featureBv2` work +.Histórico de commit depois do trabalho em `featureBv2` image::images/public-small-3.png[Commit history after `featureBv2` work] [[r_project_over_email]] -==== Public Project over Email +==== Projeto Público através de Email (((contributing, public large project))) -Many projects have established procedures for accepting patches -- you'll need to check the specific rules for each project, because they will differ. -Since there are several older, larger projects which accept patches via a developer mailing list, we'll go over an example of that now. +Muitos projetos têm procedimentos estabelecidos para aceitar patches -- você irá precisar checar as regras específicas para cada projeto, pois elas serão diferentes. +Já que existem vários projetos mais antigos, maiores, que aceitam patches através de uma lista de emails de desenvolvedores, iremos exemplificar isto agora: -The workflow is similar to the previous use case -- you create topic branches for each patch series you work on. -The difference is how you submit them to the project. -Instead of forking the project and pushing to your own writable version, you generate email versions of each commit series and email them to the developer mailing list: +O fluxo de trabalho é parecido ao caso anterior -- você cria branches separados para cada série de patches em que trabalhar. +A diferença é como enviá-los ao projeto. +Ao invés de fazer um fork do projeto e publicar sua própria versão editável, você gera versões de email de cada série de commites e as envia para a lista de email dos desenvolvedores: [source,console] ---- -$ git checkout -b topicA - ... work ... +$ git checkout -b assuntoA + ... trabalho ... $ git commit - ... work ... + ... trabalho ... $ git commit ---- (((git commands, format-patch))) -Now you have two commits that you want to send to the mailing list. -You use `git format-patch` to generate the mbox-formatted files that you can email to the list -- it turns each commit into an email message with the first line of the commit message as the subject and the rest of the message plus the patch that the commit introduces as the body. -The nice thing about this is that applying a patch from an email generated with `format-patch` preserves all the commit information properly. +Agora você tem dois commites que gostaria de enviar para a lista de email. +Você pode usar `git format-patch` para gerar os arquivos formatados em mbox e enviar para a lista de email -- isto transforma cada commit em uma mensagem de email, com a primeira linha da mensagem do commit como o assunto, e o resto da mensagem mais o patch que o commit traz como o corpo do email. +O legal disto é que aplicar um patch de email gerado com `format-patch` preserva todas as informações de commit corretamente. [source,console] ---- $ git format-patch -M origin/master -0001-add-limit-to-log-function.patch -0002-increase-log-output-to-30-from-25.patch +0001-adicionar-limite-para-a-função-log.patch +0002-aumentar-a-saída-do-log-para-30-de-25.patch ---- -The `format-patch` command prints out the names of the patch files it creates. -The `-M` switch tells Git to look for renames. -The files end up looking like this: +O comando `format-patch` exibe os nomes dos arquivos de patch que cria. +A chave `-M` diz ao Git para procurar por renomeações. +Os arquivos acabam se parecendo com isto: [source,console] ---- -$ cat 0001-add-limit-to-log-function.patch +$ cat 0001-adicionar-limite-para-a-função-log.patch From 330090432754092d704da8e76ca5c05c198e71a8 Mon Sep 17 00:00:00 2001 From: Jessica Smith Date: Sun, 6 Apr 2008 10:17:23 -0700 -Subject: [PATCH 1/2] Add limit to log function +Subject: [PATCH 1/2] Adicionar limite a função log -Limit log functionality to the first 20 +Limitar a função log aos primeiros 20 --- lib/simplegit.rb | 2 +- @@ -702,31 +702,31 @@ index 76f47bc..f9815f1 100644 2.1.0 ---- -You can also edit these patch files to add more information for the email list that you don't want to show up in the commit message. -If you add text between the `---` line and the beginning of the patch (the `diff --git` line), the developers can read it, but that content is ignored by the patching process. +Você também pode editar estes arquivos de patch para adicionar mais informação para a lista de email que você não gostaria de colocar na mensagem do commit. +Se você adicionar texto entre a linha `---` e o começo do patch (a linha `diff --git), os desenvolvedores podem ler, mas o conteúdo é ignorado pelo processo de patch. -To email this to a mailing list, you can either paste the file into your email program or send it via a command-line program. -Pasting the text often causes formatting issues, especially with ``smarter'' clients that don't preserve newlines and other whitespace appropriately. -Luckily, Git provides a tool to help you send properly formatted patches via IMAP, which may be easier for you. -We'll demonstrate how to send a patch via Gmail, which happens to be the email agent we know best; you can read detailed instructions for a number of mail programs at the end of the aforementioned `Documentation/SubmittingPatches` file in the Git source code. +Para enviar este email para uma lista de emails, você pode tanto colar o arquivo no seu programa de email quanto enviar via um programa de linha de comando. +Colar o texto geralmente causa problemas de formatação, especialmente com programas ``inteligentes`` que não preservam novas linhas e espaços em branco corretamente. +Felizmente, o Git fornece uma ferramenta para ajudar você enviar patches formatados adequadamente através de IMAP, o que pode ser mais fácil para você. +Iremos demonstrar como enviar um patch via Gmail, no caso o veículo que conhecemos melhor; você pode ler instruções detalhadas de vários programas de email no final do acima mencionado arquivo `Documentation/SubmittingPatches` no código fonte do Git. (((git commands, config)))(((email))) -First, you need to set up the imap section in your `~/.gitconfig` file. -You can set each value separately with a series of `git config` commands, or you can add them manually, but in the end your config file should look something like this: +Primeiro, você deve configurar a seção imap no seu arquivo `~/.gitconfig`. +Você pode configurar cada valor separadamente com uma série de comandos `git config`, ou adicioná-los manualmente, mas no final seu arquivo config deve ficar assim: [source,ini] ---- [imap] - folder = "[Gmail]/Drafts" + folder = "[Gmail]/Rascunhos" host = imaps://imap.gmail.com - user = user@gmail.com + user = usuario@gmail.com pass = YX]8g76G_2^sFbd port = 993 sslverify = false ---- -If your IMAP server doesn't use SSL, the last two lines probably aren't necessary, and the host value will be `imap://` instead of `imaps://`. -When that is set up, you can use `git imap-send` to place the patch series in the Drafts folder of the specified IMAP server: +Se o seu servidor IMAP não usa SSL, as duas últimas linhas provavelmente não são necessárias, e o valor de host será `imap://` ao invés de `imaps://`. +Quando isto estiver pronto, você poderá usar `git imap-send` para colocar os seus patches no diretório Rascunhos no servidor IMAP especificado: [source,console] ---- @@ -738,34 +738,34 @@ sending 2 messages 100% (2/2) done ---- -At this point, you should be able to go to your Drafts folder, change the To field to the mailing list you're sending the patch to, possibly CC the maintainer or person responsible for that section, and send it off. +Neste ponto, você deve poder ir ao seu diretório Rascunhos, mudar o campo Para com a lista de email para qual você está mandando o patch, possivelmente copiando (_CC_) os mantenedores ou pessoas responsáveis pela seção, e enviar o patch. -You can also send the patches through an SMTP server. -As before, you can set each value separately with a series of `git config` commands, or you can add them manually in the sendemail section in your `~/.gitconfig` file: +Você também pode enviar os patches através de um servidor SMTP. +Como antes, você pode configurar cada valor separadamente com uma série de comandos `git config`, ou você pode adicioná-los manualmente na seção sendemail no seu arquivo `~/.gitconfig`: [source,ini] ---- [sendemail] smtpencryption = tls smtpserver = smtp.gmail.com - smtpuser = user@gmail.com + smtpuser = usuario@gmail.com smtpserverport = 587 ---- -After this is done, you can use `git send-email` to send your patches: +Depois que isto estiver pronto, você pode usar `git send-email` para enviar os seus patches: [source,console] ---- $ git send-email *.patch -0001-add-limit-to-log-function.patch -0002-increase-log-output-to-30-from-25.patch +0001-adicionar-limite-para-a-função-log.patch +0002-aumentar-a-saída-do-log-para-30-de-25.patch Who should the emails appear to be from? [Jessica Smith ] Emails will be sent from: Jessica Smith Who should the emails be sent to? jessica@example.com Message-ID to be used as In-Reply-To for the first email? y ---- -Then, Git spits out a bunch of log information looking something like this for each patch you're sending: +Então, o Git retorna várias informações de log, para cada patch que você está enviando: [source,text] ---- @@ -775,7 +775,7 @@ OK. Log says: Sendmail: /usr/sbin/sendmail -i jessica@example.com From: Jessica Smith To: jessica@example.com -Subject: [PATCH 1/2] Add limit to log function +Subject: [PATCH 1/2] Adicionar limite a função log Date: Sat, 30 May 2009 13:29:15 -0700 Message-Id: <1243715356-61726-1-git-send-email-jessica@example.com> X-Mailer: git-send-email 1.6.2.rc1.20.g8c5b.dirty @@ -787,16 +787,16 @@ Result: OK [TIP] ==== -For help on configuring your system and email, more tips and tricks, and a sandbox to send a trial patch via email, go to [git-send-email.io](https://git-send-email.io/). +Se quiser ajuda para configurar seu sistema de email, mais dicas e truques, e um ambiente controlado para enviar um patch de teste através de email, acesse [git-send-email.io](https://git-send-email.io/). ==== -==== Summary +==== Resumo -In this section, we covered multiple workflows, and talked about the differences between working as part of a small team on closed-source projects vs contributing to a big public project. -You know to check for white-space errors before committing, and can write a great commit message. -You learned how to format patches, and e-mail them to a developer mailing list. -Dealing with merges was also covered in the context of the different workflows. -You are now well prepared to collaborate on any project. +Nesta seção nós abordamos múltiplos fluxos de trabalho, e falamos sobre as diferenças entre trabalhar como parte de uma equipe pequena em projetos de código fechado, e contribuir para um grande projeto público. +Você sabe checar por erros de espaços em branco antes do seu commit, e pode escrever uma excelente mensagem nele. +Você aprendeu como formatar patches, e enviá-los por email para a lista de desenvolvedores. +Lidando com combinações também foi coberto no contexto de diferentes fluxos de trabalho. +Você está agora bem preparado para colaborar com qualquer projeto. -Next, you'll see how to work the other side of the coin: maintaining a Git project. -You'll learn how to be a benevolent dictator or integration manager. +A seguir, você verá como trabalhar no outro lado da moeda: mantendo um projeto Git. +Aprenderá como ser um ditador benevolente ou um coordenador. From c0c48190c6159ec35aa9588e121355aaf1813e31 Mon Sep 17 00:00:00 2001 From: Flavio V Filho Date: Wed, 9 Jun 2021 11:46:39 -0300 Subject: [PATCH 2/2] Reenviar cap 5.2 --- book/05-distributed-git/sections/contributing.asc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/book/05-distributed-git/sections/contributing.asc b/book/05-distributed-git/sections/contributing.asc index c582ac88..c237b4ba 100644 --- a/book/05-distributed-git/sections/contributing.asc +++ b/book/05-distributed-git/sections/contributing.asc @@ -1,5 +1,5 @@ [[r_contributing_project]] -=== Contributing to a Project +=== Contribuindo com um Projeto (((contributing))) A principal dificuldade em descrever como contribuir com um projeto é a numerosa quantidade de maneiras de contribuir.