From 3741f12a505ea033ffa1e830e1ac80040aa54478 Mon Sep 17 00:00:00 2001 From: "Sergio Cabral (AI Agent)" Date: Thu, 20 Aug 2026 13:51:56 -0300 Subject: [PATCH 01/16] =?UTF-8?q?Traduz:=20Licen=C3=A7a?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- LICENSE.asc | 4 ++-- book/license.asc | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/LICENSE.asc b/LICENSE.asc index 5aceb9e9..ec9ee853 100644 --- a/LICENSE.asc +++ b/LICENSE.asc @@ -1,2 +1,2 @@ -This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. -To view a copy of this license, visit https://creativecommons.org/licenses/by-nc-sa/3.0 or send a letter to Creative Commons, PO Box 1866, Mountain View, CA 94042, USA. +Esta obra está licenciada sob a Licença Creative Commons Atribuição-NãoComercial-CompartilhaIgual 3.0 Não Adaptada. +Para ver uma cópia desta licença, visite https://creativecommons.org/licenses/by-nc-sa/3.0 ou envie uma carta para Creative Commons, PO Box 1866, Mountain View, CA 94042, USA. diff --git a/book/license.asc b/book/license.asc index 090996ab..65322b20 100644 --- a/book/license.asc +++ b/book/license.asc @@ -1,4 +1,4 @@ [preface] -== License +== Licença include::../LICENSE.asc[] From 6dc835b00aa4e63f70d9a8911ade4b2d7dbe9519 Mon Sep 17 00:00:00 2001 From: "Sergio Cabral (AI Agent)" Date: Thu, 20 Aug 2026 13:51:56 -0300 Subject: [PATCH 02/16] =?UTF-8?q?Traduz:=20Elementos=20pr=C3=A9-textuais?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- book/dedication.asc | 8 ++-- book/introduction.asc | 82 ++++++++++++++++++++-------------------- book/preface_ben.asc | 16 ++++---- book/preface_schacon.asc | 54 +++++++++++++------------- index.asc | 2 +- 5 files changed, 81 insertions(+), 81 deletions(-) diff --git a/book/dedication.asc b/book/dedication.asc index 0c75ccb4..f1a877b1 100644 --- a/book/dedication.asc +++ b/book/dedication.asc @@ -1,7 +1,7 @@ [dedication] -== Dedications +== Dedicatórias -_To my wife, Becky, without whom this adventure never would have begun. — Ben_ +_Para minha esposa, Becky, sem a qual esta aventura nunca teria começado. — Ben_ -_This edition is dedicated to my girls. -To my wife Jessica who has supported me for all of these years and to my daughter Josephine, who will support me when I'm too old to know what's going on. — Scott_ +_Esta edição é dedicada às minhas garotas. +Para minha esposa Jessica que me apoiou por todos esses anos e para minha filha Josephine, que me apoiará quando eu for velho demais para saber o que está acontecendo. — Scott_ diff --git a/book/introduction.asc b/book/introduction.asc index 23b261dc..387c6188 100644 --- a/book/introduction.asc +++ b/book/introduction.asc @@ -1,57 +1,57 @@ [preface] -== Introduction +== Introdução -You're about to spend several hours of your life reading about Git. -Let's take a minute to explain what we have in store for you. -Here is a quick summary of the ten chapters and three appendices of this book. +Você está prestes a passar várias horas da sua vida lendo sobre o Git. +Vamos tirar um minuto para explicar o que temos reservado para você. +Aqui está um breve resumo dos dez capítulos e três apêndices deste livro. -In *Chapter 1*, we're going to cover Version Control Systems (VCSs) and Git basics -- no technical stuff, just what Git is, why it came about in a land full of VCSs, what sets it apart, and why so many people are using it. -Then, we'll explain how to download Git and set it up for the first time if you don't already have it on your system. +No *Capítulo 1*, vamos abordar os Sistemas de Controle de Versão (VCSs) e o básico do Git -- nada técnico, apenas o que o Git é, por que ele surgiu em uma terra cheia de VCSs, o que o diferencia e por que tantas pessoas o estão usando. +Em seguida, explicaremos como baixar o Git e configurá-lo pela primeira vez, se você ainda não o tem no seu sistema. -In *Chapter 2*, we will go over basic Git usage -- how to use Git in the 80% of cases you'll encounter most often. -After reading this chapter, you should be able to clone a repository, see what has happened in the history of the project, modify files, and contribute changes. -If the book spontaneously combusts at this point, you should already be pretty useful wielding Git in the time it takes you to go pick up another copy. +No *Capítulo 2*, abordaremos o uso básico do Git -- como usar o Git em 80% dos casos que você encontrará com mais frequência. +Depois de ler este capítulo, você deve ser capaz de clonar um repositório, ver o que aconteceu no histórico do projeto, modificar arquivos e contribuir com alterações. +Se o livro entrar em combustão espontânea neste ponto, você já deve ser bastante útil manejando o Git no tempo que levar para ir pegar outra cópia. -*Chapter 3* is about the branching model in Git, often described as Git's killer feature. -Here you'll learn what truly sets Git apart from the pack. -When you're done, you may feel the need to spend a quiet moment pondering how you lived before Git branching was part of your life. +O *Capítulo 3* é sobre o modelo de ramificação (branching) no Git, frequentemente descrito como a funcionalidade matadora do Git. +Aqui você aprenderá o que realmente diferencia o Git do resto do grupo. +Quando você terminar, pode sentir a necessidade de passar um momento tranquilo ponderando como você viveu antes que as ramificações do Git fizessem parte da sua vida. -*Chapter 4* will cover Git on the server. -This chapter is for those of you who want to set up Git inside your organization or on your own personal server for collaboration. -We will also explore various hosted options if you prefer to let someone else handle that for you. +O *Capítulo 4* abordará o Git no servidor. +Este capítulo é para aqueles de vocês que desejam configurar o Git dentro de sua organização ou em seu próprio servidor pessoal para colaboração. +Também exploraremos várias opções hospedadas se você preferir deixar que outra pessoa cuide disso para você. -*Chapter 5* will go over in full detail various distributed workflows and how to accomplish them with Git. -When you are done with this chapter, you should be able to work expertly with multiple remote repositories, use Git over email and deftly juggle numerous remote branches and contributed patches. +O *Capítulo 5* detalhará vários fluxos de trabalho distribuídos e como realizá-los com o Git. +Quando você terminar este capítulo, deve ser capaz de trabalhar de forma experiente com vários repositórios remotos, usar o Git por e-mail e fazer malabarismos habilmente com vários branches remotos e patches contribuídos. -*Chapter 6* covers the GitHub hosting service and tooling in depth. -We cover signing up for and managing an account, creating and using Git repositories, common workflows to contribute to projects and to accept contributions to yours, GitHub's programmatic interface and lots of little tips to make your life easier in general. +O *Capítulo 6* cobre o serviço de hospedagem GitHub e suas ferramentas em profundidade. +Abordamos como se inscrever e gerenciar uma conta, criar e usar repositórios Git, fluxos de trabalho comuns para contribuir em projetos e aceitar contribuições no seu, a interface programática do GitHub e muitas pequenas dicas para tornar sua vida mais fácil em geral. -*Chapter 7* is about advanced Git commands. -Here you will learn about topics like mastering the scary 'reset' command, using binary search to identify bugs, editing history, revision selection in detail, and a lot more. -This chapter will round out your knowledge of Git so that you are truly a master. +O *Capítulo 7* é sobre comandos avançados do Git. +Aqui você aprenderá sobre tópicos como dominar o assustador comando 'reset', usar a busca binária para identificar bugs, editar o histórico, seleção de revisões em detalhes e muito mais. +Este capítulo completará seu conhecimento sobre o Git para que você seja verdadeiramente um mestre. -*Chapter 8* is about configuring your custom Git environment. -This includes setting up hook scripts to enforce or encourage customized policies and using environment configuration settings so you can work the way you want to. -We will also cover building your own set of scripts to enforce a custom committing policy. +O *Capítulo 8* é sobre a configuração do seu ambiente Git personalizado. +Isso inclui configurar scripts de gancho (hooks) para impor ou encorajar políticas personalizadas e usar configurações de ambiente para que você possa trabalhar da maneira que desejar. +Também abordaremos a criação do seu próprio conjunto de scripts para impor uma política de commit personalizada. -*Chapter 9* deals with Git and other VCSs. -This includes using Git in a Subversion (SVN) world and converting projects from other VCSs to Git. -A lot of organizations still use SVN and are not about to change, but by this point you'll have learned the incredible power of Git -- and this chapter shows you how to cope if you still have to use a SVN server. -We also cover how to import projects from several different systems in case you do convince everyone to make the plunge. +O *Capítulo 9* trata do Git e de outros VCSs. +Isso inclui o uso do Git em um mundo Subversion (SVN) e a conversão de projetos de outros VCSs para o Git. +Muitas organizações ainda usam o SVN e não estão prestes a mudar, mas a essa altura você já terá aprendido o incrível poder do Git -- e este capítulo mostra como lidar se você ainda precisar usar um servidor SVN. +Também cobrimos como importar projetos de vários sistemas diferentes, caso você consiga convencer todos a darem o mergulho. -*Chapter 10* delves into the murky yet beautiful depths of Git internals. -Now that you know all about Git and can wield it with power and grace, you can move on to discuss how Git stores its objects, what the object model is, details of packfiles, server protocols, and more. -Throughout the book, we will refer to sections of this chapter in case you feel like diving deep at that point; but if you are like us and want to dive into the technical details, you may want to read Chapter 10 first. -We leave that up to you. +O *Capítulo 10* mergulha nas profundezas sombrias, porém belas, dos componentes internos do Git. +Agora que você sabe tudo sobre o Git e pode manejá-lo com poder e graça, você pode seguir em frente para discutir como o Git armazena seus objetos, qual é o modelo de objeto, detalhes sobre packfiles, protocolos de servidor e mais. +Ao longo do livro, nos referiremos a seções deste capítulo caso você sinta vontade de mergulhar fundo naquele momento; mas se você é como nós e quer mergulhar nos detalhes técnicos, pode querer ler o Capítulo 10 primeiro. +Deixamos isso a seu critério. -In *Appendix A*, we look at a number of examples of using Git in various specific environments. -We cover a number of different GUIs and IDE programming environments that you may want to use Git in and what is available for you. -If you're interested in an overview of using Git in your shell, your IDE, or your text editor, take a look here. +No *Apêndice A*, olhamos para uma série de exemplos de uso do Git em vários ambientes específicos. +Cobrimos uma série de diferentes GUIs e ambientes de programação de IDE nos quais você pode querer usar o Git e o que está disponível para você. +Se você estiver interessado em uma visão geral do uso do Git em seu shell, seu IDE ou seu editor de texto, dê uma olhada aqui. -In *Appendix B*, we explore scripting and extending Git through tools like libgit2 and JGit. -If you're interested in writing complex and fast custom tools and need low-level Git access, this is where you can see what that landscape looks like. +No *Apêndice B*, exploramos a criação de scripts e a extensão do Git por meio de ferramentas como libgit2 e JGit. +Se você estiver interessado em escrever ferramentas personalizadas complexas e rápidas e precisar de acesso de baixo nível ao Git, é aqui que você pode ver como é essa paisagem. -Finally, in *Appendix C*, we go through all the major Git commands one at a time and review where in the book we covered them and what we did with them. -If you want to know where in the book we used any specific Git command you can look that up here. +Finalmente, no *Apêndice C*, examinamos todos os principais comandos do Git, um de cada vez, e revisamos onde no livro os abordamos e o que fizemos com eles. +Se você quiser saber onde no livro usamos algum comando Git específico, pode procurar aqui. -Let's get started. +Vamos começar. diff --git a/book/preface_ben.asc b/book/preface_ben.asc index bd76e045..d761023d 100644 --- a/book/preface_ben.asc +++ b/book/preface_ben.asc @@ -1,12 +1,12 @@ [preface] -== Preface by Ben Straub +== Prefácio por Ben Straub -The first edition of this book is what got me hooked on Git. -This was my introduction to a style of making software that felt more natural than anything I had seen before. -I had been a developer for several years by then, but this was the right turn that sent me down a much more interesting path than the one I was on. +A primeira edição deste livro foi o que me deixou viciado no Git. +Esta foi minha introdução a um estilo de fazer software que parecia mais natural do que qualquer coisa que eu já tinha visto antes. +Eu já era desenvolvedor há vários anos na época, mas esta foi a curva certa que me enviou por um caminho muito mais interessante do que o em que eu estava. -Now, years later, I'm a contributor to a major Git implementation, I've worked for the largest Git hosting company, and I've traveled the world teaching people about Git. -When Scott asked if I'd be interested in working on the second edition, I didn't even have to think. +Agora, anos depois, sou um contribuidor de uma grande implementação do Git, trabalhei para a maior empresa de hospedagem Git e viajei o mundo ensinando as pessoas sobre o Git. +Quando Scott perguntou se eu estaria interessado em trabalhar na segunda edição, eu nem precisei pensar. -It's been a great pleasure and privilege to work on this book. -I hope it helps you as much as it did me. +Foi um grande prazer e privilégio trabalhar neste livro. +Espero que o ajude tanto quanto me ajudou. diff --git a/book/preface_schacon.asc b/book/preface_schacon.asc index bf31c08c..ffbb2678 100644 --- a/book/preface_schacon.asc +++ b/book/preface_schacon.asc @@ -1,35 +1,35 @@ [preface] -== Preface by Scott Chacon +== Prefácio por Scott Chacon -Welcome to the second edition of Pro Git. -The first edition was published over four years ago now. -Since then a lot has changed and yet many important things have not. -While most of the core commands and concepts are still valid today as the Git core team is pretty fantastic at keeping things backward compatible, there have been some significant additions and changes in the community surrounding Git. -The second edition of this book is meant to address those changes and update the book so it can be more helpful to the new user. +Bem-vindo à segunda edição do Pro Git. +A primeira edição foi publicada há mais de quatro anos. +Desde então, muita coisa mudou e, no entanto, muitas coisas importantes não mudaram. +Embora a maioria dos comandos e conceitos centrais ainda sejam válidos hoje, já que a equipe principal do Git é fantástica em manter a compatibilidade com versões anteriores, houve algumas adições e mudanças significativas na comunidade ao redor do Git. +A segunda edição deste livro tem como objetivo abordar essas mudanças e atualizar o livro para que possa ser mais útil ao novo usuário. -When I wrote the first edition, Git was still a relatively difficult to use and barely adopted tool for the harder core hacker. -It was starting to gain steam in certain communities, but had not reached anywhere near the ubiquity it has today. -Since then, nearly every open source community has adopted it. -Git has made incredible progress on Windows, in the explosion of graphical user interfaces to it for all platforms, in IDE support and in business use. -The Pro Git of four years ago knows about none of that. -One of the main aims of this new edition is to touch on all of those new frontiers in the Git community. +Quando escrevi a primeira edição, o Git ainda era uma ferramenta relativamente difícil de usar e pouco adotada, voltada para hackers mais experientes. +Estava começando a ganhar força em certas comunidades, mas não havia alcançado nem de perto a ubiquidade que tem hoje. +Desde então, quase todas as comunidades de código aberto o adotaram. +O Git fez um progresso incrível no Windows, na explosão de interfaces gráficas de usuário para ele em todas as plataformas, no suporte de IDEs e no uso corporativo. +O Pro Git de quatro anos atrás não sabe de nada disso. +Um dos principais objetivos desta nova edição é abordar todas essas novas fronteiras na comunidade Git. -The Open Source community using Git has also exploded. -When I originally sat down to write the book nearly five years ago (it took me a while to get the first version out), I had just started working at a very little known company developing a Git hosting website called GitHub. -At the time of publishing there were maybe a few thousand people using the site and just four of us working on it. -As I write this introduction, GitHub is announcing our 10 millionth hosted project, with nearly 5 million registered developer accounts and over 230 employees. -Love it or hate it, GitHub has heavily changed large swaths of the Open Source community in a way that was barely conceivable when I sat down to write the first edition. +A comunidade de código aberto usando Git também explodiu. +Quando me sentei originalmente para escrever o livro, há quase cinco anos (levei um tempo para lançar a primeira versão), eu tinha acabado de começar a trabalhar em uma empresa muito pouco conhecida que desenvolvia um site de hospedagem Git chamado GitHub. +Na época da publicação, talvez houvesse alguns milhares de pessoas usando o site e apenas quatro de nós trabalhando nele. +Enquanto escrevo esta introdução, o GitHub está anunciando nosso décimo milionésimo projeto hospedado, com quase 5 milhões de contas de desenvolvedores registradas e mais de 230 funcionários. +Ame ou odeie, o GitHub mudou fortemente grandes áreas da comunidade de código aberto de uma maneira que mal era concebível quando me sentei para escrever a primeira edição. -I wrote a small section in the original version of Pro Git about GitHub as an example of hosted Git which I was never very comfortable with. -I didn't much like that I was writing what I felt was essentially a community resource and also talking about my company in it. -While I still don't love that conflict of interests, the importance of GitHub in the Git community is unavoidable. -Instead of an example of Git hosting, I have decided to turn that part of the book into more deeply describing what GitHub is and how to effectively use it. -If you are going to learn how to use Git then knowing how to use GitHub will help you take part in a huge community, which is valuable no matter which Git host you decide to use for your own code. +Escrevi uma pequena seção na versão original do Pro Git sobre o GitHub como um exemplo de Git hospedado com o qual nunca me senti muito confortável. +Eu não gostava muito do fato de estar escrevendo o que sentia ser essencialmente um recurso da comunidade e também falando sobre minha empresa nele. +Embora eu ainda não ame esse conflito de interesses, a importância do GitHub na comunidade Git é inevitável. +Em vez de um exemplo de hospedagem Git, decidi transformar essa parte do livro em uma descrição mais profunda do que é o GitHub e de como usá-lo efetivamente. +Se você vai aprender como usar o Git, saber como usar o GitHub o ajudará a participar de uma enorme comunidade, o que é valioso não importa qual host Git você decida usar para seu próprio código. -The other large change in the time since the last publishing has been the development and rise of the HTTP protocol for Git network transactions. -Most of the examples in the book have been changed to HTTP from SSH because it's so much simpler. +A outra grande mudança no tempo desde a última publicação foi o desenvolvimento e a ascensão do protocolo HTTP para transações de rede do Git. +A maioria dos exemplos no livro foi mudada para HTTP em vez de SSH porque é muito mais simples. -It's been amazing to watch Git grow over the past few years from a relatively obscure version control system to basically dominating commercial and open source version control. -I'm happy that Pro Git has done so well and has also been able to be one of the few technical books on the market that is both quite successful and fully open source. +Tem sido incrível assistir o Git crescer nos últimos anos, de um sistema de controle de versão relativamente obscuro para basicamente dominar o controle de versão comercial e de código aberto. +Estou feliz que o Pro Git tenha se saído tão bem e também tenha sido capaz de ser um dos poucos livros técnicos no mercado que é bastante bem-sucedido e totalmente de código aberto. -I hope you enjoy this updated edition of Pro Git. +Espero que você aproveite esta edição atualizada do Pro Git. diff --git a/index.asc b/index.asc index 9618359a..19e19594 100644 --- a/index.asc +++ b/index.asc @@ -1,3 +1,3 @@ [#index] [index] -== Index +== Índice From f92bd902a682fe80cd84043359927cf6283d0a1f Mon Sep 17 00:00:00 2001 From: "Sergio Cabral (AI Agent)" Date: Thu, 20 Aug 2026 13:51:57 -0300 Subject: [PATCH 03/16] =?UTF-8?q?Traduz:=20Cap=C3=ADtulo=201=20=E2=80=94?= =?UTF-8?q?=20Primeiros=20Passos?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../sections/about-version-control.asc | 82 +++++----- .../01-introduction/sections/command-line.asc | 18 +-- .../sections/first-time-setup.asc | 98 ++++++------ book/01-introduction/sections/help.asc | 14 +- book/01-introduction/sections/history.asc | 30 ++-- book/01-introduction/sections/installing.asc | 88 +++++------ book/01-introduction/sections/what-is-git.asc | 148 +++++++++--------- ch01-getting-started.asc | 16 +- 8 files changed, 247 insertions(+), 247 deletions(-) diff --git a/book/01-introduction/sections/about-version-control.asc b/book/01-introduction/sections/about-version-control.asc index 182fcedc..780093c9 100644 --- a/book/01-introduction/sections/about-version-control.asc +++ b/book/01-introduction/sections/about-version-control.asc @@ -1,61 +1,61 @@ -=== About Version Control +=== Sobre Controle de Versão (((version control))) -What is "`version control`", and why should you care? -Version control is a system that records changes to a file or set of files over time so that you can recall specific versions later. -For the examples in this book, you will use software source code as the files being version controlled, though in reality you can do this with nearly any type of file on a computer. +O que é "`controle de versão`", e por que você deveria se importar? +O controle de versão é um sistema que registra as mudanças em um arquivo ou conjunto de arquivos ao longo do tempo, para que você possa recuperar versões específicas mais tarde. +Para os exemplos neste livro, você usará o código-fonte de software como os arquivos sendo controlados, embora na realidade você possa fazer isso com quase qualquer tipo de arquivo em um computador. -If you are a graphic or web designer and want to keep every version of an image or layout (which you would most certainly want to), a Version Control System (VCS) is a very wise thing to use. -It allows you to revert selected files back to a previous state, revert the entire project back to a previous state, compare changes over time, see who last modified something that might be causing a problem, who introduced an issue and when, and more. -Using a VCS also generally means that if you screw things up or lose files, you can easily recover. -In addition, you get all this for very little overhead. +Se você é um designer gráfico ou web e deseja manter cada versão de uma imagem ou layout (o que você certamente iria querer), usar um Sistema de Controle de Versão (VCS) é uma decisão muito sábia. +Ele permite que você reverta arquivos selecionados para um estado anterior, reverta o projeto inteiro para um estado anterior, compare as alterações ao longo do tempo, veja quem modificou por último algo que pode estar causando um problema, quem introduziu um problema e quando, e mais. +Usar um VCS também geralmente significa que se você estragar as coisas ou perder arquivos, pode se recuperar facilmente. +Além disso, você obtém tudo isso com muito pouco esforço adicional. -==== Local Version Control Systems +==== Sistemas de Controle de Versão Locais (((version control,local))) -Many people's version-control method of choice is to copy files into another directory (perhaps a time-stamped directory, if they're clever). -This approach is very common because it is so simple, but it is also incredibly error prone. -It is easy to forget which directory you're in and accidentally write to the wrong file or copy over files you don't mean to. +O método de controle de versão preferido de muitas pessoas é copiar os arquivos para outro diretório (talvez um diretório com carimbo de data/hora, se elas forem espertas). +Essa abordagem é muito comum porque é muito simples, mas também é incrivelmente sujeita a erros. +É fácil esquecer em qual diretório você está e acidentalmente escrever no arquivo errado ou sobrescrever arquivos que você não pretendia. -To deal with this issue, programmers long ago developed local VCSs that had a simple database that kept all the changes to files under revision control. +Para lidar com esse problema, os programadores desenvolveram, há muito tempo, VCSs locais que tinham um banco de dados simples que mantinha todas as alterações nos arquivos sob controle de revisão. -.Local version control diagram -image::images/local.png[Local version control diagram] +.Diagrama de controle de versão local +image::images/local.png[Diagrama de controle de versão local] -One of the most popular VCS tools was a system called RCS, which is still distributed with many computers today. -https://www.gnu.org/software/rcs/[RCS^] works by keeping patch sets (that is, the differences between files) in a special format on disk; it can then re-create what any file looked like at any point in time by adding up all the patches. +Uma das ferramentas VCS mais populares foi um sistema chamado RCS, que ainda é distribuído com muitos computadores hoje. +O https://www.gnu.org/software/rcs/[RCS^] funciona mantendo conjuntos de patches (isto é, as diferenças entre arquivos) em um formato especial no disco; ele pode então recriar a aparência de qualquer arquivo em qualquer ponto no tempo, somando todos os patches. -==== Centralized Version Control Systems +==== Sistemas de Controle de Versão Centralizados (((version control,centralized))) -The next major issue that people encounter is that they need to collaborate with developers on other systems. -To deal with this problem, Centralized Version Control Systems (CVCSs) were developed. -These systems (such as CVS, Subversion, and Perforce) have a single server that contains all the versioned files, and a number of clients that check out files from that central place.(((CVS)))(((Subversion)))(((Perforce))) -For many years, this has been the standard for version control. +O próximo grande problema que as pessoas encontram é que precisam colaborar com desenvolvedores em outros sistemas. +Para lidar com esse problema, os Sistemas de Controle de Versão Centralizados (CVCSs) foram desenvolvidos. +Esses sistemas (como CVS, Subversion e Perforce) possuem um único servidor que contém todos os arquivos versionados, e vários clientes que fazem o checkout dos arquivos desse local central.(((CVS)))(((Subversion)))(((Perforce))) +Por muitos anos, este tem sido o padrão para controle de versão. -.Centralized version control diagram -image::images/centralized.png[Centralized version control diagram] +.Diagrama de controle de versão centralizado +image::images/centralized.png[Diagrama de controle de versão centralizado] -This setup offers many advantages, especially over local VCSs. -For example, everyone knows to a certain degree what everyone else on the project is doing. -Administrators have fine-grained control over who can do what, and it's far easier to administer a CVCS than it is to deal with local databases on every client. +Essa configuração oferece muitas vantagens, especialmente sobre os VCSs locais. +Por exemplo, todo mundo sabe, até certo ponto, o que todos os outros no projeto estão fazendo. +Os administradores têm um controle refinado sobre quem pode fazer o quê, e é muito mais fácil administrar um CVCS do que lidar com bancos de dados locais em cada cliente. -However, this setup also has some serious downsides. -The most obvious is the single point of failure that the centralized server represents. -If that server goes down for an hour, then during that hour nobody can collaborate at all or save versioned changes to anything they're working on. -If the hard disk the central database is on becomes corrupted, and proper backups haven't been kept, you lose absolutely everything -- the entire history of the project except whatever single snapshots people happen to have on their local machines. -Local VCSs suffer from this same problem -- whenever you have the entire history of the project in a single place, you risk losing everything. +No entanto, essa configuração também tem algumas desvantagens sérias. +A mais óbvia é o ponto único de falha que o servidor centralizado representa. +Se esse servidor ficar inativo por uma hora, durante essa hora ninguém poderá colaborar de forma alguma ou salvar alterações versionadas em nada no qual estejam trabalhando. +Se o disco rígido onde o banco de dados central está for corrompido e não tiverem sido mantidos backups adequados, você perde absolutamente tudo -- o histórico inteiro do projeto, exceto quaisquer snapshots únicos que as pessoas tenham em suas máquinas locais. +Os VCSs locais sofrem do mesmo problema -- sempre que você tem o histórico inteiro do projeto em um único lugar, corre o risco de perder tudo. -==== Distributed Version Control Systems +==== Sistemas de Controle de Versão Distribuídos (((version control,distributed))) -This is where Distributed Version Control Systems (DVCSs) step in. -In a DVCS (such as Git, Mercurial or Darcs), clients don't just check out the latest snapshot of the files; rather, they fully mirror the repository, including its full history. -Thus, if any server dies, and these systems were collaborating via that server, any of the client repositories can be copied back up to the server to restore it. -Every clone is really a full backup of all the data. +É aqui que os Sistemas de Controle de Versão Distribuídos (DVCSs) entram em cena. +Em um DVCS (como Git, Mercurial ou Darcs), os clientes não fazem apenas o checkout do snapshot mais recente dos arquivos; em vez disso, eles espelham totalmente o repositório, incluindo todo o seu histórico. +Assim, se qualquer servidor morrer, e esses sistemas estivessem colaborando através desse servidor, qualquer um dos repositórios dos clientes pode ser copiado de volta para o servidor para restaurá-lo. +Cada clone é realmente um backup completo de todos os dados. -.Distributed version control diagram -image::images/distributed.png[Distributed version control diagram] +.Diagrama de controle de versão distribuído +image::images/distributed.png[Diagrama de controle de versão distribuído] -Furthermore, many of these systems deal pretty well with having several remote repositories they can work with, so you can collaborate with different groups of people in different ways simultaneously within the same project. -This allows you to set up several types of workflows that aren't possible in centralized systems, such as hierarchical models. +Além disso, muitos desses sistemas lidam muito bem com a existência de vários repositórios remotos com os quais podem trabalhar, de modo que você pode colaborar com diferentes grupos de pessoas de diferentes maneiras, simultaneamente, dentro do mesmo projeto. +Isso permite que você configure vários tipos de fluxos de trabalho que não são possíveis em sistemas centralizados, como modelos hierárquicos. diff --git a/book/01-introduction/sections/command-line.asc b/book/01-introduction/sections/command-line.asc index e7fd185b..232c3b28 100644 --- a/book/01-introduction/sections/command-line.asc +++ b/book/01-introduction/sections/command-line.asc @@ -1,11 +1,11 @@ -=== The Command Line +=== A Linha de Comando -There are a lot of different ways to use Git. -There are the original command-line tools, and there are many graphical user interfaces of varying capabilities. -For this book, we will be using Git on the command line. -For one, the command line is the only place you can run _all_ Git commands -- most of the GUIs implement only a partial subset of Git functionality for simplicity. -If you know how to run the command-line version, you can probably also figure out how to run the GUI version, while the opposite is not necessarily true. -Also, while your choice of graphical client is a matter of personal taste, _all_ users will have the command-line tools installed and available. +Existem muitas maneiras diferentes de usar o Git. +Existem as ferramentas de linha de comando originais, e existem muitas interfaces gráficas de usuário com capacidades variadas. +Para este livro, usaremos o Git na linha de comando. +Por um lado, a linha de comando é o único lugar onde você pode executar _todos_ os comandos do Git -- a maioria das GUIs implementa apenas um subconjunto parcial das funcionalidades do Git por simplicidade. +Se você sabe como executar a versão de linha de comando, provavelmente também conseguirá descobrir como executar a versão da GUI, enquanto o oposto não é necessariamente verdadeiro. +Além disso, enquanto a escolha do cliente gráfico é uma questão de gosto pessoal, _todos_ os usuários terão as ferramentas de linha de comando instaladas e disponíveis. -So we will expect you to know how to open Terminal in macOS or Command Prompt or PowerShell in Windows. -If you don't know what we're talking about here, you may need to stop and research that quickly so that you can follow the rest of the examples and descriptions in this book. +Portanto, esperamos que você saiba como abrir o Terminal no macOS ou o Prompt de Comando ou PowerShell no Windows. +Se você não sabe do que estamos falando aqui, pode ser necessário parar e pesquisar isso rapidamente para que você possa acompanhar o restante dos exemplos e descrições neste livro. diff --git a/book/01-introduction/sections/first-time-setup.asc b/book/01-introduction/sections/first-time-setup.asc index 10b7049c..b1f36411 100644 --- a/book/01-introduction/sections/first-time-setup.asc +++ b/book/01-introduction/sections/first-time-setup.asc @@ -1,40 +1,40 @@ [[_first_time]] -=== First-Time Git Setup +=== Configuração inicial do Git -Now that you have Git on your system, you'll want to do a few things to customize your Git environment. -You should have to do these things only once on any given computer; they'll stick around between upgrades. -You can also change them at any time by running through the commands again. +Agora que você tem o Git em seu sistema, você vai querer fazer algumas coisas para personalizar o seu ambiente Git. +Você deve ter que fazer essas coisas apenas uma vez em qualquer computador; elas permanecerão entre as atualizações. +Você também pode alterá-las a qualquer momento executando os comandos novamente. -Git comes with a tool called `git config` that lets you get and set configuration variables that control all aspects of how Git looks and operates.(((git commands, config))) -These variables can be stored in three different places: +O Git vem com uma ferramenta chamada `git config` que permite obter e definir variáveis de configuração que controlam todos os aspectos de como o Git se parece e opera.(((git commands, config))) +Essas variáveis podem ser armazenadas em três locais diferentes: -1. `[path]/etc/gitconfig` file: Contains values applied to every user on the system and all their repositories. - If you pass the option `--system` to `git config`, it reads and writes from this file specifically. - Because this is a system configuration file, you would need administrative or superuser privilege to make changes to it. -2. `~/.gitconfig` or `~/.config/git/config` file: Values specific personally to you, the user. - You can make Git read and write to this file specifically by passing the `--global` option, and this affects _all_ of the repositories you work with on your system. -3. `config` file in the Git directory (that is, `.git/config`) of whatever repository you're currently using: Specific to that single repository. - You can force Git to read from and write to this file with the `--local` option, but that is in fact the default. - Unsurprisingly, you need to be located somewhere in a Git repository for this option to work properly. +1. Arquivo `[caminho]/etc/gitconfig`: Contém valores aplicados a todos os usuários no sistema e em todos os seus repositórios. + Se você passar a opção `--system` para `git config`, ele lê e escreve especificamente a partir deste arquivo. + Como este é um arquivo de configuração do sistema, você precisaria de privilégios administrativos ou de superusuário para fazer alterações nele. +2. Arquivo `~/.gitconfig` ou `~/.config/git/config`: Valores específicos pessoalmente para você, o usuário. + Você pode fazer com que o Git leia e grave especificamente neste arquivo passando a opção `--global`, e isso afeta _todos_ os repositórios com os quais você trabalha no seu sistema. +3. Arquivo `config` no diretório Git (ou seja, `.git/config`) de qualquer repositório que você esteja usando no momento: Específico para aquele único repositório. + Você pode forçar o Git a ler e escrever neste arquivo com a opção `--local`, mas isso é de fato o padrão. + Sem surpresa, você precisa estar localizado em algum lugar de um repositório Git para que esta opção funcione corretamente. -Each level overrides values in the previous level, so values in `.git/config` trump those in `[path]/etc/gitconfig`. +Cada nível substitui os valores no nível anterior, portanto, os valores em `.git/config` superam os de `[caminho]/etc/gitconfig`. -On Windows systems, Git looks for the `.gitconfig` file in the `$HOME` directory (`C:\Users\$USER` for most people). -It also still looks for `[path]/etc/gitconfig`, although it's relative to the MSys root, which is wherever you decide to install Git on your Windows system when you run the installer. -If you are using version 2.x or later of Git for Windows, there is also a system-level config file at `C:\Documents and Settings\All Users\Application Data\Git\config` on Windows XP, and in `C:\ProgramData\Git\config` on Windows Vista and newer. -This config file can only be changed by `git config -f ` as an admin. +Em sistemas Windows, o Git procura o arquivo `.gitconfig` no diretório `$HOME` (`C:\Users\$USER` para a maioria das pessoas). +Ele também ainda procura por `[caminho]/etc/gitconfig`, embora seja relativo à raiz do MSys, que é onde quer que você decida instalar o Git em seu sistema Windows ao executar o instalador. +Se você estiver usando a versão 2.x ou mais recente do Git para Windows, também existe um arquivo de configuração no nível do sistema em `C:\Documents and Settings\All Users\Application Data\Git\config` no Windows XP, e em `C:\ProgramData\Git\config` no Windows Vista e mais recentes. +Este arquivo de configuração só pode ser alterado por `git config -f ` como administrador. -You can view all of your settings and where they are coming from using: +Você pode visualizar todas as suas configurações e de onde elas vêm usando: [source,console] ---- $ git config --list --show-origin ---- -==== Your Identity +==== Sua Identidade -The first thing you should do when you install Git is to set your user name and email address. -This is important because every Git commit uses this information, and it's immutably baked into the commits you start creating: +A primeira coisa que você deve fazer ao instalar o Git é definir o seu nome de usuário e endereço de e-mail. +Isso é importante porque todo commit do Git usa essas informações e elas estão incorporadas de forma imutável nos commits que você começa a criar: [source,console] ---- @@ -42,29 +42,29 @@ $ git config --global user.name "John Doe" $ git config --global user.email johndoe@example.com ---- -Again, you need to do this only once if you pass the `--global` option, because then Git will always use that information for your user on that system. -If you want to override this with a different name or email address for specific projects, you can run the command without the `--global` option when you're in that project. +Novamente, você precisa fazer isso apenas uma vez se passar a opção `--global`, porque então o Git sempre usará essas informações para o seu usuário nesse sistema. +Se você quiser substituir isso com um nome ou endereço de e-mail diferente para projetos específicos, poderá executar o comando sem a opção `--global` quando estiver nesse projeto. -Many of the GUI tools will help you do this when you first run them. +Muitas das ferramentas de GUI ajudarão você a fazer isso quando as executar pela primeira vez. [[_editor]] -==== Your Editor +==== Seu Editor -Now that your identity is set up, you can configure the default text editor that will be used when Git needs you to type in a message. -If not configured, Git uses your system's default editor. +Agora que sua identidade está configurada, você pode configurar o editor de texto padrão que será usado quando o Git precisar que você digite uma mensagem. +Se não estiver configurado, o Git usará o editor padrão do seu sistema. -If you want to use a different text editor, such as Emacs, you can do the following: +Se você quiser usar um editor de texto diferente, como o Emacs, pode fazer o seguinte: [source,console] ---- $ git config --global core.editor emacs ---- -On a Windows system, if you want to use a different text editor, you must specify the full path to its executable file. -This can be different depending on how your editor is packaged. +Em um sistema Windows, se você quiser usar um editor de texto diferente, deverá especificar o caminho completo para seu arquivo executável. +Isso pode ser diferente dependendo de como o seu editor está empacotado. -In the case of Notepad++, a popular programming editor, you are likely to want to use the 32-bit version, since at the time of writing the 64-bit version doesn't support all plug-ins. -If you are on a 32-bit Windows system, or you have a 64-bit editor on a 64-bit system, you'll type something like this: +No caso do Notepad++, um editor de programação popular, é provável que você queira usar a versão de 32 bits, já que, no momento da escrita, a versão de 64 bits não suporta todos os plug-ins. +Se você estiver em um sistema Windows de 32 bits, ou se tiver um editor de 64 bits em um sistema de 64 bits, digitará algo assim: [source,console] ---- @@ -73,32 +73,32 @@ $ git config --global core.editor "'C:/Program Files/Notepad++/notepad++.exe' -m [NOTE] ==== -Vim, Emacs and Notepad++ are popular text editors often used by developers on Unix-based systems like Linux and macOS or a Windows system. -If you are using another editor, or a 32-bit version, please find specific instructions for how to set up your favorite editor with Git in <>. +O Vim, Emacs e Notepad++ são editores de texto populares frequentemente usados por desenvolvedores em sistemas baseados em Unix como Linux e macOS ou um sistema Windows. +Se você estiver usando outro editor, ou uma versão de 32 bits, encontre instruções específicas sobre como configurar o seu editor favorito com o Git em <>. ==== [WARNING] ==== -You may find, if you don't setup your editor like this, you get into a really confusing state when Git attempts to launch it. -An example on a Windows system may include a prematurely terminated Git operation during a Git initiated edit. +Você pode descobrir que, se não configurar seu editor dessa forma, ficará em um estado muito confuso quando o Git tentar iniciá-lo. +Um exemplo em um sistema Windows pode incluir uma operação do Git encerrada prematuramente durante uma edição iniciada pelo Git. ==== [[_new_default_branch]] -==== Your default branch name +==== O nome do seu branch padrão -By default Git will create a branch called _master_ when you create a new repository with `git init`. -From Git version 2.28 onwards, you can set a different name for the initial branch. +Por padrão, o Git criará um branch chamado _master_ quando você criar um novo repositório com `git init`. +A partir da versão 2.28 do Git, você pode definir um nome diferente para o branch inicial. -To set _main_ as the default branch name do: +Para definir _main_ como o nome do branch padrão, faça: [source,console] ---- $ git config --global init.defaultBranch main ---- -==== Checking Your Settings +==== Verificando suas configurações -If you want to check your configuration settings, you can use the `git config --list` command to list all the settings Git can find at that point: +Se você quiser verificar suas definições de configuração, pode usar o comando `git config --list` para listar todas as configurações que o Git pode encontrar naquele ponto: [source,console] ---- @@ -112,10 +112,10 @@ color.diff=auto ... ---- -You may see keys more than once, because Git reads the same key from different files (`[path]/etc/gitconfig` and `~/.gitconfig`, for example). -In this case, Git uses the last value for each unique key it sees. +Você pode ver as chaves mais de uma vez, porque o Git lê a mesma chave de arquivos diferentes (`[caminho]/etc/gitconfig` e `~/.gitconfig`, por exemplo). +Nesse caso, o Git usa o último valor para cada chave única que vê. -You can also check what Git thinks a specific key's value is by typing `git config `:(((git commands, config))) +Você também pode verificar o que o Git pensa ser o valor de uma chave específica digitando `git config `:(((git commands, config))) [source,console] ---- @@ -125,8 +125,8 @@ John Doe [NOTE] ==== -Since Git might read the same configuration variable value from more than one file, it's possible that you have an unexpected value for one of these values and you don't know why. -In cases like that, you can query Git as to the _origin_ for that value, and it will tell you which configuration file had the final say in setting that value: +Como o Git pode ler o valor da mesma variável de configuração de mais de um arquivo, é possível que você tenha um valor inesperado para um desses valores e não saiba o porquê. +Em casos assim, você pode consultar o Git quanto à _origem_ (_origin_) desse valor, e ele dirá qual arquivo de configuração teve a palavra final na definição desse valor: [source,console] ---- diff --git a/book/01-introduction/sections/help.asc b/book/01-introduction/sections/help.asc index 68d76a4c..96984499 100644 --- a/book/01-introduction/sections/help.asc +++ b/book/01-introduction/sections/help.asc @@ -1,7 +1,7 @@ [[_git_help]] -=== Getting Help +=== Obtendo Ajuda -If you ever need help while using Git, there are three equivalent ways to get the comprehensive manual page (manpage) help for any of the Git commands: +Se você precisar de ajuda ao usar o Git, existem três maneiras equivalentes de obter a ajuda abrangente da página de manual (manpage) para qualquer um dos comandos do Git: [source,console] ---- @@ -10,18 +10,18 @@ $ git --help $ man git- ---- -For example, you can get the manpage help for the `git config` command by running this:(((git commands, help))) +Por exemplo, você pode obter a ajuda da manpage para o comando `git config` executando isto:(((git commands, help))) [source,console] ---- $ git help config ---- -These commands are nice because you can access them anywhere, even offline. -If the manpages and this book aren't enough and you need in-person help, you can try the `#git`, `#github`, or `#gitlab` channels on the Libera Chat IRC server, which can be found at https://libera.chat/[^]. -These channels are regularly filled with hundreds of people who are all very knowledgeable about Git and are often willing to help.(((IRC))) +Esses comandos são ótimos porque você pode acessá-los de qualquer lugar, mesmo offline. +Se as manpages e este livro não forem suficientes e você precisar de ajuda em pessoa, pode tentar os canais `#git`, `#github` ou `#gitlab` no servidor IRC Libera Chat, que pode ser encontrado em https://libera.chat/[^]. +Esses canais costumam estar cheios de centenas de pessoas que têm muito conhecimento sobre o Git e geralmente estão dispostas a ajudar.(((IRC))) -In addition, if you don't need the full-blown manpage help, but just need a quick refresher on the available options for a Git command, you can ask for the more concise "`help`" output with the `-h` option, as in: +Além disso, se você não precisar da ajuda completa da manpage, mas apenas precisar de uma rápida lembrança sobre as opções disponíveis para um comando do Git, você pode solicitar a saída "`help`" mais concisa com a opção `-h`, como em: [source,console] ---- diff --git a/book/01-introduction/sections/history.asc b/book/01-introduction/sections/history.asc index 7ab05fd3..280593c9 100644 --- a/book/01-introduction/sections/history.asc +++ b/book/01-introduction/sections/history.asc @@ -1,20 +1,20 @@ -=== A Short History of Git +=== Uma Breve História do Git -As with many great things in life, Git began with a bit of creative destruction and fiery controversy. +Como muitas coisas grandes na vida, o Git começou com um pouco de destruição criativa e uma controvérsia acalorada. -The Linux kernel is an open source software project of fairly large scope.(((Linux))) -During the early years of the Linux kernel maintenance (1991–2002), changes to the software were passed around as patches and archived files. -In 2002, the Linux kernel project began using a proprietary DVCS called BitKeeper.(((BitKeeper))) +O kernel Linux é um projeto de software de código aberto de escopo bastante grande.(((Linux))) +Durante os primeiros anos de manutenção do kernel Linux (1991–2002), as alterações no software eram passadas como patches e arquivos compactados. +Em 2002, o projeto do kernel Linux começou a usar um DVCS proprietário chamado BitKeeper.(((BitKeeper))) -In 2005, the relationship between the community that developed the Linux kernel and the commercial company that developed BitKeeper broke down, and the tool's free-of-charge status was revoked. -This prompted the Linux development community (and in particular Linus Torvalds, the creator of Linux) to develop their own tool based on some of the lessons they learned while using BitKeeper.(((Linus Torvalds))) -Some of the goals of the new system were as follows: +Em 2005, o relacionamento entre a comunidade que desenvolveu o kernel Linux e a empresa comercial que desenvolveu o BitKeeper desmoronou, e o status gratuito da ferramenta foi revogado. +Isso levou a comunidade de desenvolvimento do Linux (e em particular Linus Torvalds, o criador do Linux) a desenvolver sua própria ferramenta baseada em algumas das lições que aprenderam ao usar o BitKeeper.(((Linus Torvalds))) +Alguns dos objetivos do novo sistema eram os seguintes: -* Speed -* Simple design -* Strong support for non-linear development (thousands of parallel branches) -* Fully distributed -* Able to handle large projects like the Linux kernel efficiently (speed and data size) +* Velocidade +* Design simples +* Forte suporte para desenvolvimento não linear (milhares de branches paralelos) +* Totalmente distribuído +* Capaz de lidar com grandes projetos como o kernel Linux eficientemente (velocidade e tamanho dos dados) -Since its birth in 2005, Git has evolved and matured to be easy to use and yet retain these initial qualities. -It's amazingly fast, it's very efficient with large projects, and it has an incredible branching system for non-linear development (see <>). +Desde o seu nascimento em 2005, o Git evoluiu e amadureceu para ser fácil de usar, e ainda assim reter essas qualidades iniciais. +Ele é incrivelmente rápido, é muito eficiente com grandes projetos e tem um incrível sistema de branching para desenvolvimento não linear (veja <>). diff --git a/book/01-introduction/sections/installing.asc b/book/01-introduction/sections/installing.asc index d4f6dcbd..bebc1722 100644 --- a/book/01-introduction/sections/installing.asc +++ b/book/01-introduction/sections/installing.asc @@ -1,73 +1,73 @@ -=== Installing Git +=== Instalando o Git -Before you start using Git, you have to make it available on your computer. -Even if it's already installed, it's probably a good idea to update to the latest version. -You can either install it as a package or via another installer, or download the source code and compile it yourself. +Antes de começar a usar o Git, você deve disponibilizá-lo no seu computador. +Mesmo que já esteja instalado, provavelmente é uma boa ideia atualizar para a versão mais recente. +Você pode instalá-lo como um pacote ou por meio de outro instalador, ou baixar o código-fonte e compilá-lo você mesmo. [NOTE] ==== -This book was written using Git version 2. -Since Git is quite excellent at preserving backwards compatibility, any recent version should work just fine. -Though most of the commands we use should work even in ancient versions of Git, some of them might not or might act slightly differently. +Este livro foi escrito usando o Git versão 2. +Como o Git é excelente em preservar a compatibilidade com versões anteriores, qualquer versão recente deve funcionar bem. +Embora a maioria dos comandos que usamos deva funcionar mesmo em versões antigas do Git, alguns deles podem não funcionar ou podem agir de maneira ligeiramente diferente. ==== -==== Installing on Linux +==== Instalando no Linux (((Linux, installing))) -If you want to install the basic Git tools on Linux via a binary installer, you can generally do so through the package management tool that comes with your distribution. -If you're on Fedora (or any closely-related RPM-based distribution, such as RHEL or CentOS), you can use `dnf`: +Se você deseja instalar as ferramentas básicas do Git no Linux por meio de um instalador binário, geralmente pode fazer isso através da ferramenta de gerenciamento de pacotes que vem com sua distribuição. +Se você estiver no Fedora (ou em qualquer distribuição baseada em RPM intimamente relacionada, como RHEL ou CentOS), pode usar o `dnf`: [source,console] ---- $ sudo dnf install git-all ---- -If you're on a Debian-based distribution, such as Ubuntu, try `apt`: +Se você estiver em uma distribuição baseada em Debian, como o Ubuntu, tente o `apt`: [source,console] ---- $ sudo apt install git-all ---- -For more options, there are instructions for installing on several different Unix distributions on the Git website, at https://git-scm.com/download/linux[^]. +Para mais opções, existem instruções para instalar em várias distribuições Unix diferentes no site do Git, em https://git-scm.com/download/linux[^]. -==== Installing on macOS +==== Instalando no macOS (((macOS, installing))) -There are several ways to install Git on macOS. -The easiest is probably to install the Xcode Command Line Tools.(((Xcode))) -On Mavericks (10.9) or above you can do this simply by trying to run `git` from the Terminal the very first time. +Existem várias maneiras de instalar o Git no macOS. +A mais fácil é provavelmente instalar as ferramentas de linha de comando do Xcode.(((Xcode))) +No Mavericks (10.9) ou superior, você pode fazer isso simplesmente tentando executar `git` a partir do Terminal na primeira vez. [source,console] ---- $ git --version ---- -If you don't have it installed already, it will prompt you to install it. +Se você ainda não o tiver instalado, será solicitado a instalá-lo. -If you want a more up to date version, you can also install it via a binary installer. -A macOS Git installer is maintained and available for download at the Git website, at https://git-scm.com/download/mac[^]. +Se você quiser uma versão mais atualizada, também pode instalá-la por meio de um instalador binário. +Um instalador do Git para macOS é mantido e está disponível para download no site do Git, em https://git-scm.com/download/mac[^]. -.Git macOS installer -image::images/git-osx-installer.png[Git macOS installer] +.Instalador do Git para macOS +image::images/git-osx-installer.png[Instalador do Git para macOS] -==== Installing on Windows +==== Instalando no Windows -There are also a few ways to install Git on Windows.(((Windows, installing))) -The most official build is available for download on the Git website. -Just go to https://git-scm.com/download/win[^] and the download will start automatically. -Note that this is a project called Git for Windows, which is separate from Git itself; for more information on it, go to https://gitforwindows.org[^]. +Também existem algumas maneiras de instalar o Git no Windows.(((Windows, installing))) +A compilação mais oficial está disponível para download no site do Git. +Basta ir em https://git-scm.com/download/win[^] e o download iniciará automaticamente. +Note que este é um projeto chamado Git para Windows, que é separado do próprio Git; para mais informações sobre ele, vá em https://gitforwindows.org[^]. -To get an automated installation you can use the https://community.chocolatey.org/packages/git[Git Chocolatey package^]. -Note that the Chocolatey package is community maintained. +Para obter uma instalação automatizada, você pode usar o https://community.chocolatey.org/packages/git[pacote Chocolatey do Git^]. +Note que o pacote Chocolatey é mantido pela comunidade. -==== Installing from Source +==== Instalando a partir do código-fonte -Some people may instead find it useful to install Git from source, because you'll get the most recent version. -The binary installers tend to be a bit behind, though as Git has matured in recent years, this has made less of a difference. +Algumas pessoas podem achar mais útil instalar o Git a partir do código-fonte, porque você obterá a versão mais recente. +Os instaladores binários tendem a ficar um pouco para trás, embora, à medida que o Git amadureceu nos últimos anos, isso tenha feito menos diferença. -If you do want to install Git from source, you need to have the following libraries that Git depends on: autotools, curl, zlib, openssl, expat, and libiconv. -For example, if you're on a system that has `dnf` (such as Fedora) or `apt-get` (such as a Debian-based system), you can use one of these commands to install the minimal dependencies for compiling and installing the Git binaries: +Se você quiser instalar o Git a partir do código-fonte, precisará ter as seguintes bibliotecas das quais o Git depende: autotools, curl, zlib, openssl, expat e libiconv. +Por exemplo, se você estiver em um sistema que tem o `dnf` (como o Fedora) ou `apt-get` (como um sistema baseado em Debian), pode usar um desses comandos para instalar as dependências mínimas para compilar e instalar os binários do Git: [source,console] ---- @@ -77,7 +77,7 @@ $ sudo apt-get install dh-autoreconf libcurl4-gnutls-dev libexpat1-dev \ gettext libz-dev libssl-dev ---- -In order to be able to add the documentation in various formats (doc, html, info), these additional dependencies are required: +Para ser capaz de adicionar a documentação em vários formatos (doc, html, info), estas dependências adicionais são necessárias: [source,console] ---- @@ -87,37 +87,37 @@ $ sudo apt-get install asciidoc xmlto docbook2x [NOTE] ==== -Users of RHEL and RHEL-derivatives like CentOS and Scientific Linux will have to https://docs.fedoraproject.org/en-US/epel/#how_can_i_use_these_extra_packages[enable the EPEL repository^] to download the `docbook2X` package. +Usuários do RHEL e de derivados do RHEL, como CentOS e Scientific Linux, terão que https://docs.fedoraproject.org/en-US/epel/#how_can_i_use_these_extra_packages[habilitar o repositório EPEL^] para baixar o pacote `docbook2X`. ==== -If you're using a Debian-based distribution (Debian/Ubuntu/Ubuntu-derivatives), you also need the `install-info` package: +Se você estiver usando uma distribuição baseada no Debian (Debian/Ubuntu/derivados do Ubuntu), também precisará do pacote `install-info`: [source,console] ---- $ sudo apt-get install install-info ---- -If you're using a RPM-based distribution (Fedora/RHEL/RHEL-derivatives), you also need the `getopt` package (which is already installed on a Debian-based distro): +Se você estiver usando uma distribuição baseada em RPM (Fedora/RHEL/derivados do RHEL), também precisará do pacote `getopt` (que já vem instalado em uma distribuição baseada em Debian): [source,console] ---- $ sudo dnf install getopt ---- -Additionally, if you're using Fedora/RHEL/RHEL-derivatives, you need to do this: +Adicionalmente, se você estiver usando Fedora/RHEL/derivados do RHEL, precisará fazer isso: [source,console] ---- $ sudo ln -s /usr/bin/db2x_docbook2texi /usr/bin/docbook2x-texi ---- -due to binary name differences. +devido a diferenças de nome de binário. -When you have all the necessary dependencies, you can go ahead and grab the latest tagged release tarball from several places. -You can get it via the kernel.org site, at https://www.kernel.org/pub/software/scm/git[^], or the mirror on the GitHub website, at https://github.com/git/git/tags[^]. -It's generally a little clearer what the latest version is on the GitHub page, but the kernel.org page also has release signatures if you want to verify your download. +Quando você tiver todas as dependências necessárias, pode ir em frente e pegar o tarball da versão mais recente marcada (tagged release) de vários lugares. +Você pode obtê-lo no site kernel.org, em https://www.kernel.org/pub/software/scm/git[^], ou no espelho do site no GitHub, em https://github.com/git/git/tags[^]. +Geralmente é um pouco mais claro qual é a versão mais recente na página do GitHub, mas a página kernel.org também tem assinaturas de lançamento se você quiser verificar seu download. -Then, compile and install: +Então, compile e instale: [source,console] ---- @@ -129,7 +129,7 @@ $ make all doc info $ sudo make install install-doc install-html install-info ---- -After this is done, you can also get Git via Git itself for updates: +Depois que isso for feito, você também pode obter o Git por meio do próprio Git para atualizações: [source,console] ---- diff --git a/book/01-introduction/sections/what-is-git.asc b/book/01-introduction/sections/what-is-git.asc index 466201b2..372427a6 100644 --- a/book/01-introduction/sections/what-is-git.asc +++ b/book/01-introduction/sections/what-is-git.asc @@ -1,109 +1,109 @@ [[what_is_git_section]] -=== What is Git? +=== O que é Git? -So, what is Git in a nutshell? -This is an important section to absorb, because if you understand what Git is and the fundamentals of how it works, then using Git effectively will probably be much easier for you. -As you learn Git, try to clear your mind of the things you may know about other VCSs, such as CVS, Subversion or Perforce -- doing so will help you avoid subtle confusion when using the tool. -Even though Git's user interface is fairly similar to these other VCSs, Git stores and thinks about information in a very different way, and understanding these differences will help you avoid becoming confused while using it.(((Subversion)))(((Perforce))) +Então, o que é o Git em poucas palavras? +Esta é uma seção importante para absorver, porque se você entender o que o Git é e os fundamentos de como ele funciona, então usar o Git de forma eficaz provavelmente será muito mais fácil para você. +À medida que você aprende o Git, tente limpar a mente das coisas que você talvez saiba sobre outros VCSs, como CVS, Subversion ou Perforce -- fazer isso o ajudará a evitar confusões sutis ao usar a ferramenta. +Mesmo que a interface de usuário do Git seja bastante semelhante a esses outros VCSs, o Git armazena e pensa sobre as informações de uma maneira muito diferente, e entender essas diferenças o ajudará a evitar ficar confuso ao usá-lo.(((Subversion)))(((Perforce))) -==== Snapshots, Not Differences +==== Snapshots, não diferenças -The major difference between Git and any other VCS (Subversion and friends included) is the way Git thinks about its data. -Conceptually, most other systems store information as a list of file-based changes. -These other systems (CVS, Subversion, Perforce, and so on) think of the information they store as a set of files and the changes made to each file over time (this is commonly described as _delta-based_ version control). +A principal diferença entre o Git e qualquer outro VCS (Subversion e amigos incluídos) é a maneira como o Git pensa sobre seus dados. +Conceitualmente, a maioria dos outros sistemas armazena informações como uma lista de alterações baseadas em arquivos. +Esses outros sistemas (CVS, Subversion, Perforce e assim por diante) pensam nas informações que armazenam como um conjunto de arquivos e as alterações feitas em cada arquivo ao longo do tempo (isso é comumente descrito como controle de versão _baseado em delta_). -.Storing data as changes to a base version of each file -image::images/deltas.png[Storing data as changes to a base version of each file] +.Armazenamento de dados como alterações em uma versão base de cada arquivo +image::images/deltas.png[Armazenamento de dados como alterações em uma versão base de cada arquivo] -Git doesn't think of or store its data this way. -Instead, Git thinks of its data more like a series of snapshots of a miniature filesystem. -With Git, every time you commit, or save the state of your project, Git basically takes a picture of what all your files look like at that moment and stores a reference to that snapshot. -To be efficient, if files have not changed, Git doesn't store the file again, just a link to the previous identical file it has already stored. -Git thinks about its data more like a *stream of snapshots*. +O Git não pensa ou armazena seus dados dessa maneira. +Em vez disso, o Git pensa em seus dados mais como uma série de snapshots de um sistema de arquivos em miniatura. +Com o Git, toda vez que você faz um commit, ou salva o estado do seu projeto, o Git basicamente tira uma foto de como todos os seus arquivos se parecem naquele momento e armazena uma referência para esse snapshot. +Para ser eficiente, se os arquivos não mudaram, o Git não armazena o arquivo novamente, apenas um link para o arquivo idêntico anterior que ele já armazenou. +O Git pensa em seus dados mais como um *fluxo de snapshots*. -.Storing data as snapshots of the project over time -image::images/snapshots.png[Git stores data as snapshots of the project over time] +.Armazenamento de dados como snapshots do projeto ao longo do tempo +image::images/snapshots.png[O Git armazena dados como snapshots do projeto ao longo do tempo] -This is an important distinction between Git and nearly all other VCSs. -It makes Git reconsider almost every aspect of version control that most other systems copied from the previous generation. -This makes Git more like a mini filesystem with some incredibly powerful tools built on top of it, rather than simply a VCS. -We'll explore some of the benefits you gain by thinking of your data this way when we cover Git branching in <>. +Esta é uma distinção importante entre o Git e quase todos os outros VCSs. +Isso faz com que o Git reconsidere quase todos os aspectos do controle de versão que a maioria dos outros sistemas copiou da geração anterior. +Isso torna o Git mais como um mini sistema de arquivos com algumas ferramentas incrivelmente poderosas construídas sobre ele, em vez de simplesmente um VCS. +Exploraremos alguns dos benefícios que você ganha ao pensar em seus dados dessa maneira quando abordarmos o branching do Git em <>. -==== Nearly Every Operation Is Local +==== Quase toda operação é local -Most operations in Git need only local files and resources to operate -- generally no information is needed from another computer on your network. -If you're used to a CVCS where most operations have that network latency overhead, this aspect of Git will make you think that the gods of speed have blessed Git with unworldly powers. -Because you have the entire history of the project right there on your local disk, most operations seem almost instantaneous. +A maioria das operações no Git precisa apenas de arquivos e recursos locais para operar -- geralmente nenhuma informação de outro computador na sua rede é necessária. +Se você está acostumado a um CVCS em que a maioria das operações tem aquele custo adicional de latência de rede, esse aspecto do Git fará você pensar que os deuses da velocidade abençoaram o Git com poderes de outro mundo. +Como você tem todo o histórico do projeto bem ali no seu disco local, a maioria das operações parece quase instantânea. -For example, to browse the history of the project, Git doesn't need to go out to the server to get the history and display it for you -- it simply reads it directly from your local database. -This means you see the project history almost instantly. -If you want to see the changes introduced between the current version of a file and the file a month ago, Git can look up the file a month ago and do a local difference calculation, instead of having to either ask a remote server to do it or pull an older version of the file from the remote server to do it locally. +Por exemplo, para navegar no histórico do projeto, o Git não precisa ir ao servidor para obter o histórico e exibi-lo para você -- ele simplesmente o lê direto do seu banco de dados local. +Isso significa que você vê o histórico do projeto quase instantaneamente. +Se você quiser ver as alterações introduzidas entre a versão atual de um arquivo e o arquivo há um mês, o Git pode consultar o arquivo de um mês atrás e fazer um cálculo de diferença local, em vez de ter que pedir a um servidor remoto para fazer isso ou extrair uma versão mais antiga do arquivo do servidor remoto para fazê-lo localmente. -This also means that there is very little you can't do if you're offline or off VPN. -If you get on an airplane or a train and want to do a little work, you can commit happily (to your _local_ copy, remember?) until you get to a network connection to upload. -If you go home and can't get your VPN client working properly, you can still work. -In many other systems, doing so is either impossible or painful. -In Perforce, for example, you can't do much when you aren't connected to the server; in Subversion and CVS, you can edit files, but you can't commit changes to your database (because your database is offline). -This may not seem like a huge deal, but you may be surprised what a big difference it can make. +Isso também significa que há muito pouco que você não pode fazer se estiver offline ou fora da VPN. +Se você entrar em um avião ou trem e quiser trabalhar um pouco, pode fazer commits alegremente (na sua cópia _local_, lembra?) até chegar a uma conexão de rede para fazer o upload. +Se você for para casa e não conseguir fazer o seu cliente VPN funcionar corretamente, você ainda pode trabalhar. +Em muitos outros sistemas, fazer isso é impossível ou doloroso. +No Perforce, por exemplo, você não pode fazer muita coisa quando não está conectado ao servidor; no Subversion e CVS, você pode editar arquivos, mas não pode fazer commit das alterações no seu banco de dados (porque o seu banco de dados está offline). +Isso pode não parecer grande coisa, mas você pode se surpreender com a grande diferença que isso pode fazer. -==== Git Has Integrity +==== O Git tem integridade -Everything in Git is checksummed before it is stored and is then referred to by that checksum. -This means it's impossible to change the contents of any file or directory without Git knowing about it. -This functionality is built into Git at the lowest levels and is integral to its philosophy. -You can't lose information in transit or get file corruption without Git being able to detect it. +Tudo no Git é verificado por soma de verificação (checksummed) antes de ser armazenado e é então referido por essa soma de verificação. +Isso significa que é impossível alterar o conteúdo de qualquer arquivo ou diretório sem que o Git saiba disso. +Essa funcionalidade é incorporada ao Git nos níveis mais baixos e é essencial à sua filosofia. +Você não pode perder informações em trânsito ou sofrer corrupção de arquivos sem que o Git seja capaz de detectar isso. -The mechanism that Git uses for this checksumming is called a SHA-1 hash.(((SHA-1))) -This is a 40-character string composed of hexadecimal characters (0–9 and a–f) and calculated based on the contents of a file or directory structure in Git. -A SHA-1 hash looks something like this: +O mecanismo que o Git usa para essa soma de verificação é chamado de hash SHA-1.(((SHA-1))) +Esta é uma string de 40 caracteres composta por caracteres hexadecimais (0–9 e a–f) e calculada com base no conteúdo de um arquivo ou estrutura de diretórios no Git. +Um hash SHA-1 se parece com isto: [source] ---- 24b9da6552252987aa493b52f8696cd6d3b00373 ---- -You will see these hash values all over the place in Git because it uses them so much. -In fact, Git stores everything in its database not by file name but by the hash value of its contents. +Você verá esses valores de hash em todos os lugares no Git porque ele os usa muito. +Na verdade, o Git armazena tudo em seu banco de dados não pelo nome do arquivo, mas pelo valor de hash do seu conteúdo. -==== Git Generally Only Adds Data +==== O Git geralmente apenas adiciona dados -When you do actions in Git, nearly all of them only _add_ data to the Git database. -It is hard to get the system to do anything that is not undoable or to make it erase data in any way. -As with any VCS, you can lose or mess up changes you haven't committed yet, but after you commit a snapshot into Git, it is very difficult to lose, especially if you regularly push your database to another repository. +Quando você executa ações no Git, quase todas elas apenas _adicionam_ dados ao banco de dados do Git. +É difícil fazer o sistema fazer qualquer coisa que não seja desfazível ou fazê-lo apagar dados de alguma forma. +Como com qualquer VCS, você pode perder ou bagunçar alterações que ainda não commitou, mas depois que você faz o commit de um snapshot no Git, é muito difícil perdê-lo, especialmente se você envia (push) regularmente o seu banco de dados para outro repositório. -This makes using Git a joy because we know we can experiment without the danger of severely screwing things up. -For a more in-depth look at how Git stores its data and how you can recover data that seems lost, see <>. +Isso faz com que usar o Git seja uma alegria, porque sabemos que podemos experimentar sem o perigo de estragar as coisas gravemente. +Para uma visão mais aprofundada de como o Git armazena seus dados e como você pode recuperar dados que parecem perdidos, veja <>. -==== The Three States +==== Os Três Estados -Pay attention now -- here is the main thing to remember about Git if you want the rest of your learning process to go smoothly. -Git has three main states that your files can reside in: _modified_, _staged_, and _committed_: +Preste atenção agora -- aqui está a principal coisa a lembrar sobre o Git se você quiser que o resto do seu processo de aprendizado ocorra sem problemas. +O Git tem três estados principais nos quais seus arquivos podem residir: _modificado_, _preparado_ e _commitado_: -* Modified means that you have changed the file but have not committed it to your database yet. -* Staged means that you have marked a modified file in its current version to go into your next commit snapshot. -* Committed means that the data is safely stored in your local database. +* Modificado significa que você alterou o arquivo, mas ainda não o commitou em seu banco de dados. +* Preparado significa que você marcou um arquivo modificado em sua versão atual para entrar em seu próximo snapshot de commit. +* Commitado significa que os dados estão armazenados com segurança em seu banco de dados local. -This leads us to the three main sections of a Git project: the working tree, the staging area, and the Git directory. +Isso nos leva às três seções principais de um projeto Git: a árvore de trabalho, a área de preparação e o diretório Git. -.Working tree, staging area, and Git directory -image::images/areas.png["Working tree, staging area, and Git directory"] +.Árvore de trabalho, área de preparação e diretório Git +image::images/areas.png["Árvore de trabalho, área de preparação e diretório Git"] -The working tree is a single checkout of one version of the project. -These files are pulled out of the compressed database in the Git directory and placed on disk for you to use or modify. +A árvore de trabalho é um único checkout de uma versão do projeto. +Esses arquivos são retirados do banco de dados compactado no diretório Git e colocados no disco para você usar ou modificar. -The staging area is a file, generally contained in your Git directory, that stores information about what will go into your next commit. -Its technical name in Git parlance is the "`index`", but the phrase "`staging area`" works just as well. +A área de preparação é um arquivo, geralmente contido no seu diretório Git, que armazena informações sobre o que irá para o seu próximo commit. +Seu nome técnico no jargão do Git é o "`index`", mas a frase "`área de preparação`" funciona da mesma forma. -The Git directory is where Git stores the metadata and object database for your project. -This is the most important part of Git, and it is what is copied when you _clone_ a repository from another computer. +O diretório Git é onde o Git armazena os metadados e o banco de dados de objetos para o seu projeto. +Esta é a parte mais importante do Git e é o que é copiado quando você _clona_ um repositório de outro computador. -The basic Git workflow goes something like this: +O fluxo de trabalho básico do Git é mais ou menos assim: -1. You modify files in your working tree. -2. You selectively stage just those changes you want to be part of your next commit, which adds _only_ those changes to the staging area. -3. You do a commit, which takes the files as they are in the staging area and stores that snapshot permanently to your Git directory. +1. Você modifica arquivos na sua árvore de trabalho. +2. Você prepara (stage) seletivamente apenas as alterações que deseja que façam parte do seu próximo commit, o que adiciona _apenas_ essas alterações à área de preparação. +3. Você faz um commit, o que pega os arquivos como eles estão na área de preparação e armazena esse snapshot permanentemente no seu diretório Git. -If a particular version of a file is in the Git directory, it's considered _committed_. -If it has been modified and was added to the staging area, it is _staged_. -And if it was changed since it was checked out but has not been staged, it is _modified_. -In <>, you'll learn more about these states and how you can either take advantage of them or skip the staged part entirely. +Se uma versão particular de um arquivo está no diretório Git, ela é considerada _commitada_. +Se ela foi modificada e foi adicionada à área de preparação, ela está _preparada_. +E se ela foi alterada desde o checkout, mas não foi preparada, ela está _modificada_. +No <>, você aprenderá mais sobre esses estados e como você pode tirar vantagem deles ou pular a parte preparada inteiramente. diff --git a/ch01-getting-started.asc b/ch01-getting-started.asc index b5f0d22c..5bf436f4 100644 --- a/ch01-getting-started.asc +++ b/ch01-getting-started.asc @@ -1,9 +1,9 @@ [[ch01-getting-started]] -== Getting Started +== Primeiros Passos -This chapter will be about getting started with Git. -We will begin by explaining some background on version control tools, then move on to how to get Git running on your system and finally how to get it set up to start working with. -At the end of this chapter you should understand why Git is around, why you should use it and you should be all set up to do so. +Este capítulo é sobre como dar os primeiros passos com o Git. +Começaremos explicando alguns fundamentos sobre ferramentas de controle de versão, em seguida, passaremos para como fazer o Git rodar em seu sistema e, por fim, como configurá-lo para começar a trabalhar. +Ao final deste capítulo, você deverá entender por que o Git existe, por que você deve usá-lo e deve estar com tudo configurado para fazê-lo. include::book/01-introduction/sections/about-version-control.asc[] @@ -19,8 +19,8 @@ include::book/01-introduction/sections/first-time-setup.asc[] include::book/01-introduction/sections/help.asc[] -=== Summary +=== Resumo -You should have a basic understanding of what Git is and how it's different from any centralized version control systems you may have been using previously. -You should also now have a working version of Git on your system that's set up with your personal identity. -It's now time to learn some Git basics. +Você deve ter um entendimento básico do que é o Git e como ele é diferente de quaisquer sistemas de controle de versão centralizados que você possa ter usado anteriormente. +Você também deve ter agora uma versão funcional do Git em seu sistema que está configurada com sua identidade pessoal. +Agora é a hora de aprender alguns fundamentos do Git. From 1175b1abc2d30311ba3ce098c121c0a8f90ba844 Mon Sep 17 00:00:00 2001 From: "Sergio Cabral (AI Agent)" Date: Thu, 20 Aug 2026 13:51:57 -0300 Subject: [PATCH 04/16] =?UTF-8?q?Traduz:=20Cap=C3=ADtulo=202=20=E2=80=94?= =?UTF-8?q?=20Fundamentos=20do=20Git?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- book/02-git-basics/sections/aliases.asc | 38 +- .../sections/getting-a-repository.asc | 68 ++-- .../sections/recording-changes.asc | 340 +++++++++--------- book/02-git-basics/sections/remotes.asc | 138 +++---- book/02-git-basics/sections/tagging.asc | 126 +++---- book/02-git-basics/sections/undoing.asc | 144 ++++---- .../sections/viewing-history.asc | 190 +++++----- ch02-git-basics-chapter.asc | 16 +- 8 files changed, 530 insertions(+), 530 deletions(-) diff --git a/book/02-git-basics/sections/aliases.asc b/book/02-git-basics/sections/aliases.asc index 5d6d117c..537c9a7c 100644 --- a/book/02-git-basics/sections/aliases.asc +++ b/book/02-git-basics/sections/aliases.asc @@ -1,13 +1,13 @@ [[_git_aliases]] -=== Git Aliases +=== Aliases (Apelidos) no Git (((aliases))) -Before we move on to the next chapter, we want to introduce a feature that can make your Git experience simpler, easier, and more familiar: aliases. -For clarity's sake, we won't be using them anywhere else in this book, but if you go on to use Git with any regularity, aliases are something you should know about. +Antes de passarmos para o próximo capítulo, queremos introduzir um recurso que pode tornar a sua experiência com o Git mais simples, fácil e familiar: os aliases (apelidos). +Para fins de clareza, não os usaremos em nenhum outro lugar neste livro, mas se você continuar a usar o Git com alguma regularidade, aliases são algo que você deve conhecer. -Git doesn't automatically infer your command if you type it in partially. -If you don't want to type the entire text of each of the Git commands, you can easily set up an alias for each command using `git config`.(((git commands, config))) -Here are a couple of examples you may want to set up: +O Git não infere automaticamente o seu comando se você digitá-lo parcialmente. +Se você não quiser digitar o texto inteiro de cada um dos comandos do Git, poderá configurar facilmente um alias para cada comando usando `git config`.(((git commands, config))) +Aqui estão alguns exemplos que você pode querer configurar: [source,console] ---- @@ -17,18 +17,18 @@ $ git config --global alias.ci commit $ git config --global alias.st status ---- -This means that, for example, instead of typing `git commit`, you just need to type `git ci`. -As you go on using Git, you'll probably use other commands frequently as well; don't hesitate to create new aliases. +Isso significa que, por exemplo, em vez de digitar `git commit`, você só precisa digitar `git ci`. +À medida que continuar usando o Git, você provavelmente usará outros comandos com frequência também; não hesite em criar novos aliases. -This technique can also be very useful in creating commands that you think should exist. -For example, to correct the usability problem you encountered with unstaging a file, you can add your own unstage alias to Git: +Esta técnica também pode ser muito útil para criar comandos que você acha que deveriam existir. +Por exemplo, para corrigir o problema de usabilidade que você encontrou ao retirar a preparação (unstage) de um arquivo, você pode adicionar seu próprio alias de unstage ao Git: [source,console] ---- $ git config --global alias.unstage 'reset HEAD --' ---- -This makes the following two commands equivalent: +Isso torna os dois comandos a seguir equivalentes: [source,console] ---- @@ -36,15 +36,15 @@ $ git unstage fileA $ git reset HEAD -- fileA ---- -This seems a bit clearer. -It's also common to add a `last` command, like this: +Isso parece um pouco mais claro. +Também é comum adicionar um comando `last`, assim: [source,console] ---- $ git config --global alias.last 'log -1 HEAD' ---- -This way, you can see the last commit easily: +Desta forma, você pode ver o último commit facilmente: [source,console] ---- @@ -58,11 +58,11 @@ Date: Tue Aug 26 19:48:51 2008 +0800 Signed-off-by: Scott Chacon ---- -As you can tell, Git simply replaces the new command with whatever you alias it for. -However, maybe you want to run an external command, rather than a Git subcommand. -In that case, you start the command with a `!` character. -This is useful if you write your own tools that work with a Git repository. -We can demonstrate by aliasing `git visual` to run `gitk`: +Como você pode ver, o Git simplesmente substitui o novo comando pelo que você criou como alias. +No entanto, talvez você queira executar um comando externo, em vez de um subcomando do Git. +Nesse caso, você inicia o comando com um caractere `!`. +Isso é útil se você escrever suas próprias ferramentas que funcionam com um repositório Git. +Podemos demonstrar isso criando um alias para `git visual` para executar o `gitk`: [source,console] ---- diff --git a/book/02-git-basics/sections/getting-a-repository.asc b/book/02-git-basics/sections/getting-a-repository.asc index 3b69efd0..3e515411 100644 --- a/book/02-git-basics/sections/getting-a-repository.asc +++ b/book/02-git-basics/sections/getting-a-repository.asc @@ -1,47 +1,47 @@ [[_getting_a_repo]] -=== Getting a Git Repository +=== Obtendo um Repositório Git -You typically obtain a Git repository in one of two ways: +Você normalmente obtém um repositório Git de uma de duas maneiras: -1. You can take a local directory that is currently not under version control, and turn it into a Git repository, or -2. You can _clone_ an existing Git repository from elsewhere. +1. Você pode pegar um diretório local que não esteja sob controle de versão, e transformá-lo em um repositório Git, ou +2. Você pode _clonar_ um repositório Git existente de outro lugar. -In either case, you end up with a Git repository on your local machine, ready for work. +Em ambos os casos, você acaba com um repositório Git em sua máquina local, pronto para o trabalho. -==== Initializing a Repository in an Existing Directory +==== Inicializando um repositório em um diretório existente -If you have a project directory that is currently not under version control and you want to start controlling it with Git, you first need to go to that project's directory. -If you've never done this, it looks a little different depending on which system you're running: +Se você tem um diretório de projeto que não está atualmente sob controle de versão e deseja começar a controlá-lo com o Git, você primeiro precisa ir para o diretório desse projeto. +Se você nunca fez isso, parece um pouco diferente dependendo de qual sistema você está executando: -for Linux: +para Linux: [source,console] ---- $ cd /home/user/my_project ---- -for macOS: +para macOS: [source,console] ---- $ cd /Users/user/my_project ---- -for Windows: +para Windows: [source,console] ---- $ cd C:/Users/user/my_project ---- -and type: +e digite: [source,console] ---- $ git init ---- -This creates a new subdirectory named `.git` that contains all of your necessary repository files -- a Git repository skeleton. -At this point, nothing in your project is tracked yet. -See <> for more information about exactly what files are contained in the `.git` directory you just created.(((git commands, init))) +Isso cria um novo subdiretório chamado `.git` que contém todos os arquivos de repositório necessários -- um esqueleto de repositório Git. +Neste ponto, nada em seu projeto é rastreado ainda. +Veja <> para mais informações sobre exatamente quais arquivos estão contidos no diretório `.git` que você acabou de criar.(((git commands, init))) -If you want to start version-controlling existing files (as opposed to an empty directory), you should probably begin tracking those files and do an initial commit. -You can accomplish that with a few `git add` commands that specify the files you want to track, followed by a `git commit`: +Se você quiser começar a controlar a versão de arquivos existentes (em oposição a um diretório vazio), você provavelmente deve começar a rastrear esses arquivos e fazer um commit inicial. +Você pode realizar isso com alguns comandos `git add` que especificam os arquivos que você deseja rastrear, seguidos por um `git commit`: [source,console] ---- @@ -50,38 +50,38 @@ $ git add LICENSE $ git commit -m 'Initial project version' ---- -We'll go over what these commands do in just a minute. -At this point, you have a Git repository with tracked files and an initial commit. +Vamos analisar o que esses comandos fazem em apenas um minuto. +Neste ponto, você tem um repositório Git com arquivos rastreados e um commit inicial. [[_git_cloning]] -==== Cloning an Existing Repository +==== Clonando um Repositório Existente -If you want to get a copy of an existing Git repository -- for example, a project you'd like to contribute to -- the command you need is `git clone`. -If you're familiar with other VCSs such as Subversion, you'll notice that the command is "clone" and not "checkout". -This is an important distinction -- instead of getting just a working copy, Git receives a full copy of nearly all data that the server has. -Every version of every file for the history of the project is pulled down by default when you run `git clone`. -In fact, if your server disk gets corrupted, you can often use nearly any of the clones on any client to set the server back to the state it was in when it was cloned (you may lose some server-side hooks and such, but all the versioned data would be there -- see <> for more details). +Se você quiser obter uma cópia de um repositório Git existente -- por exemplo, um projeto para o qual você gostaria de contribuir -- o comando de que você precisa é `git clone`. +Se você está familiarizado com outros VCSs como Subversion, notará que o comando é "clone" e não "checkout". +Essa é uma distinção importante -- em vez de obter apenas uma cópia de trabalho, o Git recebe uma cópia completa de quase todos os dados que o servidor possui. +Toda versão de todo arquivo do histórico do projeto é baixada (pulled down) por padrão quando você executa `git clone`. +De fato, se o disco do seu servidor for corrompido, muitas vezes você pode usar quase qualquer um dos clones em qualquer cliente para restaurar o servidor ao estado em que estava quando foi clonado (você pode perder alguns hooks do lado do servidor e coisas do tipo, mas todos os dados versionados estariam lá -- veja <> para mais detalhes). -You clone a repository with `git clone `.(((git commands, clone))) -For example, if you want to clone the Git linkable library called `libgit2`, you can do so like this: +Você clona um repositório com `git clone `.(((git commands, clone))) +Por exemplo, se você quiser clonar a biblioteca vinculável (linkable library) do Git chamada `libgit2`, pode fazer isso assim: [source,console] ---- $ git clone https://github.com/libgit2/libgit2 ---- -That creates a directory named `libgit2`, initializes a `.git` directory inside it, pulls down all the data for that repository, and checks out a working copy of the latest version. -If you go into the new `libgit2` directory that was just created, you'll see the project files in there, ready to be worked on or used. +Isso cria um diretório chamado `libgit2`, inicializa um diretório `.git` dentro dele, baixa todos os dados para aquele repositório e faz o checkout de uma cópia de trabalho da versão mais recente. +Se você entrar no novo diretório `libgit2` que acabou de ser criado, verá os arquivos do projeto lá, prontos para serem trabalhados ou usados. -If you want to clone the repository into a directory named something other than `libgit2`, you can specify the new directory name as an additional argument: +Se você quiser clonar o repositório em um diretório com um nome diferente de `libgit2`, pode especificar o novo nome do diretório como um argumento adicional: [source,console] ---- $ git clone https://github.com/libgit2/libgit2 mylibgit ---- -That command does the same thing as the previous one, but the target directory is called `mylibgit`. +Esse comando faz a mesma coisa que o anterior, mas o diretório de destino é chamado `mylibgit`. -Git has a number of different transfer protocols you can use. -The previous example uses the `https://` protocol, but you may also see `git://` or `user@server:path/to/repo.git`, which uses the SSH transfer protocol. -<> will introduce all of the available options the server can set up to access your Git repository and the pros and cons of each. +O Git possui vários protocolos de transferência diferentes que você pode usar. +O exemplo anterior usa o protocolo `https://`, mas você também pode ver `git://` ou `user@server:path/to/repo.git`, que usa o protocolo de transferência SSH. +<> apresentará todas as opções disponíveis que o servidor pode configurar para acessar seu repositório Git e os prós e contras de cada uma. diff --git a/book/02-git-basics/sections/recording-changes.asc b/book/02-git-basics/sections/recording-changes.asc index 8bcd785f..de7aa208 100644 --- a/book/02-git-basics/sections/recording-changes.asc +++ b/book/02-git-basics/sections/recording-changes.asc @@ -1,26 +1,26 @@ -=== Recording Changes to the Repository +=== Gravando Alterações no Repositório -At this point, you should have a _bona fide_ Git repository on your local machine, and a checkout or _working copy_ of all of its files in front of you. -Typically, you'll want to start making changes and committing snapshots of those changes into your repository each time the project reaches a state you want to record. +Neste ponto, você deve ter um repositório Git _bona fide_ na sua máquina local e um checkout ou _cópia de trabalho_ (_working copy_) de todos os seus arquivos à sua frente. +Normalmente, você vai querer começar a fazer alterações e fazer o commit de snapshots dessas alterações no seu repositório cada vez que o projeto atingir um estado que você deseja gravar. -Remember that each file in your working directory can be in one of two states: _tracked_ or _untracked_. -Tracked files are files that were in the last snapshot, as well as any newly staged files; they can be unmodified, modified, or staged. -In short, tracked files are files that Git knows about. +Lembre-se de que cada arquivo no seu diretório de trabalho pode estar em um de dois estados: _rastreado_ (_tracked_) ou _não rastreado_ (_untracked_). +Arquivos rastreados são arquivos que estavam no último snapshot, bem como quaisquer arquivos recém-preparados; eles podem estar não modificados, modificados ou preparados (staged). +Em resumo, arquivos rastreados são arquivos que o Git conhece. -Untracked files are everything else -- any files in your working directory that were not in your last snapshot and are not in your staging area. -When you first clone a repository, all of your files will be tracked and unmodified because Git just checked them out and you haven't edited anything. +Arquivos não rastreados são tudo o mais -- quaisquer arquivos no seu diretório de trabalho que não estavam no seu último snapshot e não estão na sua área de preparação. +Quando você clona um repositório pela primeira vez, todos os seus arquivos estarão rastreados e não modificados, porque o Git acabou de fazer o checkout deles e você não editou nada. -As you edit files, Git sees them as modified, because you've changed them since your last commit. -As you work, you selectively stage these modified files and then commit all those staged changes, and the cycle repeats. +À medida que você edita os arquivos, o Git os vê como modificados, porque você os alterou desde o último commit. +Conforme você trabalha, você prepara seletivamente esses arquivos modificados e, em seguida, faz o commit de todas essas alterações preparadas, e o ciclo se repete. -.The lifecycle of the status of your files -image::images/lifecycle.png[The lifecycle of the status of your files] +.O ciclo de vida do status dos seus arquivos +image::images/lifecycle.png[O ciclo de vida do status dos seus arquivos] [[_checking_status]] -==== Checking the Status of Your Files +==== Verificando o status dos seus arquivos -The main tool you use to determine which files are in which state is the `git status` command.(((git commands, status))) -If you run this command directly after a clone, you should see something like this: +A principal ferramenta que você usa para determinar quais arquivos estão em qual estado é o comando `git status`.(((git commands, status))) +Se você executar este comando logo após um clone, deverá ver algo assim: [source,console] ---- @@ -30,23 +30,23 @@ Your branch is up-to-date with 'origin/master'. nothing to commit, working tree clean ---- -This means you have a clean working directory; in other words, none of your tracked files are modified. -Git also doesn't see any untracked files, or they would be listed here. -Finally, the command tells you which branch you're on and informs you that it has not diverged from the same branch on the server. -For now, that branch is always `master`, which is the default; you won't worry about it here. -<> will go over branches and references in detail. +Isso significa que você tem um diretório de trabalho limpo; em outras palavras, nenhum dos seus arquivos rastreados foi modificado. +O Git também não vê nenhum arquivo não rastreado, ou eles estariam listados aqui. +Por fim, o comando informa em qual branch você está e informa que não divergiu do mesmo branch no servidor. +Por enquanto, esse branch é sempre `master`, que é o padrão; você não vai se preocupar com isso aqui. +<> abordará branches e referências em detalhes. [NOTE] ==== -GitHub changed the default branch name from `master` to `main` in mid-2020, and other Git hosts followed suit. -So you may find that the default branch name in some newly created repositories is `main` and not `master`. -In addition, the default branch name can be changed (as you have seen in <>), so you may see a different name for the default branch. +O GitHub mudou o nome padrão do branch de `master` para `main` em meados de 2020, e outros hosts Git seguiram o exemplo. +Portanto, você pode descobrir que o nome padrão do branch em alguns repositórios recém-criados é `main` e não `master`. +Além disso, o nome padrão do branch pode ser alterado (como você viu em <>), então você pode ver um nome diferente para o branch padrão. -However, Git itself still uses `master` as the default, so we will use it throughout the book. +No entanto, o próprio Git ainda usa `master` como padrão, então nós o usaremos em todo o livro. ==== -Let's say you add a new file to your project, a simple `README` file. -If the file didn't exist before, and you run `git status`, you see your untracked file like so: +Digamos que você adicione um novo arquivo ao seu projeto, um arquivo `README` simples. +Se o arquivo não existia antes e você executar `git status`, verá seu arquivo não rastreado assim: [source,console] ---- @@ -62,23 +62,23 @@ Untracked files: nothing added to commit but untracked files present (use "git add" to track) ---- -You can see that your new `README` file is untracked, because it's under the "`Untracked files`" heading in your status output. -Untracked basically means that Git sees a file you didn't have in the previous snapshot (commit), and which hasn't yet been staged; Git won't start including it in your commit snapshots until you explicitly tell it to do so. -It does this so you don't accidentally begin including generated binary files or other files that you did not mean to include. -You do want to start including `README`, so let's start tracking the file. +Você pode ver que seu novo arquivo `README` não é rastreado, porque está sob o cabeçalho "`Untracked files`" na saída do status. +Não rastreado basicamente significa que o Git vê um arquivo que você não tinha no snapshot anterior (commit) e que ainda não foi preparado; o Git não começará a incluí-lo em seus snapshots de commit até que você diga explicitamente a ele para fazer isso. +Ele faz isso para que você não comece acidentalmente a incluir arquivos binários gerados ou outros arquivos que você não pretendia incluir. +Você quer começar a incluir o `README`, então vamos começar a rastrear o arquivo. [[_tracking_files]] -==== Tracking New Files +==== Rastreando Novos Arquivos -In order to begin tracking a new file, you use the command `git add`.(((git commands, add))) -To begin tracking the `README` file, you can run this: +Para começar a rastrear um novo arquivo, você usa o comando `git add`.(((git commands, add))) +Para começar a rastrear o arquivo `README`, você pode executar isto: [source,console] ---- $ git add README ---- -If you run your status command again, you can see that your `README` file is now tracked and staged to be committed: +Se você executar seu comando status novamente, poderá ver que seu arquivo `README` agora está rastreado e preparado para ser commitado: [source,console] ---- @@ -92,15 +92,15 @@ Changes to be committed: ---- -You can tell that it's staged because it's under the "`Changes to be committed`" heading. -If you commit at this point, the version of the file at the time you ran `git add` is what will be in the subsequent historical snapshot. -You may recall that when you ran `git init` earlier, you then ran `git add ` -- that was to begin tracking files in your directory.(((git commands, init)))(((git commands, add))) -The `git add` command takes a path name for either a file or a directory; if it's a directory, the command adds all the files in that directory recursively. +Você pode dizer que ele está preparado porque está sob o cabeçalho "`Changes to be committed`". +Se você fizer o commit neste ponto, a versão do arquivo no momento em que você executou o `git add` é a que estará no snapshot histórico subsequente. +Você deve se lembrar que, quando executou o `git init` anteriormente, executou o `git add ` em seguida -- isso foi para começar a rastrear arquivos no seu diretório.(((git commands, init)))(((git commands, add))) +O comando `git add` recebe um nome de caminho para um arquivo ou diretório; se for um diretório, o comando adiciona todos os arquivos desse diretório recursivamente. -==== Staging Modified Files +==== Preparando Arquivos Modificados -Let's change a file that was already tracked. -If you change a previously tracked file called `CONTRIBUTING.md` and then run your `git status` command again, you get something that looks like this: +Vamos alterar um arquivo que já estava rastreado. +Se você alterar um arquivo previamente rastreado chamado `CONTRIBUTING.md` e depois executar seu comando `git status` novamente, obterá algo parecido com isto: [source,console] ---- @@ -120,11 +120,11 @@ Changes not staged for commit: ---- -The `CONTRIBUTING.md` file appears under a section named "`Changes not staged for commit`" -- which means that a file that is tracked has been modified in the working directory but not yet staged. -To stage it, you run the `git add` command. -`git add` is a multipurpose command -- you use it to begin tracking new files, to stage files, and to do other things like marking merge-conflicted files as resolved. -It may be helpful to think of it more as "`add precisely this content to the next commit`" rather than "`add this file to the project`".(((git commands, add))) -Let's run `git add` now to stage the `CONTRIBUTING.md` file, and then run `git status` again: +O arquivo `CONTRIBUTING.md` aparece em uma seção chamada "`Changes not staged for commit`" -- o que significa que um arquivo que é rastreado foi modificado no diretório de trabalho, mas ainda não foi preparado. +Para prepará-lo, você executa o comando `git add`. +`git add` é um comando polivalente -- você o usa para começar a rastrear novos arquivos, preparar arquivos e fazer outras coisas como marcar arquivos com conflito de mesclagem (merge-conflicted files) como resolvidos. +Pode ser útil pensar nele mais como "`adicione precisamente este conteúdo ao próximo commit`" em vez de "`adicione este arquivo ao projeto`".(((git commands, add))) +Vamos executar `git add` agora para preparar o arquivo `CONTRIBUTING.md` e depois executar `git status` novamente: [source,console] ---- @@ -140,10 +140,10 @@ Changes to be committed: ---- -Both files are staged and will go into your next commit. -At this point, suppose you remember one little change that you want to make in `CONTRIBUTING.md` before you commit it. -You open it again and make that change, and you're ready to commit. -However, let's run `git status` one more time: +Ambos os arquivos estão preparados e irão para o seu próximo commit. +Neste ponto, suponha que você se lembre de uma pequena alteração que deseja fazer no `CONTRIBUTING.md` antes de fazer o commit dele. +Você o abre novamente e faz essa alteração, e está pronto para fazer o commit. +No entanto, vamos executar `git status` mais uma vez: [source,console] ---- @@ -165,12 +165,12 @@ Changes not staged for commit: ---- -What the heck? -Now `CONTRIBUTING.md` is listed as both staged _and_ unstaged. -How is that possible? -It turns out that Git stages a file exactly as it is when you run the `git add` command. -If you commit now, the version of `CONTRIBUTING.md` as it was when you last ran the `git add` command is how it will go into the commit, not the version of the file as it looks in your working directory when you run `git commit`. -If you modify a file after you run `git add`, you have to run `git add` again to stage the latest version of the file: +Que diabos? +Agora o `CONTRIBUTING.md` está listado como preparado _e_ não preparado. +Como isso é possível? +Acontece que o Git prepara um arquivo exatamente como ele é quando você executa o comando `git add`. +Se você fizer o commit agora, a versão de `CONTRIBUTING.md` como era quando você executou o comando `git add` pela última vez é como ela entrará no commit, não a versão do arquivo como aparece no seu diretório de trabalho quando você executa `git commit`. +Se você modificar um arquivo depois de executar `git add`, precisará executar `git add` novamente para preparar a versão mais recente do arquivo: [source,console] ---- @@ -185,11 +185,11 @@ Changes to be committed: modified: CONTRIBUTING.md ---- -==== Short Status +==== Status Curto -While the `git status` output is pretty comprehensive, it's also quite wordy. -Git also has a short status flag so you can see your changes in a more compact way. -If you run `git status -s` or `git status --short` you get a far more simplified output from the command: +Embora a saída de `git status` seja bem abrangente, ela também é bastante prolixa. +O Git também tem uma flag de status curto (short status) para que você possa ver suas alterações de uma maneira mais compacta. +Se você executar `git status -s` ou `git status --short`, obterá uma saída muito mais simplificada do comando: [source,console] ---- @@ -201,18 +201,18 @@ M lib/simplegit.rb ?? LICENSE.txt ---- -New files that aren't tracked have a `??` next to them, new files that have been added to the staging area have an `A`, modified files have an `M` and so on. -There are two columns to the output -- the left-hand column indicates the status of the staging area and the right-hand column indicates the status of the working tree. -So for example in that output, the `README` file is modified in the working directory but not yet staged, while the `lib/simplegit.rb` file is modified and staged. -The `Rakefile` was modified, staged and then modified again, so there are changes to it that are both staged and unstaged. +Arquivos novos que não são rastreados têm um `??` ao lado deles, arquivos novos que foram adicionados à área de preparação têm um `A`, arquivos modificados têm um `M` e assim por diante. +Existem duas colunas na saída -- a coluna da esquerda indica o status da área de preparação e a coluna da direita indica o status da árvore de trabalho (working tree). +Portanto, por exemplo nessa saída, o arquivo `README` foi modificado no diretório de trabalho, mas ainda não foi preparado, enquanto o arquivo `lib/simplegit.rb` foi modificado e preparado. +O `Rakefile` foi modificado, preparado e modificado novamente, portanto, há alterações nele que estão preparadas e não preparadas. [[_ignoring]] -==== Ignoring Files +==== Ignorando Arquivos -Often, you'll have a class of files that you don't want Git to automatically add or even show you as being untracked. -These are generally automatically generated files such as log files or files produced by your build system. -In such cases, you can create a file listing patterns to match them named `.gitignore`.(((ignoring files))) -Here is an example `.gitignore` file: +Geralmente, você terá uma classe de arquivos que não deseja que o Git adicione automaticamente ou até mesmo mostre a você como não rastreados. +Estes geralmente são arquivos gerados automaticamente, como arquivos de log ou arquivos produzidos pelo seu sistema de compilação (build system). +Nesses casos, você pode criar um arquivo listando padrões que correspondam a eles, chamado `.gitignore`.(((ignoring files))) +Aqui está um exemplo de arquivo `.gitignore`: [source,console] ---- @@ -221,24 +221,24 @@ $ cat .gitignore *~ ---- -The first line tells Git to ignore any files ending in "`.o`" or "`.a`" -- object and archive files that may be the product of building your code. -The second line tells Git to ignore all files whose names end with a tilde (`~`), which is used by many text editors such as Emacs to mark temporary files. -You may also include a log, tmp, or pid directory; automatically generated documentation; and so on. -Setting up a `.gitignore` file for your new repository before you get going is generally a good idea so you don't accidentally commit files that you really don't want in your Git repository. +A primeira linha diz ao Git para ignorar quaisquer arquivos que terminem em "`.o`" ou "`.a`" -- arquivos de objeto e de arquivamento (archive) que podem ser o produto da compilação do seu código. +A segunda linha diz ao Git para ignorar todos os arquivos cujos nomes terminam com um til (`~`), o que é usado por muitos editores de texto como o Emacs para marcar arquivos temporários. +Você também pode incluir um diretório de log, tmp ou pid; documentação gerada automaticamente; e assim por diante. +Configurar um arquivo `.gitignore` para o seu novo repositório antes de começar é geralmente uma boa ideia, para que você não faça o commit acidentalmente de arquivos que você realmente não deseja em seu repositório Git. -The rules for the patterns you can put in the `.gitignore` file are as follows: +As regras para os padrões que você pode colocar no arquivo `.gitignore` são as seguintes: -* Blank lines or lines starting with `#` are ignored. -* Standard glob patterns work, and will be applied recursively throughout the entire working tree. -* You can start patterns with a forward slash (`/`) to avoid recursivity. -* You can end patterns with a forward slash (`/`) to specify a directory. -* You can negate a pattern by starting it with an exclamation point (`!`). +* Linhas em branco ou linhas começando com `#` são ignoradas. +* Os padrões de glob (glob patterns) padrão funcionam e serão aplicados recursivamente em toda a árvore de trabalho. +* Você pode iniciar os padrões com uma barra normal (`/`) para evitar a recursividade. +* Você pode terminar os padrões com uma barra normal (`/`) para especificar um diretório. +* Você pode negar um padrão iniciando-o com um ponto de exclamação (`!`). -Glob patterns are like simplified regular expressions that shells use. -An asterisk (`\*`) matches zero or more characters; `[abc]` matches any character inside the brackets (in this case a, b, or c); a question mark (`?`) matches a single character; and brackets enclosing characters separated by a hyphen (`[0-9]`) matches any character between them (in this case 0 through 9). -You can also use two asterisks to match nested directories; `a/**/z` would match `a/z`, `a/b/z`, `a/b/c/z`, and so on. +Os padrões de glob são como expressões regulares simplificadas que os shells usam. +Um asterisco (`\*`) corresponde a zero ou mais caracteres; `[abc]` corresponde a qualquer caractere dentro dos colchetes (neste caso, a, b ou c); um ponto de interrogação (`?`) corresponde a um único caractere; e os caracteres dentro de colchetes separados por um hífen (`[0-9]`) correspondem a qualquer caractere entre eles (neste caso, de 0 a 9). +Você também pode usar dois asteriscos para corresponder a diretórios aninhados; `a/**/z` corresponderia a `a/z`, `a/b/z`, `a/b/c/z` e assim por diante. -Here is another example `.gitignore` file: +Aqui está outro exemplo de arquivo `.gitignore`: [source] ---- @@ -263,29 +263,29 @@ doc/**/*.pdf [TIP] ==== -GitHub maintains a fairly comprehensive list of good `.gitignore` file examples for dozens of projects and languages at https://github.com/github/gitignore[^] if you want a starting point for your project. +O GitHub mantém uma lista bastante abrangente de bons exemplos de arquivos `.gitignore` para dezenas de projetos e linguagens em https://github.com/github/gitignore[^] se você quiser um ponto de partida para o seu projeto. ==== [NOTE] ==== -In the simple case, a repository might have a single `.gitignore` file in its root directory, which applies recursively to the entire repository. -However, it is also possible to have additional `.gitignore` files in subdirectories. -The rules in these nested `.gitignore` files apply only to the files under the directory where they are located. -The Linux kernel source repository has 206 `.gitignore` files. +No caso simples, um repositório pode ter um único arquivo `.gitignore` em seu diretório raiz, que se aplica recursivamente a todo o repositório. +No entanto, também é possível ter arquivos `.gitignore` adicionais em subdiretórios. +As regras nesses arquivos `.gitignore` aninhados se aplicam apenas aos arquivos no diretório onde estão localizados. +O repositório de código-fonte do kernel do Linux tem 206 arquivos `.gitignore`. -It is beyond the scope of this book to get into the details of multiple `.gitignore` files; see `man gitignore` for the details. +Está além do escopo deste livro entrar em detalhes de vários arquivos `.gitignore`; veja `man gitignore` para obter os detalhes. ==== [[_git_diff_staged]] -==== Viewing Your Staged and Unstaged Changes +==== Visualizando suas Alterações Preparadas e Não Preparadas -If the `git status` command is too vague for you -- you want to know exactly what you changed, not just which files were changed -- you can use the `git diff` command.(((git commands, diff))) -We'll cover `git diff` in more detail later, but you'll probably use it most often to answer these two questions: What have you changed but not yet staged? -And what have you staged that you are about to commit? -Although `git status` answers those questions very generally by listing the file names, `git diff` shows you the exact lines added and removed -- the patch, as it were. +Se o comando `git status` for muito vago para você -- você quer saber exatamente o que você alterou, não apenas quais arquivos foram alterados -- você pode usar o comando `git diff`.(((git commands, diff))) +Abordaremos o `git diff` com mais detalhes posteriormente, mas você provavelmente o usará com mais frequência para responder a estas duas perguntas: O que você alterou, mas ainda não preparou? +E o que você preparou que está prestes a fazer o commit? +Embora `git status` responda a essas perguntas de maneira muito geral, listando os nomes dos arquivos, `git diff` mostra as linhas exatas adicionadas e removidas -- o patch, por assim dizer. -Let's say you edit and stage the `README` file again and then edit the `CONTRIBUTING.md` file without staging it. -If you run your `git status` command, you once again see something like this: +Digamos que você edite e prepare o arquivo `README` novamente e, em seguida, edite o arquivo `CONTRIBUTING.md` sem prepará-lo. +Se você executar seu comando `git status`, verá mais uma vez algo assim: [source,console] ---- @@ -304,7 +304,7 @@ Changes not staged for commit: modified: CONTRIBUTING.md ---- -To see what you've changed but not yet staged, type `git diff` with no other arguments: +Para ver o que você alterou, mas ainda não preparou, digite `git diff` sem outros argumentos: [source,console] ---- @@ -325,11 +325,11 @@ index 8ebb991..643e24f 100644 that highlights your work in progress (and note in the PR title that it's ---- -That command compares what is in your working directory with what is in your staging area. -The result tells you the changes you've made that you haven't yet staged. +Esse comando compara o que está no seu diretório de trabalho com o que está na sua área de preparação. +O resultado informa as alterações que você fez e que ainda não preparou. -If you want to see what you've staged that will go into your next commit, you can use `git diff --staged`. -This command compares your staged changes to your last commit: +Se você quiser ver o que você preparou e que irá para o seu próximo commit, pode usar `git diff --staged`. +Este comando compara suas alterações preparadas com o seu último commit: [source,console] ---- @@ -343,11 +343,11 @@ index 0000000..03902a1 +My Project ---- -It's important to note that `git diff` by itself doesn't show all changes made since your last commit -- only changes that are still unstaged. -If you've staged all of your changes, `git diff` will give you no output. +É importante notar que `git diff` por si só não mostra todas as alterações feitas desde o seu último commit -- apenas as alterações que ainda não foram preparadas. +Se você tiver preparado todas as suas alterações, o `git diff` não fornecerá nenhuma saída. -For another example, if you stage the `CONTRIBUTING.md` file and then edit it, you can use `git diff` to see the changes in the file that are staged and the changes that are unstaged. -If our environment looks like this: +Como outro exemplo, se você preparar o arquivo `CONTRIBUTING.md` e depois editá-lo, poderá usar `git diff` para ver as alterações no arquivo que estão preparadas e as alterações que não estão preparadas. +Se o nosso ambiente for assim: [source,console] ---- @@ -368,7 +368,7 @@ Changes not staged for commit: modified: CONTRIBUTING.md ---- -Now you can use `git diff` to see what is still unstaged: +Agora você pode usar `git diff` para ver o que ainda não foi preparado: [source,console] ---- @@ -384,7 +384,7 @@ index 643e24f..87f08c8 100644 +# test line ---- -and `git diff --cached` to see what you've staged so far (`--staged` and `--cached` are synonyms): +e `git diff --cached` para ver o que você preparou até agora (`--staged` e `--cached` são sinônimos): [source,console] ---- @@ -406,36 +406,36 @@ index 8ebb991..643e24f 100644 ---- [NOTE] -.Git Diff in an External Tool +.Git Diff em uma Ferramenta Externa ==== -We will continue to use the `git diff` command in various ways throughout the rest of the book. -There is another way to look at these diffs if you prefer a graphical or external diff viewing program instead. -If you run `git difftool` instead of `git diff`, you can view any of these diffs in software like emerge, vimdiff and many more (including commercial products). -Run `git difftool --tool-help` to see what is available on your system. +Continuaremos a usar o comando `git diff` de várias maneiras ao longo do resto do livro. +Há outra maneira de ver esses diffs se você preferir um programa de visualização de diff gráfico ou externo. +Se você executar `git difftool` em vez de `git diff`, poderá visualizar qualquer um desses diffs em softwares como emerge, vimdiff e muitos outros (incluindo produtos comerciais). +Execute `git difftool --tool-help` para ver o que está disponível em seu sistema. ==== [[_committing_changes]] -==== Committing Your Changes +==== Fazendo o Commit de suas Alterações -Now that your staging area is set up the way you want it, you can commit your changes. -Remember that anything that is still unstaged -- any files you have created or modified that you haven't run `git add` on since you edited them -- won't go into this commit. -They will stay as modified files on your disk. -In this case, let's say that the last time you ran `git status`, you saw that everything was staged, so you're ready to commit your changes.(((git commands, status))) -The simplest way to commit is to type `git commit`:(((git commands, commit))) +Agora que sua área de preparação está configurada do jeito que você deseja, você pode fazer o commit de suas alterações. +Lembre-se de que qualquer coisa que ainda não esteja preparada -- quaisquer arquivos que você criou ou modificou e nos quais não executou `git add` desde que os editou -- não entrará neste commit. +Eles permanecerão como arquivos modificados no seu disco. +Neste caso, digamos que da última vez que você executou `git status`, viu que tudo estava preparado, então você está pronto para fazer o commit das suas alterações.(((git commands, status))) +A maneira mais simples de fazer o commit é digitar `git commit`:(((git commands, commit))) [source,console] ---- $ git commit ---- -Doing so launches your editor of choice. +Isso inicia o seu editor de escolha. [NOTE] ==== -This is set by your shell's `EDITOR` environment variable -- usually vim or emacs, although you can configure it with whatever you want using the `git config --global core.editor` command as you saw in <>.(((editor, changing default)))(((git commands, config))) +Isso é definido pela variável de ambiente `EDITOR` do seu shell -- geralmente vim ou emacs, embora você possa configurá-lo com o que quiser usando o comando `git config --global core.editor`, como você viu em <>.(((editor, changing default)))(((git commands, config))) ==== -The editor displays the following text (this example is a Vim screen): +O editor exibe o seguinte texto (este exemplo é uma tela do Vim): [source] ---- @@ -455,18 +455,18 @@ The editor displays the following text (this example is a Vim screen): ".git/COMMIT_EDITMSG" 9L, 283C ---- -You can see that the default commit message contains the latest output of the `git status` command commented out and one empty line on top. -You can remove these comments and type your commit message, or you can leave them there to help you remember what you're committing. +Você pode ver que a mensagem de commit padrão contém a saída mais recente do comando `git status` comentada e uma linha vazia no topo. +Você pode remover esses comentários e digitar sua mensagem de commit, ou pode deixá-los lá para ajudá-lo a lembrar o que está commitando. [NOTE] ==== -For an even more explicit reminder of what you've modified, you can pass the `-v` option to `git commit`. -Doing so also puts the diff of your change in the editor so you can see exactly what changes you're committing. +Para um lembrete ainda mais explícito do que você modificou, você pode passar a opção `-v` para o `git commit`. +Fazer isso também coloca o diff de sua alteração no editor para que você possa ver exatamente quais alterações está commitando. ==== -When you exit the editor, Git creates your commit with that commit message (with the comments and diff stripped out). +Quando você sai do editor, o Git cria o seu commit com essa mensagem de commit (com os comentários e o diff removidos). -Alternatively, you can type your commit message inline with the `commit` command by specifying it after a `-m` flag, like this: +Alternativamente, você pode digitar sua mensagem de commit embutida no comando `commit` especificando-a após a flag `-m`, assim: [source,console] ---- @@ -476,19 +476,19 @@ $ git commit -m "Story 182: fix benchmarks for speed" create mode 100644 README ---- -Now you've created your first commit! -You can see that the commit has given you some output about itself: which branch you committed to (`master`), what SHA-1 checksum the commit has (`463dc4f`), how many files were changed, and statistics about lines added and removed in the commit. +Agora você criou o seu primeiro commit! +Você pode ver que o commit forneceu a você algumas saídas sobre si mesmo: em qual branch você fez o commit (`master`), qual checksum SHA-1 o commit tem (`463dc4f`), quantos arquivos foram alterados e estatísticas sobre as linhas adicionadas e removidas no commit. -Remember that the commit records the snapshot you set up in your staging area. -Anything you didn't stage is still sitting there modified; you can do another commit to add it to your history. -Every time you perform a commit, you're recording a snapshot of your project that you can revert to or compare to later. +Lembre-se de que o commit registra o snapshot que você configurou na sua área de preparação. +Qualquer coisa que você não tenha preparado ainda está lá modificada; você pode fazer outro commit para adicioná-la ao seu histórico. +Toda vez que você realiza um commit, está registrando um snapshot do seu projeto para o qual você pode reverter ou comparar posteriormente. -==== Skipping the Staging Area +==== Ignorando a Área de Preparação (((staging area, skipping))) -Although it can be amazingly useful for crafting commits exactly how you want them, the staging area is sometimes a bit more complex than you need in your workflow. -If you want to skip the staging area, Git provides a simple shortcut. -Adding the `-a` option to the `git commit` command makes Git automatically stage every file that is already tracked before doing the commit, letting you skip the `git add` part: +Embora possa ser incrivelmente útil para criar commits exatamente da forma como você os deseja, a área de preparação às vezes é um pouco mais complexa do que você precisa em seu fluxo de trabalho. +Se você quiser pular a área de preparação, o Git fornece um atalho simples. +Adicionar a opção `-a` ao comando `git commit` faz com que o Git prepare automaticamente todos os arquivos que já estão sendo rastreados antes de fazer o commit, permitindo que você ignore a parte do `git add`: [source,console] ---- @@ -507,18 +507,18 @@ $ git commit -a -m 'Add new benchmarks' 1 file changed, 5 insertions(+), 0 deletions(-) ---- -Notice how you don't have to run `git add` on the `CONTRIBUTING.md` file in this case before you commit. -That's because the `-a` flag includes all changed files. -This is convenient, but be careful; sometimes this flag will cause you to include unwanted changes. +Observe como você não precisa executar `git add` no arquivo `CONTRIBUTING.md` neste caso antes de fazer o commit. +Isso ocorre porque a flag `-a` inclui todos os arquivos alterados. +Isso é conveniente, mas tenha cuidado; às vezes, essa flag fará com que você inclua alterações indesejadas. [[_removing_files]] -==== Removing Files +==== Removendo Arquivos (((files, removing))) -To remove a file from Git, you have to remove it from your tracked files (more accurately, remove it from your staging area) and then commit. -The `git rm` command does that, and also removes the file from your working directory so you don't see it as an untracked file the next time around. +Para remover um arquivo do Git, você deve removê-lo dos seus arquivos rastreados (mais precisamente, removê-lo da sua área de preparação) e, em seguida, fazer o commit. +O comando `git rm` faz isso e também remove o arquivo do seu diretório de trabalho para que você não o veja como um arquivo não rastreado na próxima vez. -If you simply remove the file from your working directory, it shows up under the "`Changes not staged for commit`" (that is, _unstaged_) area of your `git status` output: +Se você simplesmente remover o arquivo do seu diretório de trabalho, ele aparecerá na área "`Changes not staged for commit`" (ou seja, _não preparado_) da saída do seu `git status`: [source,console] ---- @@ -535,7 +535,7 @@ Changes not staged for commit: no changes added to commit (use "git add" and/or "git commit -a") ---- -Then, if you run `git rm`, it stages the file's removal: +Então, se você executar `git rm`, ele preparará a remoção do arquivo: [source,console] ---- @@ -550,58 +550,58 @@ Changes to be committed: deleted: PROJECTS.md ---- -The next time you commit, the file will be gone and no longer tracked. -If you modified the file or had already added it to the staging area, you must force the removal with the `-f` option. -This is a safety feature to prevent accidental removal of data that hasn't yet been recorded in a snapshot and that can't be recovered from Git. +Na próxima vez que você fizer commit, o arquivo não existirá mais e não será mais rastreado. +Se você modificou o arquivo ou já o adicionou à área de preparação, deve forçar a remoção com a opção `-f`. +Esse é um recurso de segurança para evitar a remoção acidental de dados que ainda não foram gravados em um snapshot e que não podem ser recuperados do Git. -Another useful thing you may want to do is to keep the file in your working tree but remove it from your staging area. -In other words, you may want to keep the file on your hard drive but not have Git track it anymore. -This is particularly useful if you forgot to add something to your `.gitignore` file and accidentally staged it, like a large log file or a bunch of `.a` compiled files. -To do this, use the `--cached` option: +Outra coisa útil que você pode querer fazer é manter o arquivo na sua árvore de trabalho, mas removê-lo da sua área de preparação. +Em outras palavras, você pode querer manter o arquivo no seu disco rígido, mas não ter mais o Git o rastreando. +Isso é particularmente útil se você esqueceu de adicionar algo ao seu arquivo `.gitignore` e acidentalmente o preparou, como um arquivo de log grande ou um monte de arquivos `.a` compilados. +Para fazer isso, use a opção `--cached`: [source,console] ---- $ git rm --cached README ---- -You can pass files, directories, and file-glob patterns to the `git rm` command. -That means you can do things such as: +Você pode passar arquivos, diretórios e padrões de file-glob para o comando `git rm`. +Isso significa que você pode fazer coisas como: [source,console] ---- $ git rm log/\*.log ---- -Note the backslash (`\`) in front of the `*`. -This is necessary because Git does its own filename expansion in addition to your shell's filename expansion. -This command removes all files that have the `.log` extension in the `log/` directory. -Or, you can do something like this: +Observe a barra invertida (`\`) na frente do `*`. +Isso é necessário porque o Git faz sua própria expansão de nome de arquivo, além da expansão de nome de arquivo do seu shell. +Esse comando remove todos os arquivos que têm a extensão `.log` no diretório `log/`. +Ou você pode fazer algo assim: [source,console] ---- $ git rm \*~ ---- -This command removes all files whose names end with a `~`. +Este comando remove todos os arquivos cujos nomes terminam com um `~`. [[_git_mv]] -==== Moving Files +==== Movendo Arquivos (((files, moving))) -Unlike many other VCSs, Git doesn't explicitly track file movement. -If you rename a file in Git, no metadata is stored in Git that tells it you renamed the file. -However, Git is pretty smart about figuring that out after the fact -- we'll deal with detecting file movement a bit later. +Ao contrário de muitos outros VCSs, o Git não rastreia explicitamente o movimento de arquivos. +Se você renomear um arquivo no Git, nenhum metadado será armazenado no Git que informe que você renomeou o arquivo. +No entanto, o Git é muito inteligente em descobrir isso depois do fato -- lidaremos com a detecção de movimento de arquivos um pouco mais tarde. -Thus it's a bit confusing that Git has a `mv` command. -If you want to rename a file in Git, you can run something like: +Portanto, é um pouco confuso que o Git tenha um comando `mv`. +Se você quiser renomear um arquivo no Git, você pode executar algo como: [source,console] ---- $ git mv file_from file_to ---- -and it works fine. -In fact, if you run something like this and look at the status, you'll see that Git considers it a renamed file: +e funciona perfeitamente. +De fato, se você executar algo assim e observar o status, verá que o Git o considera um arquivo renomeado: [source,console] ---- @@ -615,7 +615,7 @@ Changes to be committed: renamed: README.md -> README ---- -However, this is equivalent to running something like this: +No entanto, isso é equivalente a executar algo assim: [source,console] ---- @@ -624,6 +624,6 @@ $ git rm README.md $ git add README ---- -Git figures out that it's a rename implicitly, so it doesn't matter if you rename a file that way or with the `mv` command. -The only real difference is that `git mv` is one command instead of three -- it's a convenience function. -More importantly, you can use any tool you like to rename a file, and address the `add`/`rm` later, before you commit. +O Git descobre que é uma renomeação implicitamente, portanto, não importa se você renomeia um arquivo dessa maneira ou com o comando `mv`. +A única diferença real é que `git mv` é um comando em vez de três -- é uma função de conveniência. +Mais importante ainda, você pode usar qualquer ferramenta que desejar para renomear um arquivo e tratar o `add`/`rm` depois, antes de fazer o commit. diff --git a/book/02-git-basics/sections/remotes.asc b/book/02-git-basics/sections/remotes.asc index 80e98250..b0b84631 100644 --- a/book/02-git-basics/sections/remotes.asc +++ b/book/02-git-basics/sections/remotes.asc @@ -1,26 +1,26 @@ [[_remote_repos]] -=== Working with Remotes +=== Trabalhando com Repositórios Remotos -To be able to collaborate on any Git project, you need to know how to manage your remote repositories. -Remote repositories are versions of your project that are hosted on the Internet or network somewhere. -You can have several of them, each of which generally is either read-only or read/write for you. -Collaborating with others involves managing these remote repositories and pushing and pulling data to and from them when you need to share work. -Managing remote repositories includes knowing how to add remote repositories, remove remotes that are no longer valid, manage various remote branches and define them as being tracked or not, and more. -In this section, we'll cover some of these remote-management skills. +Para poder colaborar em qualquer projeto Git, você precisa saber como gerenciar seus repositórios remotos. +Repositórios remotos são versões do seu projeto que estão hospedadas na Internet ou em algum lugar da rede. +Você pode ter vários deles, cada um geralmente sendo somente leitura ou leitura/gravação para você. +Colaborar com outras pessoas envolve gerenciar esses repositórios remotos e enviar (push) e extrair (pull) dados de e para eles quando você precisa compartilhar o trabalho. +O gerenciamento de repositórios remotos inclui saber como adicionar repositórios remotos, remover remotos que não são mais válidos, gerenciar várias branches remotas e defini-las como sendo rastreadas (tracked) ou não e muito mais. +Nesta seção, abordaremos algumas dessas habilidades de gerenciamento de remotos. [NOTE] -.Remote repositories can be on your local machine. +.Repositórios remotos podem estar na sua máquina local. ==== -It is entirely possible that you can be working with a "`remote`" repository that is, in fact, on the same host you are. -The word "`remote`" does not necessarily imply that the repository is somewhere else on the network or Internet, only that it is elsewhere. -Working with such a remote repository would still involve all the standard pushing, pulling and fetching operations as with any other remote. +É inteiramente possível que você esteja trabalhando com um repositório "`remoto`" que, de fato, esteja no mesmo host que você. +A palavra "`remoto`" não implica necessariamente que o repositório esteja em outro lugar na rede ou na Internet, apenas que está em outro lugar. +Trabalhar com um repositório remoto assim ainda envolveria todas as operações padrão de push, pull e fetch, como em qualquer outro remoto. ==== -==== Showing Your Remotes +==== Mostrando seus Remotos -To see which remote servers you have configured, you can run the `git remote` command.(((git commands, remote))) -It lists the shortnames of each remote handle you've specified. -If you've cloned your repository, you should at least see `origin` -- that is the default name Git gives to the server you cloned from: +Para ver quais servidores remotos você configurou, você pode executar o comando `git remote`.(((git commands, remote))) +Ele lista os nomes curtos (shortnames) de cada handle remoto que você especificou. +Se você clonou seu repositório, você deve pelo menos ver `origin` -- esse é o nome padrão que o Git dá ao servidor do qual você clonou: [source,console] ---- @@ -36,7 +36,7 @@ $ git remote origin ---- -You can also specify `-v`, which shows you the URLs that Git has stored for the shortname to be used when reading and writing to that remote: +Você também pode especificar `-v`, que mostra as URLs que o Git armazenou para o nome curto (shortname) a ser usado ao ler e gravar nesse remoto: [source,console] ---- @@ -45,8 +45,8 @@ origin https://github.com/schacon/ticgit (fetch) origin https://github.com/schacon/ticgit (push) ---- -If you have more than one remote, the command lists them all. -For example, a repository with multiple remotes for working with several collaborators might look something like this. +Se você tiver mais de um remoto, o comando lista todos eles. +Por exemplo, um repositório com vários remotos para trabalhar com vários colaboradores pode ser parecido com isto. [source,console] ---- @@ -64,16 +64,16 @@ origin git@github.com:mojombo/grit.git (fetch) origin git@github.com:mojombo/grit.git (push) ---- -This means we can pull contributions from any of these users pretty easily. -We may additionally have permission to push to one or more of these, though we can't tell that here. +Isso significa que podemos extrair (pull) contribuições de qualquer um desses usuários com bastante facilidade. +Adicionalmente, podemos ter permissão para enviar (push) para um ou mais deles, embora não possamos dizer isso aqui. -Notice that these remotes use a variety of protocols; we'll cover more about this in <>. +Observe que esses remotos usam uma variedade de protocolos; cobriremos mais sobre isso em <>. -==== Adding Remote Repositories +==== Adicionando Repositórios Remotos -We've mentioned and given some demonstrations of how the `git clone` command implicitly adds the `origin` remote for you. -Here's how to add a new remote explicitly.(((git commands, remote))) -To add a new remote Git repository as a shortname you can reference easily, run `git remote add `: +Mencionamos e demonstramos como o comando `git clone` adiciona implicitamente o remoto `origin` para você. +Veja como adicionar um novo remoto explicitamente.(((git commands, remote))) +Para adicionar um novo repositório Git remoto como um nome curto (shortname) que você pode referenciar facilmente, execute `git remote add `: [source,console] ---- @@ -87,8 +87,8 @@ pb https://github.com/paulboone/ticgit (fetch) pb https://github.com/paulboone/ticgit (push) ---- -Now you can use the string `pb` on the command line instead of the whole URL. -For example, if you want to fetch all the information that Paul has but that you don't yet have in your repository, you can run `git fetch pb`: +Agora você pode usar a string `pb` na linha de comando em vez da URL inteira. +Por exemplo, se você quiser buscar (fetch) todas as informações que Paul tem, mas que você ainda não tem em seu repositório, você pode executar `git fetch pb`: [source,console] ---- @@ -102,65 +102,65 @@ From https://github.com/paulboone/ticgit * [new branch] ticgit -> pb/ticgit ---- -Paul's `master` branch is now accessible locally as `pb/master` -- you can merge it into one of your branches, or you can check out a local branch at that point if you want to inspect it. -We'll go over what branches are and how to use them in much more detail in <>. +O branch `master` de Paul agora está acessível localmente como `pb/master` -- você pode mesclá-lo (merge) em um dos seus branches, ou você pode fazer checkout em um branch local naquele ponto se quiser inspecioná-lo. +Veremos o que são branches e como usá-los com muito mais detalhes em <>. [[_fetching_and_pulling]] -==== Fetching and Pulling from Your Remotes +==== Buscando (fetching) e Extraindo (pulling) de Seus Remotos -As you just saw, to get data from your remote projects, you can run:(((git commands, fetch))) +Como você acabou de ver, para obter dados de seus projetos remotos, você pode executar:(((git commands, fetch))) [source,console] ---- $ git fetch ---- -The command goes out to that remote project and pulls down all the data from that remote project that you don't have yet. -After you do this, you should have references to all the branches from that remote, which you can merge in or inspect at any time. +O comando vai para aquele projeto remoto e puxa (pulls down) todos os dados daquele projeto remoto que você ainda não tem. +Depois de fazer isso, você deve ter referências para todos os branches daquele remoto, os quais você pode mesclar (merge) ou inspecionar a qualquer momento. -If you clone a repository, the command automatically adds that remote repository under the name "`origin`". -So, `git fetch origin` fetches any new work that has been pushed to that server since you cloned (or last fetched from) it. -It's important to note that the `git fetch` command only downloads the data to your local repository -- it doesn't automatically merge it with any of your work or modify what you're currently working on. -You have to merge it manually into your work when you're ready. +Se você clonar um repositório, o comando adicionará automaticamente esse repositório remoto com o nome "`origin`". +Portanto, `git fetch origin` busca (fetches) qualquer trabalho novo que tenha sido enviado (pushed) para aquele servidor desde que você o clonou (ou buscou dele pela última vez). +É importante observar que o comando `git fetch` apenas baixa os dados para o seu repositório local -- ele não os mescla (merge) automaticamente com nenhum de seus trabalhos, nem modifica o que você está trabalhando no momento. +Você deve mesclá-lo manualmente em seu trabalho quando estiver pronto. -If your current branch is set up to track a remote branch (see the next section and <> for more information), you can use the `git pull` command to automatically fetch and then merge that remote branch into your current branch.(((git commands, pull))) -This may be an easier or more comfortable workflow for you; and by default, the `git clone` command automatically sets up your local `master` branch to track the remote `master` branch (or whatever the default branch is called) on the server you cloned from. -Running `git pull` generally fetches data from the server you originally cloned from and automatically tries to merge it into the code you're currently working on. +Se o seu branch atual estiver configurado para rastrear um branch remoto (consulte a próxima seção e <> para obter mais informações), você poderá usar o comando `git pull` para buscar (fetch) e, em seguida, mesclar (merge) automaticamente aquele branch remoto em seu branch atual.(((git commands, pull))) +Esse pode ser um fluxo de trabalho mais fácil ou mais confortável para você; e, por padrão, o comando `git clone` configura automaticamente seu branch `master` local para rastrear o branch `master` remoto (ou qualquer que seja o nome do branch padrão) no servidor de onde você clonou. +A execução do `git pull` geralmente busca (fetches) dados do servidor do qual você clonou originalmente e tenta mesclá-los (merge) automaticamente no código em que você está trabalhando no momento. [NOTE] ==== -From Git version 2.27 onward, `git pull` will give a warning if the `pull.rebase` variable is not set. -Git will keep warning you until you set the variable. +A partir do Git versão 2.27, o `git pull` emitirá um aviso se a variável `pull.rebase` não estiver definida. +O Git continuará avisando você até que você defina a variável. -If you want the default behavior of Git (fast-forward if possible, else create a merge commit): +Se você quiser o comportamento padrão do Git (fast-forward se possível, caso contrário crie um commit de mesclagem (merge commit)): `git config --global pull.rebase "false"` -If you want to rebase when pulling: +Se você quiser fazer rebase ao extrair (pulling): `git config --global pull.rebase "true"` ==== [[_pushing_remotes]] -==== Pushing to Your Remotes +==== Enviando (pushing) para seus Remotos -When you have your project at a point that you want to share, you have to push it upstream. -The command for this is simple: `git push `.(((git commands, push))) -If you want to push your `master` branch to your `origin` server (again, cloning generally sets up both of those names for you automatically), then you can run this to push any commits you've done back up to the server: +Quando você tiver seu projeto em um ponto que deseja compartilhar, você deve enviá-lo (push) para upstream. +O comando para isso é simples: `git push `.(((git commands, push))) +Se você quiser enviar (push) seu branch `master` para o seu servidor `origin` (novamente, a clonagem geralmente configura ambos os nomes para você automaticamente), você pode executar isso para enviar todos os commits que você fez de volta para o servidor: [source,console] ---- $ git push origin master ---- -This command works only if you cloned from a server to which you have write access and if nobody has pushed in the meantime. -If you and someone else clone at the same time and they push upstream and then you push upstream, your push will rightly be rejected. -You'll have to fetch their work first and incorporate it into yours before you'll be allowed to push. -See <> for more detailed information on how to push to remote servers. +Este comando funciona apenas se você clonou de um servidor no qual você tem acesso de gravação e se ninguém fez o push nesse meio tempo. +Se você e outra pessoa clonarem ao mesmo tempo, e ela enviar (push) para upstream e depois você enviar (push) para upstream, o seu push será corretamente rejeitado. +Você terá que buscar (fetch) o trabalho deles primeiro e incorporá-lo ao seu antes de ter permissão para fazer o push. +Consulte <> para obter informações mais detalhadas sobre como fazer push para servidores remotos. [[_inspecting_remote]] -==== Inspecting a Remote +==== Inspecionando um Remoto -If you want to see more information about a particular remote, you can use the `git remote show ` command.(((git commands, remote))) -If you run this command with a particular shortname, such as `origin`, you get something like this: +Se você quiser ver mais informações sobre um remoto específico, você pode usar o comando `git remote show `.(((git commands, remote))) +Se você executar este comando com um nome curto (shortname) específico, como `origin`, você obterá algo assim: [source,console] ---- @@ -178,12 +178,12 @@ $ git remote show origin master pushes to master (up to date) ---- -It lists the URL for the remote repository as well as the tracking branch information. -The command helpfully tells you that if you're on the `master` branch and you run `git pull`, it will automatically merge the remote's `master` branch into the local one after it has been fetched. -It also lists all the remote references it has pulled down. +Ele lista a URL para o repositório remoto, bem como as informações do branch de rastreamento (tracking branch). +O comando informa utilmente que se você estiver no branch `master` e executar `git pull`, ele mesclará (merge) automaticamente o branch `master` do remoto no local depois de ser buscado (fetched). +Ele também lista todas as referências remotas que puxou (pulled down). -That is a simple example you're likely to encounter. -When you're using Git more heavily, however, you may see much more information from `git remote show`: +Esse é um exemplo simples que você provavelmente encontrará. +Quando você estiver usando o Git de forma mais intensa, no entanto, poderá ver muito mais informações do `git remote show`: [source,console] ---- @@ -209,13 +209,13 @@ $ git remote show origin master pushes to master (up to date) ---- -This command shows which branch is automatically pushed to when you run `git push` while on certain branches. -It also shows you which remote branches on the server you don't yet have, which remote branches you have that have been removed from the server, and multiple local branches that are able to merge automatically with their remote-tracking branch when you run `git pull`. +Este comando mostra para qual branch o envio é feito automaticamente quando você executa `git push` enquanto está em certos branches. +Ele também mostra quais branches remotos no servidor você ainda não tem, quais branches remotos você tem que foram removidos do servidor e vários branches locais que podem ser mesclados automaticamente com seus branches de rastreamento remotos (remote-tracking branch) quando você executa `git pull`. -==== Renaming and Removing Remotes +==== Renomeando e Removendo Remotos -You can run `git remote rename` to change a remote's shortname.(((git commands, remote))) -For instance, if you want to rename `pb` to `paul`, you can do so with `git remote rename`: +Você pode executar `git remote rename` para alterar o nome curto (shortname) de um remoto.(((git commands, remote))) +Por exemplo, se você quiser renomear `pb` para `paul`, você pode fazê-lo com `git remote rename`: [source,console] ---- @@ -225,10 +225,10 @@ origin paul ---- -It's worth mentioning that this changes all your remote-tracking branch names, too. -What used to be referenced at `pb/master` is now at `paul/master`. +Vale a pena mencionar que isso também altera todos os nomes dos seus branches de rastreamento remoto (remote-tracking branch). +O que costumava ser referenciado em `pb/master` agora está em `paul/master`. -If you want to remove a remote for some reason -- you've moved the server or are no longer using a particular mirror, or perhaps a contributor isn't contributing anymore -- you can either use `git remote remove` or `git remote rm`: +Se você quiser remover um remoto por algum motivo -- você mudou de servidor ou não está mais usando um espelho (mirror) específico, ou talvez um colaborador não esteja mais contribuindo -- você pode usar `git remote remove` ou `git remote rm`: [source,console] ---- @@ -237,4 +237,4 @@ $ git remote origin ---- -Once you delete the reference to a remote this way, all remote-tracking branches and configuration settings associated with that remote are also deleted. +Depois de excluir a referência a um remoto dessa maneira, todos os branches de rastreamento remoto (remote-tracking branches) e definições de configuração associados a esse remoto também serão excluídos. diff --git a/book/02-git-basics/sections/tagging.asc b/book/02-git-basics/sections/tagging.asc index 34604c57..cc5cb166 100644 --- a/book/02-git-basics/sections/tagging.asc +++ b/book/02-git-basics/sections/tagging.asc @@ -1,15 +1,15 @@ [[_git_tagging]] -=== Tagging +=== Criando Tags (((tags))) -Like most VCSs, Git has the ability to tag specific points in a repository's history as being important. -Typically, people use this functionality to mark release points (`v1.0`, `v2.0` and so on). -In this section, you'll learn how to list existing tags, how to create and delete tags, and what the different types of tags are. +Como a maioria dos VCSs, o Git tem a capacidade de marcar (tag) pontos específicos no histórico de um repositório como sendo importantes. +Normalmente, as pessoas usam essa funcionalidade para marcar pontos de lançamento (`v1.0`, `v2.0` e assim por diante). +Nesta seção, você aprenderá como listar as tags existentes, como criar e excluir tags, e quais são os diferentes tipos de tags. -==== Listing Your Tags +==== Listando Suas Tags -Listing the existing tags in Git is straightforward. -Just type `git tag` (with optional `-l` or `--list`):(((git commands, tag))) +Listar as tags existentes no Git é simples. +Basta digitar `git tag` (com o opcional `-l` ou `--list`):(((git commands, tag))) [source,console] ---- @@ -18,11 +18,11 @@ v1.0 v2.0 ---- -This command lists the tags in alphabetical order; the order in which they are displayed has no real importance. +Este comando lista as tags em ordem alfabética; a ordem na qual elas são exibidas não tem importância real. -You can also search for tags that match a particular pattern. -The Git source repo, for instance, contains more than 500 tags. -If you're interested only in looking at the 1.8.5 series, you can run this: +Você também pode pesquisar tags que correspondam a um padrão específico. +O repositório de código-fonte do Git, por exemplo, contém mais de 500 tags. +Se você estiver interessado apenas em observar a série 1.8.5, você pode executar isto: [source,console] ---- @@ -40,29 +40,29 @@ v1.8.5.5 ---- [NOTE] -.Listing tag wildcards requires `-l` or `--list` option +.A listagem de curingas (wildcards) de tags requer a opção `-l` ou `--list` ==== -If you want just the entire list of tags, running the command `git tag` implicitly assumes you want a listing and provides one; the use of `-l` or `--list` in this case is optional. +Se você quiser apenas a lista inteira de tags, executar o comando `git tag` assume implicitamente que você deseja uma lista e fornece uma; o uso de `-l` ou `--list` neste caso é opcional. -If, however, you're supplying a wildcard pattern to match tag names, the use of `-l` or `--list` is mandatory. +Se, no entanto, você estiver fornecendo um padrão curinga (wildcard) para corresponder a nomes de tags, o uso de `-l` ou `--list` é obrigatório. ==== -==== Creating Tags +==== Criando Tags -Git supports two types of tags: _lightweight_ and _annotated_. +O Git suporta dois tipos de tags: _leves (lightweight)_ e _anotadas (annotated)_. -A lightweight tag is very much like a branch that doesn't change -- it's just a pointer to a specific commit. +Uma tag leve (lightweight tag) é muito parecida com um branch que não muda -- é apenas um ponteiro para um commit específico. -Annotated tags, however, are stored as full objects in the Git database. -They're checksummed; contain the tagger name, email, and date; have a tagging message; and can be signed and verified with GNU Privacy Guard (GPG). -It's generally recommended that you create annotated tags so you can have all this information; but if you want a temporary tag or for some reason don't want to keep the other information, lightweight tags are available too. +As tags anotadas (annotated tags), no entanto, são armazenadas como objetos completos no banco de dados do Git. +Elas têm checksum; contêm o nome do criador da tag (tagger), e-mail e data; possuem uma mensagem de tag; e podem ser assinadas e verificadas com o GNU Privacy Guard (GPG). +Geralmente é recomendado que você crie tags anotadas para que possa ter todas essas informações; mas se você quiser uma tag temporária ou, por algum motivo, não quiser manter as outras informações, as tags leves também estão disponíveis. [[_annotated_tags]] -==== Annotated Tags +==== Tags Anotadas (Annotated Tags) (((tags, annotated))) -Creating an annotated tag in Git is simple. -The easiest way is to specify `-a` when you run the `tag` command:(((git commands, tag))) +Criar uma tag anotada no Git é simples. +A maneira mais fácil é especificar `-a` quando você executar o comando `tag`:(((git commands, tag))) [source,console] ---- @@ -73,10 +73,10 @@ v1.3 v1.4 ---- -The `-m` specifies a tagging message, which is stored with the tag. -If you don't specify a message for an annotated tag, Git launches your editor so you can type it in. +O `-m` especifica uma mensagem de tag, que é armazenada junto com ela. +Se você não especificar uma mensagem para uma tag anotada, o Git iniciará o seu editor para que você possa digitá-la. -You can see the tag data along with the commit that was tagged by using the `git show` command: +Você pode ver os dados da tag junto com o commit que foi tagueado usando o comando `git show`: [source,console] ---- @@ -94,14 +94,14 @@ Date: Mon Mar 17 21:52:11 2008 -0700 Change version number ---- -That shows the tagger information, the date the commit was tagged, and the annotation message before showing the commit information. +Isso mostra as informações de quem criou a tag (tagger), a data em que o commit foi tagueado e a mensagem de anotação antes de mostrar as informações do commit. -==== Lightweight Tags +==== Tags Leves (Lightweight Tags) (((tags, lightweight))) -Another way to tag commits is with a lightweight tag. -This is basically the commit checksum stored in a file -- no other information is kept. -To create a lightweight tag, don't supply any of the `-a`, `-s`, or `-m` options, just provide a tag name: +Outra forma de taguear commits é com uma tag leve (lightweight tag). +Isso é basicamente o checksum do commit armazenado em um arquivo -- nenhuma outra informação é mantida. +Para criar uma tag leve, não forneça nenhuma das opções `-a`, `-s` ou `-m`, forneça apenas o nome da tag: [source,console] ---- @@ -114,8 +114,8 @@ v1.4-lw v1.5 ---- -This time, if you run `git show` on the tag, you don't see the extra tag information.(((git commands, show))) -The command just shows the commit: +Desta vez, se você executar `git show` na tag, você não verá as informações extras da tag.(((git commands, show))) +O comando apenas mostra o commit: [source,console] ---- @@ -127,10 +127,10 @@ Date: Mon Mar 17 21:52:11 2008 -0700 Change version number ---- -==== Tagging Later +==== Tagueando Depois -You can also tag commits after you've moved past them. -Suppose your commit history looks like this: +Você também pode taguear commits depois de ter passado por eles. +Suponha que o seu histórico de commits seja parecido com este: [source,console] ---- @@ -147,16 +147,16 @@ a6b4c97498bd301d84096da251c98a07c7723e65 Create write support 8a5cbc430f1a9c3d00faaeffd07798508422908a Update readme ---- -Now, suppose you forgot to tag the project at v1.2, which was at the "`Update rakefile`" commit. -You can add it after the fact. -To tag that commit, you specify the commit checksum (or part of it) at the end of the command: +Agora, suponha que você esqueceu de taguear o projeto na v1.2, que estava no commit "`Update rakefile`". +Você pode adicioná-la depois do fato. +Para taguear aquele commit, você especifica o checksum do commit (ou parte dele) no final do comando: [source,console] ---- $ git tag -a v1.2 9fceb02 ---- -You can see that you've tagged the commit:(((git commands, tag))) +Você pode ver que tagueou o commit:(((git commands, tag))) [source,console] ---- @@ -183,11 +183,11 @@ Date: Sun Apr 27 20:43:35 2008 -0700 ---- [[_sharing_tags]] -==== Sharing Tags +==== Compartilhando Tags -By default, the `git push` command doesn't transfer tags to remote servers.(((git commands, push))) -You will have to explicitly push tags to a shared server after you have created them. -This process is just like sharing remote branches -- you can run `git push origin `. +Por padrão, o comando `git push` não transfere tags para servidores remotos.(((git commands, push))) +Você terá que enviar (push) as tags explicitamente para um servidor compartilhado depois de tê-las criado. +Esse processo é igual a compartilhar branches remotos -- você pode executar `git push origin `. [source,console] ---- @@ -201,8 +201,8 @@ To git@github.com:schacon/simplegit.git * [new tag] v1.5 -> v1.5 ---- -If you have a lot of tags that you want to push up at once, you can also use the `--tags` option to the `git push` command. -This will transfer all of your tags to the remote server that are not already there. +Se você tiver muitas tags que deseja enviar (push) de uma só vez, também poderá usar a opção `--tags` do comando `git push`. +Isso transferirá todas as suas tags para o servidor remoto que ainda não estão lá. [source,console] ---- @@ -215,19 +215,19 @@ To git@github.com:schacon/simplegit.git * [new tag] v1.4-lw -> v1.4-lw ---- -Now, when someone else clones or pulls from your repository, they will get all your tags as well. +Agora, quando outra pessoa clonar ou extrair (pull) do seu repositório, ela também obterá todas as suas tags. [NOTE] -.`git push` pushes both types of tags +.`git push` envia ambos os tipos de tags ==== -`git push --tags` will push both lightweight and annotated tags. -There is currently no option to push only lightweight tags, but if you use `git push --follow-tags` only annotated tags will be pushed to the remote. +`git push --tags` enviará tags leves e anotadas. +No momento, não há opção para enviar apenas tags leves, mas se você usar `git push --follow-tags` apenas as tags anotadas serão enviadas para o remoto. ==== -==== Deleting Tags +==== Excluindo Tags -To delete a tag on your local repository, you can use `git tag -d `. -For example, we could remove our lightweight tag above as follows: +Para excluir uma tag no seu repositório local, você pode usar `git tag -d `. +Por exemplo, poderíamos remover a nossa tag leve acima da seguinte maneira: [source,console] ---- @@ -235,10 +235,10 @@ $ git tag -d v1.4-lw Deleted tag 'v1.4-lw' (was e7d5add) ---- -Note that this does not remove the tag from any remote servers. -There are two common variations for deleting a tag from a remote server. +Observe que isso não remove a tag de nenhum servidor remoto. +Existem duas variações comuns para excluir uma tag de um servidor remoto. -The first variation is `git push :refs/tags/`: +A primeira variação é `git push :refs/tags/`: [source,console] ---- @@ -247,18 +247,18 @@ To /git@github.com:schacon/simplegit.git - [deleted] v1.4-lw ---- -The way to interpret the above is to read it as the null value before the colon is being pushed to the remote tag name, effectively deleting it. +A maneira de interpretar o comando acima é lê-lo como o valor nulo antes dos dois pontos (colon) sendo enviado para o nome da tag remota, efetivamente excluindo-a. -The second (and more intuitive) way to delete a remote tag is with: +A segunda (e mais intuitiva) maneira de excluir uma tag remota é com: [source,console] ---- $ git push origin --delete ---- -==== Checking out Tags +==== Fazendo Checkout de Tags -If you want to view the versions of files a tag is pointing to, you can do a `git checkout` of that tag, although this puts your repository in "`detached HEAD`" state, which has some ill side effects: +Se você quiser ver as versões dos arquivos para as quais uma tag está apontando, você pode fazer um `git checkout` daquela tag, embora isso coloque seu repositório no estado "`detached HEAD`", o que tem alguns efeitos colaterais ruins: [source,console] ---- @@ -287,8 +287,8 @@ Previous HEAD position was 99ada87... Merge pull request #89 from schacon/append HEAD is now at df3f601... Add atlas.json and cover image ---- -In "`detached HEAD`" state, if you make changes and then create a commit, the tag will stay the same, but your new commit won't belong to any branch and will be unreachable, except by the exact commit hash. -Thus, if you need to make changes -- say you're fixing a bug on an older version, for instance -- you will generally want to create a branch: +No estado "`detached HEAD`", se você fizer alterações e então criar um commit, a tag permanecerá a mesma, mas seu novo commit não pertencerá a nenhum branch e ficará inacessível, exceto pelo hash exato do commit. +Portanto, se você precisar fazer alterações -- digamos que esteja corrigindo um bug em uma versão mais antiga, por exemplo -- geralmente você desejará criar um branch: [source,console] ---- @@ -296,4 +296,4 @@ $ git checkout -b version2 v2.0.0 Switched to a new branch 'version2' ---- -If you do this and make a commit, your `version2` branch will be slightly different than your `v2.0.0` tag since it will move forward with your new changes, so do be careful. +Se você fizer isso e criar um commit, seu branch `version2` será ligeiramente diferente da sua tag `v2.0.0`, pois ele avançará com as suas novas alterações, portanto tenha cuidado. diff --git a/book/02-git-basics/sections/undoing.asc b/book/02-git-basics/sections/undoing.asc index 0c815dde..9032b02c 100644 --- a/book/02-git-basics/sections/undoing.asc +++ b/book/02-git-basics/sections/undoing.asc @@ -1,26 +1,26 @@ [[_undoing]] -=== Undoing Things +=== Desfazendo Coisas -At any stage, you may want to undo something. -Here, we'll review a few basic tools for undoing changes that you've made. -Be careful, because you can't always undo some of these undos. -This is one of the few areas in Git where you may lose some work if you do it wrong. +Em qualquer estágio, você pode querer desfazer algo. +Aqui, revisaremos algumas ferramentas básicas para desfazer alterações que você fez. +Tenha cuidado, pois você nem sempre pode desfazer alguns desses desfazimentos. +Esta é uma das poucas áreas no Git onde você pode perder algum trabalho se fizer de forma incorreta. -One of the common undos takes place when you commit too early and possibly forget to add some files, or you mess up your commit message. -If you want to redo that commit, make the additional changes you forgot, stage them, and commit again using the `--amend` option: +Um dos desfazimentos comuns ocorre quando você faz o commit muito cedo e possivelmente se esquece de adicionar alguns arquivos, ou você bagunça sua mensagem de commit. +Se você quiser refazer esse commit, faça as alterações adicionais que esqueceu, prepare-as e faça o commit novamente usando a opção `--amend`: [source,console] ---- $ git commit --amend ---- -This command takes your staging area and uses it for the commit. -If you've made no changes since your last commit (for instance, you run this command immediately after your previous commit), then your snapshot will look exactly the same, and all you'll change is your commit message. +Este comando pega sua área de preparação e a utiliza para o commit. +Se você não fez nenhuma alteração desde o seu último commit (por exemplo, você executa este comando imediatamente após o commit anterior), então o seu snapshot ficará exatamente o mesmo e tudo o que você alterará será a sua mensagem de commit. -The same commit-message editor fires up, but it already contains the message of your previous commit. -You can edit the message the same as always, but it overwrites your previous commit. +O mesmo editor de mensagem de commit é iniciado, mas já contém a mensagem do seu commit anterior. +Você pode editar a mensagem da mesma forma de sempre, mas ela substitui (overwrites) seu commit anterior. -As an example, if you commit and then realize you forgot to stage the changes in a file you wanted to add to this commit, you can do something like this: +Como exemplo, se você fizer o commit e, em seguida, perceber que se esqueceu de preparar as alterações em um arquivo que queria adicionar a este commit, você pode fazer algo assim: [source,console] ---- @@ -29,31 +29,31 @@ $ git add forgotten_file $ git commit --amend ---- -You end up with a single commit -- the second commit replaces the results of the first. +Você acaba com um único commit -- o segundo commit substitui os resultados do primeiro. [NOTE] ==== -It's important to understand that when you're amending your last commit, you're not so much fixing it as _replacing_ it entirely with a new, improved commit that pushes the old commit out of the way and puts the new commit in its place. -Effectively, it's as if the previous commit never happened, and it won't show up in your repository history. +É importante entender que quando você está alterando (amending) seu último commit, você não está tanto corrigindo-o, mas _substituindo-o_ inteiramente por um novo e melhorado commit que empurra o antigo commit para fora do caminho e coloca o novo commit em seu lugar. +Efetivamente, é como se o commit anterior nunca tivesse acontecido, e ele não aparecerá no histórico do seu repositório. -The obvious value to amending commits is to make minor improvements to your last commit, without cluttering your repository history with commit messages of the form, "`Oops, forgot to add a file`" or "`Darn, fixing a typo in last commit`". +O valor óbvio de alterar (amending) commits é fazer pequenas melhorias em seu último commit, sem sobrecarregar o histórico do seu repositório com mensagens de commit na forma, "`Ops, esqueci de adicionar um arquivo`" ou "`Droga, corrigindo erro de digitação no último commit`". ==== [NOTE] ==== -Only amend commits that are still local and have not been pushed somewhere. -Amending previously pushed commits and force pushing the branch will cause problems for your collaborators. -For more on what happens when you do this and how to recover if you're on the receiving end read <<_rebase_peril>>. +Altere apenas commits que ainda são locais e não foram enviados (pushed) para algum lugar. +Alterar commits enviados anteriormente e forçar o push do branch causará problemas para seus colaboradores. +Para saber mais sobre o que acontece quando você faz isso e como se recuperar se estiver do lado do destinatário, leia <<_rebase_peril>>. ==== [[_unstaging]] -==== Unstaging a Staged File +==== Retirando a Preparação de um Arquivo Preparado (Unstaging) -The next two sections demonstrate how to work with your staging area and working directory changes. -The nice part is that the command you use to determine the state of those two areas also reminds you how to undo changes to them. -For example, let's say you've changed two files and want to commit them as two separate changes, but you accidentally type `git add *` and stage them both. -How can you unstage one of the two? -The `git status` command reminds you: +As próximas duas seções demonstram como trabalhar com a sua área de preparação e com as alterações do diretório de trabalho. +A parte boa é que o comando que você usa para determinar o estado dessas duas áreas também o lembra de como desfazer alterações nelas. +Por exemplo, digamos que você alterou dois arquivos e quer fazer o commit deles como duas alterações separadas, mas você acidentalmente digitou `git add *` e preparou ambos. +Como você pode retirar a preparação de (unstage) um dos dois? +O comando `git status` o lembra: [source,console] ---- @@ -67,8 +67,8 @@ Changes to be committed: modified: CONTRIBUTING.md ---- -Right below the "`Changes to be committed`" text, it says use `git reset HEAD ...` to unstage. -So, let's use that advice to unstage the `CONTRIBUTING.md` file: +Logo abaixo do texto "`Changes to be committed`", ele diz para usar `git reset HEAD ...` para retirar a preparação (unstage). +Então, vamos usar esse conselho para retirar a preparação do arquivo `CONTRIBUTING.md`: [source,console] ---- @@ -89,24 +89,24 @@ Changes not staged for commit: modified: CONTRIBUTING.md ---- -The command is a bit strange, but it works. -The `CONTRIBUTING.md` file is modified but once again unstaged. +O comando é um pouco estranho, mas funciona. +O arquivo `CONTRIBUTING.md` está modificado, mas mais uma vez não preparado (unstaged). [NOTE] ===== -It's true that `git reset` can be a dangerous command, especially if you provide the `--hard` flag. -However, in the scenario described above, the file in your working directory is not touched, so it's relatively safe. +É verdade que `git reset` pode ser um comando perigoso, especialmente se você fornecer a flag `--hard`. +No entanto, no cenário descrito acima, o arquivo no seu diretório de trabalho não é tocado, então é relativamente seguro. ===== -For now this magic invocation is all you need to know about the `git reset` command. -We'll go into much more detail about what `reset` does and how to master it to do really interesting things in <>. +Por enquanto, essa invocação mágica é tudo o que você precisa saber sobre o comando `git reset`. +Entraremos em muito mais detalhes sobre o que o `reset` faz e como dominá-lo para fazer coisas realmente interessantes em <>. -==== Unmodifying a Modified File +==== Desfazendo a Modificação de um Arquivo Modificado -What if you realize that you don't want to keep your changes to the `CONTRIBUTING.md` file? -How can you easily unmodify it -- revert it back to what it looked like when you last committed (or initially cloned, or however you got it into your working directory)? -Luckily, `git status` tells you how to do that, too. -In the last example output, the unstaged area looks like this: +E se você perceber que não deseja manter as alterações feitas no arquivo `CONTRIBUTING.md`? +Como você pode desfazer as modificações facilmente -- revertê-lo para a aparência que tinha da última vez em que fez o commit (ou clonou inicialmente, ou como quer que tenha chegado ao seu diretório de trabalho)? +Felizmente, o `git status` também diz como fazer isso. +Na saída do último exemplo, a área não preparada se parece com isto: [source,console] ---- @@ -117,8 +117,8 @@ Changes not staged for commit: modified: CONTRIBUTING.md ---- -It tells you pretty explicitly how to discard the changes you've made. -Let's do what it says: +Ele diz explicitamente como descartar as alterações feitas. +Vamos fazer o que ele diz: [source,console] ---- @@ -132,37 +132,37 @@ Changes to be committed: ---- -You can see that the changes have been reverted. +Você pode ver que as alterações foram revertidas. [IMPORTANT] ===== -It's important to understand that `git checkout \-- ` is a dangerous command. -Any local changes you made to that file are gone -- Git just replaced that file with the last staged or committed version. -Don't ever use this command unless you absolutely know that you don't want those unsaved local changes. +É importante entender que `git checkout \-- ` é um comando perigoso. +Quaisquer alterações locais feitas nesse arquivo são perdidas -- o Git simplesmente substituiu aquele arquivo pela última versão preparada ou commitada. +Nunca use esse comando a menos que você saiba com certeza absoluta que não deseja essas alterações locais não salvas. ===== -If you would like to keep the changes you've made to that file but still need to get it out of the way for now, we'll go over stashing and branching in <>; these are generally better ways to go. +Se você gostaria de manter as alterações feitas nesse arquivo, mas ainda precisa tirá-lo do caminho por enquanto, abordaremos as opções de stashing e branching no <>; essas são geralmente maneiras melhores de prosseguir. -Remember, anything that is _committed_ in Git can almost always be recovered. -Even commits that were on branches that were deleted or commits that were overwritten with an `--amend` commit can be recovered (see <> for data recovery). -However, anything you lose that was never committed is likely never to be seen again. +Lembre-se, qualquer coisa que seja _commitada_ no Git quase sempre pode ser recuperada. +Até mesmo commits que estavam em branches que foram excluídos ou commits que foram sobrescritos com um commit `--amend` podem ser recuperados (consulte <> para recuperação de dados). +No entanto, qualquer coisa que você perca e que nunca tenha sido commitada provavelmente nunca mais será vista. [[undoing_git_restore]] -==== Undoing things with git restore +==== Desfazendo coisas com git restore -Git version 2.23.0 introduced a new command: `git restore`. -It's basically an alternative to `git reset` which we just covered. -From Git version 2.23.0 onwards, Git will use `git restore` instead of `git reset` for many undo operations. +O Git versão 2.23.0 introduziu um novo comando: `git restore`. +É basicamente uma alternativa ao `git reset` que acabamos de abordar. +A partir do Git versão 2.23.0, o Git usará `git restore` em vez de `git reset` para muitas operações de desfazer. -Let's retrace our steps, and undo things with `git restore` instead of `git reset`. +Vamos refazer nossos passos e desfazer as coisas com `git restore` em vez de `git reset`. -===== Unstaging a Staged File with git restore +===== Retirando a Preparação de um Arquivo Preparado com git restore -The next two sections demonstrate how to work with your staging area and working directory changes with `git restore`. -The nice part is that the command you use to determine the state of those two areas also reminds you how to undo changes to them. -For example, let's say you've changed two files and want to commit them as two separate changes, but you accidentally type `git add *` and stage them both. -How can you unstage one of the two? -The `git status` command reminds you: +As próximas duas seções demonstram como trabalhar com a sua área de preparação e as alterações do diretório de trabalho com `git restore`. +A parte boa é que o comando que você usa para determinar o estado dessas duas áreas também o lembra de como desfazer alterações nelas. +Por exemplo, digamos que você alterou dois arquivos e quer fazer o commit deles como duas alterações separadas, mas você acidentalmente digitou `git add *` e preparou ambos. +Como você pode retirar a preparação de (unstage) um dos dois? +O comando `git status` o lembra: [source,console] ---- @@ -176,8 +176,8 @@ Changes to be committed: ---- -Right below the "`Changes to be committed`" text, it says use `git restore --staged ...` to unstage. -So, let's use that advice to unstage the `CONTRIBUTING.md` file: +Logo abaixo do texto "`Changes to be committed`", ele diz para usar `git restore --staged ...` para retirar a preparação (unstage). +Então, vamos usar esse conselho para retirar a preparação do arquivo `CONTRIBUTING.md`: [source,console] ---- @@ -195,14 +195,14 @@ Changes not staged for commit: ---- -The `CONTRIBUTING.md` file is modified but once again unstaged. +O arquivo `CONTRIBUTING.md` está modificado, mas mais uma vez não preparado (unstaged). -===== Unmodifying a Modified File with git restore +===== Desfazendo a Modificação de um Arquivo Modificado com git restore -What if you realize that you don't want to keep your changes to the `CONTRIBUTING.md` file? -How can you easily unmodify it -- revert it back to what it looked like when you last committed (or initially cloned, or however you got it into your working directory)? -Luckily, `git status` tells you how to do that, too. -In the last example output, the unstaged area looks like this: +E se você perceber que não deseja manter as alterações feitas no arquivo `CONTRIBUTING.md`? +Como você pode desfazer as modificações facilmente -- revertê-lo para a aparência que tinha da última vez em que fez o commit (ou clonou inicialmente, ou como quer que tenha chegado ao seu diretório de trabalho)? +Felizmente, o `git status` também diz como fazer isso. +Na saída do último exemplo, a área não preparada se parece com isto: [source,console] ---- @@ -213,8 +213,8 @@ Changes not staged for commit: ---- -It tells you pretty explicitly how to discard the changes you've made. -Let's do what it says: +Ele diz explicitamente como descartar as alterações feitas. +Vamos fazer o que ele diz: [source,console] ---- @@ -229,7 +229,7 @@ Changes to be committed: [IMPORTANT] ===== -It's important to understand that `git restore ` is a dangerous command. -Any local changes you made to that file are gone -- Git just replaced that file with the last staged or committed version. -Don't ever use this command unless you absolutely know that you don't want those unsaved local changes. +É importante entender que `git restore ` é um comando perigoso. +Quaisquer alterações locais feitas nesse arquivo são perdidas -- o Git simplesmente substituiu aquele arquivo pela última versão preparada ou commitada. +Nunca use esse comando a menos que você saiba com certeza absoluta que não deseja essas alterações locais não salvas. ===== diff --git a/book/02-git-basics/sections/viewing-history.asc b/book/02-git-basics/sections/viewing-history.asc index 440c7f25..8c0230a8 100644 --- a/book/02-git-basics/sections/viewing-history.asc +++ b/book/02-git-basics/sections/viewing-history.asc @@ -1,18 +1,18 @@ [[_viewing_history]] -=== Viewing the Commit History +=== Visualizando o Histórico de Commits -After you have created several commits, or if you have cloned a repository with an existing commit history, you'll probably want to look back to see what has happened. -The most basic and powerful tool to do this is the `git log` command. +Depois de criar vários commits, ou se você tiver clonado um repositório com um histórico de commits existente, você provavelmente vai querer olhar para trás para ver o que aconteceu. +A ferramenta mais básica e poderosa para fazer isso é o comando `git log`. -These examples use a very simple project called "`simplegit`". -To get the project, run: +Estes exemplos usam um projeto muito simples chamado "`simplegit`". +Para obter o projeto, execute: [source,console] ---- $ git clone https://github.com/schacon/simplegit-progit ---- -When you run `git log` in this project, you should get output that looks something like this:(((git commands, log))) +Quando você executa `git log` neste projeto, você deve obter uma saída semelhante a esta:(((git commands, log))) [source,console] ---- @@ -36,14 +36,14 @@ Date: Sat Mar 15 10:31:28 2008 -0700 Initial commit ---- -By default, with no arguments, `git log` lists the commits made in that repository in reverse chronological order; that is, the most recent commits show up first. -As you can see, this command lists each commit with its SHA-1 checksum, the author's name and email, the date written, and the commit message. +Por padrão, sem argumentos, o `git log` lista os commits feitos naquele repositório em ordem cronológica reversa; ou seja, os commits mais recentes aparecem primeiro. +Como você pode ver, este comando lista cada commit com seu checksum SHA-1, o nome e e-mail do autor, a data em que foi escrito e a mensagem de commit. -A huge number and variety of options to the `git log` command are available to show you exactly what you're looking for. -Here, we'll show you some of the most popular. +Um grande número e variedade de opções para o comando `git log` estão disponíveis para mostrar exatamente o que você está procurando. +Aqui, mostraremos a você algumas das mais populares. -One of the more helpful options is `-p` or `--patch`, which shows the difference (the _patch_ output) introduced in each commit. -You can also limit the number of log entries displayed, such as using `-2` to show only the last two entries. +Uma das opções mais úteis é `-p` ou `--patch`, que mostra a diferença (a saída do _patch_) introduzida em cada commit. +Você também pode limitar o número de entradas de log exibidas, como usar `-2` para mostrar apenas as duas últimas entradas. [source,console] ---- @@ -89,10 +89,10 @@ index a0a60ae..47c6340 100644 -end ---- -This option displays the same information but with a diff directly following each entry. -This is very helpful for code review or to quickly browse what happened during a series of commits that a collaborator has added. -You can also use a series of summarizing options with `git log`. -For example, if you want to see some abbreviated stats for each commit, you can use the `--stat` option: +Esta opção exibe as mesmas informações, mas com um diff logo após cada entrada. +Isso é muito útil para revisão de código ou para navegar rapidamente pelo que aconteceu durante uma série de commits que um colaborador adicionou. +Você também pode usar uma série de opções de resumo com o `git log`. +Por exemplo, se você quiser ver algumas estatísticas abreviadas para cada commit, pode usar a opção `--stat`: [source,console] ---- @@ -127,14 +127,14 @@ Date: Sat Mar 15 10:31:28 2008 -0700 3 files changed, 54 insertions(+) ---- -As you can see, the `--stat` option prints below each commit entry a list of modified files, how many files were changed, and how many lines in those files were added and removed. -It also puts a summary of the information at the end. +Como você pode ver, a opção `--stat` imprime abaixo de cada entrada de commit uma lista de arquivos modificados, quantos arquivos foram alterados e quantas linhas nesses arquivos foram adicionadas e removidas. +Ela também coloca um resumo das informações no final. -Another really useful option is `--pretty`. -This option changes the log output to formats other than the default. -A few prebuilt option values are available for you to use. -The `oneline` value for this option prints each commit on a single line, which is useful if you're looking at a lot of commits. -In addition, the `short`, `full`, and `fuller` values show the output in roughly the same format but with less or more information, respectively: +Outra opção muito útil é `--pretty`. +Esta opção altera a saída do log para formatos diferentes do padrão. +Existem alguns valores de opções predefinidos disponíveis para você usar. +O valor `oneline` para esta opção imprime cada commit em uma única linha, o que é útil se você estiver observando muitos commits. +Além disso, os valores `short`, `full` e `fuller` mostram a saída aproximadamente no mesmo formato, mas com menos ou mais informações, respectivamente: [source,console] ---- @@ -144,8 +144,8 @@ ca82a6dff817ec66f44342007202690a93763949 Change version number a11bef06a3f659402fe7563abf99ad00de2209e6 Initial commit ---- -The most interesting option value is `format`, which allows you to specify your own log output format. -This is especially useful when you're generating output for machine parsing -- because you specify the format explicitly, you know it won't change with updates to Git:(((log formatting))) +O valor de opção mais interessante é `format`, que permite que você especifique seu próprio formato de saída de log. +Isso é especialmente útil quando você está gerando saída para análise (parsing) por máquina -- como você especifica o formato explicitamente, sabe que ele não será alterado com as atualizações do Git:(((log formatting))) [source,console] ---- @@ -155,37 +155,37 @@ ca82a6d - Scott Chacon, 6 years ago : Change version number a11bef0 - Scott Chacon, 6 years ago : Initial commit ---- -<> lists some of the more useful specifiers that `format` takes. +<> lista alguns dos especificadores mais úteis que o `format` aceita. [[pretty_format]] -.Useful specifiers for `git log --pretty=format` +.Especificadores úteis para `git log --pretty=format` [cols="1,4",options="header"] |================================ -| Specifier | Description of Output -| `%H` | Commit hash -| `%h` | Abbreviated commit hash -| `%T` | Tree hash -| `%t` | Abbreviated tree hash -| `%P` | Parent hashes -| `%p` | Abbreviated parent hashes -| `%an` | Author name -| `%ae` | Author email -| `%ad` | Author date (format respects the `--date=option`) -| `%ar` | Author date, relative -| `%cn` | Committer name -| `%ce` | Committer email -| `%cd` | Committer date -| `%cr` | Committer date, relative -| `%s` | Subject +| Especificador | Descrição da Saída +| `%H` | Hash do commit +| `%h` | Hash do commit abreviado +| `%T` | Hash da árvore (tree) +| `%t` | Hash da árvore abreviado +| `%P` | Hashes pais (parent hashes) +| `%p` | Hashes pais abreviados +| `%an` | Nome do autor +| `%ae` | E-mail do autor +| `%ad` | Data do autor (o formato respeita a opção `--date=`) +| `%ar` | Data do autor, relativa +| `%cn` | Nome do committer +| `%ce` | E-mail do committer +| `%cd` | Data do committer +| `%cr` | Data do committer, relativa +| `%s` | Assunto |================================ -You may be wondering what the difference is between _author_ and _committer_. -The author is the person who originally wrote the work, whereas the committer is the person who last applied the work. -So, if you send in a patch to a project and one of the core members applies the patch, both of you get credit -- you as the author, and the core member as the committer. -We'll cover this distinction a bit more in <>. +Você deve estar se perguntando qual é a diferença entre _autor_ (_author_) e _committer_. +O autor é a pessoa que escreveu o trabalho originalmente, ao passo que o committer é a pessoa que aplicou o trabalho por último. +Então, se você enviar um patch para um projeto e um dos membros principais (core members) aplicar o patch, ambos receberão o crédito -- você como autor e o membro principal como o committer. +Abordaremos essa distinção um pouco mais em <>. -The `oneline` and `format` option values are particularly useful with another `log` option called `--graph`. -This option adds a nice little ASCII graph showing your branch and merge history: +Os valores de opção `oneline` e `format` são particularmente úteis com outra opção `log` chamada `--graph`. +Esta opção adiciona um pequeno gráfico ASCII bacana mostrando o seu histórico de branches e merges: [source,console] ---- @@ -202,87 +202,87 @@ $ git log --pretty=format:"%h %s" --graph * 11d191e Merge branch 'defunkt' into local ---- -This type of output will become more interesting as we go through branching and merging in the next chapter. +Este tipo de saída se tornará mais interessante conforme passarmos por branches e merges no próximo capítulo. -Those are only some simple output-formatting options to `git log` -- there are many more. -<> lists the options we've covered so far, as well as some other common formatting options that may be useful, along with how they change the output of the `log` command. +Essas são apenas algumas opções simples de formatação de saída para o `git log` -- há muitas outras. +<> lista as opções que cobrimos até agora, bem como algumas outras opções comuns de formatação que podem ser úteis, junto com a forma como elas alteram a saída do comando `log`. [[log_options]] -.Common options to `git log` +.Opções comuns para `git log` [cols="1,4",options="header"] |================================ -| Option | Description -| `-p` | Show the patch introduced with each commit. -| `--stat` | Show statistics for files modified in each commit. -| `--shortstat` | Display only the changed/insertions/deletions line from the `--stat` command. -| `--name-only` | Show the list of files modified after the commit information. -| `--name-status` | Show the list of files affected with added/modified/deleted information as well. -| `--abbrev-commit` | Show only the first few characters of the SHA-1 checksum instead of all 40. -| `--relative-date` | Display the date in a relative format (for example, "`2 weeks ago`") instead of using the full date format. -| `--graph` | Display an ASCII graph of the branch and merge history beside the log output. -| `--pretty` | Show commits in an alternate format. Option values include `oneline`, `short`, `full`, `fuller`, and `format` (where you specify your own format). -| `--oneline` | Shorthand for `--pretty=oneline --abbrev-commit` used together. +| Opção | Descrição +| `-p` | Mostra o patch introduzido com cada commit. +| `--stat` | Mostra estatísticas de arquivos modificados em cada commit. +| `--shortstat` | Exibe apenas a linha changed/insertions/deletions do comando `--stat`. +| `--name-only` | Mostra a lista de arquivos modificados após as informações do commit. +| `--name-status` | Mostra a lista de arquivos afetados com informações de added/modified/deleted também. +| `--abbrev-commit` | Mostra apenas os primeiros caracteres do checksum SHA-1 em vez de todos os 40. +| `--relative-date` | Exibe a data em um formato relativo (por exemplo, "`2 weeks ago`") em vez de usar o formato de data completo. +| `--graph` | Exibe um gráfico ASCII da história de branches e merges ao lado da saída de log. +| `--pretty` | Mostra commits em um formato alternativo. Os valores de opções incluem `oneline`, `short`, `full`, `fuller` e `format` (onde você especifica seu próprio formato). +| `--oneline` | Uma forma abreviada de `--pretty=oneline --abbrev-commit` usados em conjunto. |================================ -==== Limiting Log Output +==== Limitando a Saída do Log -In addition to output-formatting options, `git log` takes a number of useful limiting options; that is, options that let you show only a subset of commits. -You've seen one such option already -- the `-2` option, which displays only the last two commits. -In fact, you can do `-`, where `n` is any integer to show the last `n` commits. -In reality, you're unlikely to use that often, because Git by default pipes all output through a pager so you see only one page of log output at a time. +Além das opções de formatação de saída, o `git log` aceita várias opções úteis de limitação; ou seja, opções que permitem exibir apenas um subconjunto de commits. +Você já viu uma dessas opções -- a opção `-2`, que exibe apenas os dois últimos commits. +De fato, você pode usar `-`, onde `n` é qualquer número inteiro para mostrar os últimos `n` commits. +Na realidade, é improvável que você o use com frequência, porque, por padrão, o Git envia (pipes) toda a saída por meio de um pager para que você veja apenas uma página de saída de log por vez. -However, the time-limiting options such as `--since` and `--until` are very useful. -For example, this command gets the list of commits made in the last two weeks: +No entanto, as opções de limite de tempo, como `--since` e `--until`, são muito úteis. +Por exemplo, este comando obtém a lista de commits feitos nas últimas duas semanas: [source,console] ---- $ git log --since=2.weeks ---- -This command works with lots of formats -- you can specify a specific date like `"2008-01-15"`, or a relative date such as `"2 years 1 day 3 minutes ago"`. +Este comando funciona com vários formatos -- você pode especificar uma data específica como `"2008-01-15"`, ou uma data relativa como `"2 years 1 day 3 minutes ago"`. -You can also filter the list to commits that match some search criteria. -The `--author` option allows you to filter on a specific author, and the `--grep` option lets you search for keywords in the commit messages. +Você também pode filtrar a lista para os commits que correspondam a alguns critérios de pesquisa. +A opção `--author` permite filtrar um autor específico, e a opção `--grep` permite pesquisar palavras-chave nas mensagens de commit. [NOTE] ==== -You can specify more than one instance of both the `--author` and `--grep` search criteria, which will limit the commit output to commits that match _any_ of the `--author` patterns and _any_ of the `--grep` patterns; however, adding the `--all-match` option further limits the output to just those commits that match _all_ `--grep` patterns. +Você pode especificar mais de uma instância dos critérios de pesquisa `--author` e `--grep`, o que limitará a saída dos commits aos commits que correspondem a _qualquer_ um dos padrões `--author` e _qualquer_ um dos padrões `--grep`; no entanto, adicionar a opção `--all-match` limita ainda mais a saída apenas aos commits que correspondem a _todos_ os padrões `--grep`. ==== -Another really helpful filter is the `-S` option (colloquially referred to as Git's "`pickaxe`" option), which takes a string and shows only those commits that changed the number of occurrences of that string. -For instance, if you wanted to find the last commit that added or removed a reference to a specific function, you could call: +Outro filtro realmente útil é a opção `-S` (coloquialmente chamada de opção "`pickaxe`" do Git), que recebe uma string e mostra apenas os commits que alteraram o número de ocorrências dessa string. +Por exemplo, se você quisesse encontrar o último commit que adicionou ou removeu uma referência a uma função específica, você poderia chamar: [source,console] ---- $ git log -S function_name ---- -The last really useful option to pass to `git log` as a filter is a path. -If you specify a directory or file name, you can limit the log output to commits that introduced a change to those files. -This is always the last option and is generally preceded by double dashes (`--`) to separate the paths from the options: +A última opção realmente útil para passar para `git log` como filtro é um caminho. +Se você especificar um diretório ou nome de arquivo, poderá limitar a saída do log aos commits que introduziram uma alteração nesses arquivos. +Essa é sempre a última opção e geralmente é precedida por dois hifens (`--`) para separar os caminhos das opções: [source,console] ---- $ git log -- path/to/file ---- -In <> we'll list these and a few other common options for your reference. +Em <>, listaremos estas e algumas outras opções comuns para sua referência. [[limit_options]] -.Options to limit the output of `git log` +.Opções para limitar a saída de `git log` [cols="2,4",options="header"] |================================ -| Option | Description -| `-` | Show only the last n commits. -| `--since`, `--after` | Limit the commits to those made after the specified date. -| `--until`, `--before` | Limit the commits to those made before the specified date. -| `--author` | Only show commits in which the author entry matches the specified string. -| `--committer` | Only show commits in which the committer entry matches the specified string. -| `--grep` | Only show commits with a commit message containing the string. -| `-S` | Only show commits adding or removing code matching the string. +| Opção | Descrição +| `-` | Mostra apenas os últimos n commits. +| `--since`, `--after` | Limita os commits aos feitos após a data especificada. +| `--until`, `--before` | Limita os commits aos feitos antes da data especificada. +| `--author` | Mostra apenas os commits em que a entrada do autor corresponda à string especificada. +| `--committer` | Mostra apenas os commits em que a entrada do committer corresponda à string especificada. +| `--grep` | Mostra apenas os commits com uma mensagem de commit contendo a string. +| `-S` | Mostra apenas os commits adicionando ou removendo código correspondente à string. |================================ -For example, if you want to see which commits modifying test files in the Git source code history were committed by Junio Hamano in the month of October 2008 and are not merge commits, you can run something like this:(((log filtering))) +Por exemplo, se você quiser ver quais commits que modificaram os arquivos de teste no histórico de código-fonte do Git foram commitados por Junio Hamano no mês de outubro de 2008 e não são commits de mesclagem (merge commits), você pode executar algo assim:(((log filtering))) [source,console] ---- @@ -296,11 +296,11 @@ d1a43f2 - reset --hard/read-tree --reset -u: remove unmerged new paths b0ad11e - pull: allow "git pull origin $something:$current_branch" into an unborn branch ---- -Of the nearly 40,000 commits in the Git source code history, this command shows the 6 that match those criteria. +Dos quase 40.000 commits no histórico do código-fonte do Git, esse comando mostra os 6 que correspondem a esses critérios. [TIP] -.Preventing the display of merge commits +.Prevenindo a exibição de commits de mesclagem (merge commits) ==== -Depending on the workflow used in your repository, it's possible that a sizable percentage of the commits in your log history are just merge commits, which typically aren't very informative. -To prevent the display of merge commits cluttering up your log history, simply add the `log` option `--no-merges`. +Dependendo do fluxo de trabalho usado no seu repositório, é possível que uma porcentagem considerável dos commits no seu histórico de log sejam apenas commits de mesclagem, que normalmente não são muito informativos. +Para evitar que a exibição de commits de mesclagem sobrecarregue (cluttering up) seu histórico de log, basta adicionar a opção `--no-merges` de `log`. ==== diff --git a/ch02-git-basics-chapter.asc b/ch02-git-basics-chapter.asc index 08db2548..689d9942 100644 --- a/ch02-git-basics-chapter.asc +++ b/ch02-git-basics-chapter.asc @@ -1,10 +1,10 @@ [[ch02-git-basics-chapter]] -== Git Basics +== Fundamentos do Git -If you can read only one chapter to get going with Git, this is it. -This chapter covers every basic command you need to do the vast majority of the things you'll eventually spend your time doing with Git. -By the end of the chapter, you should be able to configure and initialize a repository, begin and stop tracking files, and stage and commit changes. -We'll also show you how to set up Git to ignore certain files and file patterns, how to undo mistakes quickly and easily, how to browse the history of your project and view changes between commits, and how to push and pull from remote repositories. +Se você puder ler apenas um capítulo para começar a usar o Git, é este. +Este capítulo cobre todos os comandos básicos que você precisa para fazer a grande maioria das coisas que você passará seu tempo fazendo com o Git. +Ao final do capítulo, você deverá ser capaz de configurar e inicializar um repositório, começar e parar de rastrear arquivos, além de preparar (stage) e fazer commit de alterações. +Também mostraremos como configurar o Git para ignorar determinados arquivos e padrões de arquivo, como desfazer erros de maneira rápida e fácil, como navegar pelo histórico do seu projeto e visualizar alterações entre commits, e como enviar (push) e puxar (pull) de repositórios remotos. include::book/02-git-basics/sections/getting-a-repository.asc[] @@ -20,7 +20,7 @@ include::book/02-git-basics/sections/tagging.asc[] include::book/02-git-basics/sections/aliases.asc[] -=== Summary +=== Resumo -At this point, you can do all the basic local Git operations -- creating or cloning a repository, making changes, staging and committing those changes, and viewing the history of all the changes the repository has been through. -Next, we'll cover Git's killer feature: its branching model. +Neste ponto, você pode fazer todas as operações locais básicas do Git -- criar ou clonar um repositório, fazer alterações, preparar (stage) e fazer commit dessas alterações, e visualizar o histórico de todas as alterações pelas quais o repositório passou. +Em seguida, abordaremos o recurso matador do Git: seu modelo de branching. From 18eef124ded559942d4054cb7f174ddb07a077de Mon Sep 17 00:00:00 2001 From: "Sergio Cabral (AI Agent)" Date: Thu, 20 Aug 2026 13:51:57 -0300 Subject: [PATCH 05/16] =?UTF-8?q?Traduz:=20Cap=C3=ADtulo=203=20=E2=80=94?= =?UTF-8?q?=20Ramifica=C3=A7=C3=A3o=20no=20Git?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../sections/basic-branching-and-merging.asc | 194 +++++++------- .../sections/branch-management.asc | 102 +++---- book/03-git-branching/sections/nutshell.asc | 188 ++++++------- book/03-git-branching/sections/rebasing.asc | 252 +++++++++--------- .../sections/remote-branches.asc | 198 +++++++------- book/03-git-branching/sections/workflows.asc | 82 +++--- ch03-git-branching.asc | 28 +- 7 files changed, 522 insertions(+), 522 deletions(-) diff --git a/book/03-git-branching/sections/basic-branching-and-merging.asc b/book/03-git-branching/sections/basic-branching-and-merging.asc index a894b670..1d9b1422 100644 --- a/book/03-git-branching/sections/basic-branching-and-merging.asc +++ b/book/03-git-branching/sections/basic-branching-and-merging.asc @@ -1,31 +1,31 @@ -=== Basic Branching and Merging +=== Ramificação (Branching) e Mesclagem (Merging) Básicas -Let's go through a simple example of branching and merging with a workflow that you might use in the real world. -You'll follow these steps: +Vamos passar por um exemplo simples de ramificação (branching) e mesclagem (merging) com um fluxo de trabalho que você pode usar no mundo real. +Você seguirá as seguintes etapas: -. Do some work on a website. -. Create a branch for a new user story you're working on. -. Do some work in that branch. +. Fazer algum trabalho em um site. +. Criar um branch para uma nova história de usuário (user story) na qual você está trabalhando. +. Fazer algum trabalho naquele branch. -At this stage, you'll receive a call that another issue is critical and you need a hotfix. -You'll do the following: +Nesta fase, você receberá uma chamada informando que outro problema é crítico e você precisa de um hotfix. +Você fará o seguinte: -. Switch to your production branch. -. Create a branch to add the hotfix. -. After it's tested, merge the hotfix branch, and push to production. -. Switch back to your original user story and continue working. +. Mudar para o seu branch de produção. +. Criar um branch para adicionar o hotfix. +. Depois que for testado, mesclar (merge) o branch de hotfix e enviar (push) para produção. +. Mudar de volta para a sua história de usuário original e continuar trabalhando. [[_basic_branching]] -==== Basic Branching +==== Ramificação Básica (((branches, basic workflow))) -First, let's say you're working on your project and have a couple of commits already on the `master` branch. +Primeiro, digamos que você esteja trabalhando no seu projeto e já tenha alguns commits no branch `master`. -.A simple commit history -image::images/basic-branching-1.png[A simple commit history] +.Um histórico de commits simples +image::images/basic-branching-1.png[Um histórico de commits simples] -You've decided that you're going to work on issue #53 in whatever issue-tracking system your company uses. -To create a new branch and switch to it at the same time, you can run the `git checkout` command with the `-b` switch: +Você decidiu que vai trabalhar na issue #53 em qualquer sistema de rastreamento de problemas (issue-tracking) que a sua empresa utilize. +Para criar um novo branch e mudar para ele ao mesmo tempo, você pode executar o comando `git checkout` com a chave (switch) `-b`: [source,console] ---- @@ -33,7 +33,7 @@ $ git checkout -b iss53 Switched to a new branch "iss53" ---- -This is shorthand for: +Isso é um atalho para: [source,console] ---- @@ -41,11 +41,11 @@ $ git branch iss53 $ git checkout iss53 ---- -.Creating a new branch pointer -image::images/basic-branching-2.png[Creating a new branch pointer] +.Criando um novo ponteiro de branch +image::images/basic-branching-2.png[Criando um novo ponteiro de branch] -You work on your website and do some commits. -Doing so moves the `iss53` branch forward, because you have it checked out (that is, your `HEAD` is pointing to it): +Você trabalha no seu site e faz alguns commits. +Fazer isso move o branch `iss53` para frente, porque você fez checkout dele (ou seja, seu `HEAD` está apontando para ele): [source,console] ---- @@ -53,17 +53,17 @@ $ vim index.html $ git commit -a -m 'Create new footer [issue 53]' ---- -.The `iss53` branch has moved forward with your work -image::images/basic-branching-3.png[The `iss53` branch has moved forward with your work] +.O branch `iss53` avançou com o seu trabalho +image::images/basic-branching-3.png[O branch `iss53` avançou com o seu trabalho] -Now you get the call that there is an issue with the website, and you need to fix it immediately. -With Git, you don't have to deploy your fix along with the `iss53` changes you've made, and you don't have to put a lot of effort into reverting those changes before you can work on applying your fix to what is in production. -All you have to do is switch back to your `master` branch. +Agora você recebe a chamada de que há um problema com o site e você precisa corrigi-lo imediatamente. +Com o Git, você não precisa implantar (deploy) a sua correção junto com as alterações da `iss53` que você fez, e não precisa fazer muito esforço para reverter essas alterações antes de poder trabalhar na aplicação da sua correção ao que está em produção. +Tudo o que você precisa fazer é mudar de volta para o seu branch `master`. -However, before you do that, note that if your working directory or staging area has uncommitted changes that conflict with the branch you're checking out, Git won't let you switch branches. -It's best to have a clean working state when you switch branches. -There are ways to get around this (namely, stashing and commit amending) that we'll cover later on, in <>. -For now, let's assume you've committed all your changes, so you can switch back to your `master` branch: +No entanto, antes de fazer isso, observe que se o seu diretório de trabalho ou a área de preparação tiverem alterações não commitadas que conflitam com o branch para o qual você está fazendo o checkout, o Git não deixará você mudar de branch. +É melhor ter um estado de trabalho limpo quando você muda de branch. +Existem maneiras de contornar isso (como, por exemplo, o stashing e a alteração de commits) que abordaremos mais tarde, em <>. +Por enquanto, vamos assumir que você fez commit de todas as suas alterações, então você pode mudar de volta para o seu branch `master`: [source,console] ---- @@ -71,12 +71,12 @@ $ git checkout master Switched to branch 'master' ---- -At this point, your project working directory is exactly the way it was before you started working on issue #53, and you can concentrate on your hotfix. -This is an important point to remember: when you switch branches, Git resets your working directory to look like it did the last time you committed on that branch. -It adds, removes, and modifies files automatically to make sure your working copy is what the branch looked like on your last commit to it. +Neste ponto, o diretório de trabalho do seu projeto está exatamente da mesma forma que estava antes de você começar a trabalhar na issue #53, e você pode se concentrar no seu hotfix. +Este é um ponto importante a ser lembrado: quando você muda de branch, o Git redefine (resets) seu diretório de trabalho para que ele fique como na última vez em que você fez commit naquele branch. +Ele adiciona, remove e modifica arquivos automaticamente para garantir que a sua cópia de trabalho seja exatamente como o branch estava no seu último commit nele. -Next, you have a hotfix to make. -Let's create a `hotfix` branch on which to work until it's completed: +Em seguida, você tem um hotfix a fazer. +Vamos criar um branch `hotfix` no qual trabalharemos até que seja concluído: [source,console] ---- @@ -88,11 +88,11 @@ $ git commit -a -m 'Fix broken email address' 1 file changed, 2 insertions(+) ---- -.Hotfix branch based on `master` -image::images/basic-branching-4.png[Hotfix branch based on `master`] +.Branch hotfix baseado no `master` +image::images/basic-branching-4.png[Branch hotfix baseado no `master`] -You can run your tests, make sure the hotfix is what you want, and finally merge the `hotfix` branch back into your `master` branch to deploy to production. -You do this with the `git merge` command:(((git commands, merge))) +Você pode executar os seus testes, certificar-se de que o hotfix é o que você deseja, e, finalmente, mesclar o branch `hotfix` de volta para o seu branch `master` para implantar na produção. +Você faz isso com o comando `git merge`:(((git commands, merge))) [source,console] ---- @@ -104,18 +104,18 @@ Fast-forward 1 file changed, 2 insertions(+) ---- -You'll notice the phrase "`fast-forward`" in that merge. -Because the commit `C4` pointed to by the branch `hotfix` you merged in was directly ahead of the commit `C2` you're on, Git simply moves the pointer forward. -To phrase that another way, when you try to merge one commit with a commit that can be reached by following the first commit's history, Git simplifies things by moving the pointer forward because there is no divergent work to merge together -- this is called a "`fast-forward.`" +Você notará a frase "`fast-forward`" (avanço rápido) nessa mesclagem. +Como o commit `C4` apontado pelo branch `hotfix` que você mesclou estava diretamente à frente do commit `C2` em que você está, o Git simplesmente move o ponteiro para a frente. +Em outras palavras, quando você tenta mesclar um commit com um commit que pode ser alcançado seguindo o histórico do primeiro commit, o Git simplifica as coisas movendo o ponteiro para a frente, pois não há trabalho divergente a ser mesclado -- isso é chamado de "`fast-forward.`" -Your change is now in the snapshot of the commit pointed to by the `master` branch, and you can deploy the fix. +A sua alteração agora está no snapshot do commit apontado pelo branch `master`, e você pode implantar a correção. -.`master` is fast-forwarded to `hotfix` -image::images/basic-branching-5.png[`master` is fast-forwarded to `hotfix`] +.`master` é avançado (fast-forwarded) para `hotfix` +image::images/basic-branching-5.png[`master` é avançado (fast-forwarded) para `hotfix`] -After your super-important fix is deployed, you're ready to switch back to the work you were doing before you were interrupted. -However, first you'll delete the `hotfix` branch, because you no longer need it -- the `master` branch points at the same place. -You can delete it with the `-d` option to `git branch`: +Depois que sua correção superimportante for implantada, você estará pronto para voltar ao trabalho que estava fazendo antes de ser interrompido. +No entanto, primeiro você excluirá o branch `hotfix`, pois não precisa mais dele -- o branch `master` aponta para o mesmo lugar. +Você pode excluí-lo com a opção `-d` do comando `git branch`: [source,console] ---- @@ -123,7 +123,7 @@ $ git branch -d hotfix Deleted branch hotfix (3a0874c). ---- -Now you can switch back to your work-in-progress branch on issue #53 and continue working on it. +Agora você pode voltar ao seu branch de trabalho em andamento na issue #53 e continuar trabalhando nela. [source,console] ---- @@ -135,19 +135,19 @@ $ git commit -a -m 'Finish the new footer [issue 53]' 1 file changed, 1 insertion(+) ---- -.Work continues on `iss53` -image::images/basic-branching-6.png[Work continues on `iss53`] +.O trabalho continua no `iss53` +image::images/basic-branching-6.png[O trabalho continua no `iss53`] -It's worth noting here that the work you did in your `hotfix` branch is not contained in the files in your `iss53` branch. -If you need to pull it in, you can merge your `master` branch into your `iss53` branch by running `git merge master`, or you can wait to integrate those changes until you decide to pull the `iss53` branch back into `master` later. +Vale ressaltar aqui que o trabalho que você fez no seu branch `hotfix` não está contido nos arquivos do seu branch `iss53`. +Se você precisar incorporá-lo (pull it in), você pode mesclar (merge) o seu branch `master` para dentro do seu branch `iss53` executando `git merge master`, ou pode esperar para integrar essas alterações até decidir incorporar o branch `iss53` de volta ao `master` mais tarde. [[_basic_merging]] -==== Basic Merging +==== Mesclagem (Merging) Básica (((branches, merging)))(((merging))) -Suppose you've decided that your issue #53 work is complete and ready to be merged into your `master` branch. -In order to do that, you'll merge your `iss53` branch into `master`, much like you merged your `hotfix` branch earlier. -All you have to do is check out the branch you wish to merge into and then run the `git merge` command: +Suponha que você decidiu que seu trabalho na issue #53 está completo e pronto para ser mesclado (merged) no seu branch `master`. +Para fazer isso, você mesclará seu branch `iss53` no `master`, de forma semelhante à mesclagem do seu branch `hotfix` anteriormente. +Tudo o que você precisa fazer é fazer checkout do branch para o qual deseja mesclar (merge into) e depois executar o comando `git merge`: [source,console] ---- @@ -159,22 +159,22 @@ index.html | 1 + 1 file changed, 1 insertion(+) ---- -This looks a bit different than the `hotfix` merge you did earlier. -In this case, your development history has diverged from some older point. -Because the commit on the branch you're on isn't a direct ancestor of the branch you're merging in, Git has to do some work. -In this case, Git does a simple three-way merge, using the two snapshots pointed to by the branch tips and the common ancestor of the two. +Isso parece um pouco diferente da mesclagem do `hotfix` que você fez anteriormente. +Neste caso, o seu histórico de desenvolvimento divergiu de algum ponto anterior. +Como o commit do branch em que você está não é um ancestral direto do branch que você está mesclando, o Git tem que fazer algum trabalho. +Nesse caso, o Git faz uma simples mesclagem de três vias (three-way merge), usando os dois snapshots apontados pelas pontas dos branches (branch tips) e o ancestral comum aos dois. -.Three snapshots used in a typical merge -image::images/basic-merging-1.png[Three snapshots used in a typical merge] +.Três snapshots usados em uma mesclagem típica +image::images/basic-merging-1.png[Três snapshots usados em uma mesclagem típica] -Instead of just moving the branch pointer forward, Git creates a new snapshot that results from this three-way merge and automatically creates a new commit that points to it. -This is referred to as a merge commit, and is special in that it has more than one parent. +Em vez de apenas mover o ponteiro do branch para a frente, o Git cria um novo snapshot que resulta dessa mesclagem de três vias (three-way merge) e cria automaticamente um novo commit que aponta para ele. +Isso é conhecido como um merge commit (commit de mesclagem), e é especial porque tem mais de um pai. -.A merge commit -image::images/basic-merging-2.png[A merge commit] +.Um merge commit +image::images/basic-merging-2.png[Um merge commit] -Now that your work is merged in, you have no further need for the `iss53` branch. -You can close the issue in your issue-tracking system, and delete the branch: +Agora que o seu trabalho foi mesclado (merged), você não tem mais necessidade do branch `iss53`. +Você pode fechar a issue no seu sistema de rastreamento de problemas e excluir o branch: [source,console] ---- @@ -182,12 +182,12 @@ $ git branch -d iss53 ---- [[_basic_merge_conflicts]] -==== Basic Merge Conflicts +==== Conflitos Básicos de Mesclagem (Merge Conflicts) (((merging, conflicts))) -Occasionally, this process doesn't go smoothly. -If you changed the same part of the same file differently in the two branches you're merging, Git won't be able to merge them cleanly. -If your fix for issue #53 modified the same part of a file as the `hotfix` branch, you'll get a merge conflict that looks something like this: +Ocasionalmente, esse processo não ocorre sem problemas. +Se você alterou a mesma parte do mesmo arquivo de forma diferente nos dois branches que está mesclando, o Git não será capaz de mesclá-los de forma limpa (cleanly). +Se a sua correção para a issue #53 modificou a mesma parte de um arquivo que o branch `hotfix`, você terá um conflito de mesclagem (merge conflict) parecido com este: [source,console] ---- @@ -197,9 +197,9 @@ CONFLICT (content): Merge conflict in index.html Automatic merge failed; fix conflicts and then commit the result. ---- -Git hasn't automatically created a new merge commit. -It has paused the process while you resolve the conflict. -If you want to see which files are unmerged at any point after a merge conflict, you can run `git status`: +O Git não criou automaticamente um novo merge commit. +Ele pausou o processo enquanto você resolve o conflito. +Se você quiser ver quais arquivos não foram mesclados (unmerged) em qualquer ponto após um conflito de mesclagem, você pode executar o `git status`: [source,console] ---- @@ -216,9 +216,9 @@ Unmerged paths: no changes added to commit (use "git add" and/or "git commit -a") ---- -Anything that has merge conflicts and hasn't been resolved is listed as unmerged. -Git adds standard conflict-resolution markers to the files that have conflicts, so you can open them manually and resolve those conflicts. -Your file contains a section that looks something like this: +Qualquer coisa que tenha conflitos de mesclagem e não tenha sido resolvida é listada como não mesclada (unmerged). +O Git adiciona marcadores de resolução de conflitos padrão aos arquivos que têm conflitos, para que você possa abri-los manualmente e resolver esses conflitos. +O seu arquivo contém uma seção parecida com esta: [source,html] ---- @@ -231,9 +231,9 @@ Your file contains a section that looks something like this: >>>>>>> iss53:index.html ---- -This means the version in `HEAD` (your `master` branch, because that was what you had checked out when you ran your merge command) is the top part of that block (everything above the `=======`), while the version in your `iss53` branch looks like everything in the bottom part. -In order to resolve the conflict, you have to either choose one side or the other or merge the contents yourself. -For instance, you might resolve this conflict by replacing the entire block with this: +Isso significa que a versão no `HEAD` (seu branch `master`, porque era esse que você havia feito checkout quando executou o comando merge) é a parte superior daquele bloco (tudo acima de `=======`), enquanto a versão no seu branch `iss53` se parece com tudo o que está na parte inferior. +Para resolver o conflito, você deve escolher um lado ou o outro ou mesclar o conteúdo você mesmo. +Por exemplo, você pode resolver esse conflito substituindo o bloco inteiro por isso: [source,html] ---- @@ -242,11 +242,11 @@ please contact us at email.support@github.com ---- -This resolution has a little of each section, and the `<<<<<<<`, `=======`, and `>>>>>>>` lines have been completely removed. -After you've resolved each of these sections in each conflicted file, run `git add` on each file to mark it as resolved. -Staging the file marks it as resolved in Git. +Essa resolução tem um pouco de cada seção, e as linhas `<<<<<<<`, `=======` e `>>>>>>>` foram completamente removidas. +Depois de resolver cada uma dessas seções em cada arquivo em conflito, execute `git add` em cada arquivo para marcá-lo como resolvido. +Preparar o arquivo (staging) marca-o como resolvido no Git. -If you want to use a graphical tool to resolve these issues, you can run `git mergetool`, which fires up an appropriate visual merge tool and walks you through the conflicts:(((git commands, mergetool))) +Se você quiser usar uma ferramenta gráfica para resolver esses problemas, você pode executar o `git mergetool`, que aciona uma ferramenta de mesclagem visual apropriada e o guia através dos conflitos:(((git commands, mergetool))) [source,console] ---- @@ -265,17 +265,17 @@ Normal merge conflict for 'index.html': Hit return to start merge resolution tool (opendiff): ---- -If you want to use a merge tool other than the default (Git chose `opendiff` in this case because the command was run on macOS), you can see all the supported tools listed at the top after "`one of the following tools.`" -Just type the name of the tool you'd rather use. +Se você quiser usar uma ferramenta de mesclagem diferente da padrão (o Git escolheu `opendiff` neste caso porque o comando foi executado no macOS), você pode ver todas as ferramentas suportadas listadas no topo após "`one of the following tools.`" +Basta digitar o nome da ferramenta que você prefere usar. [NOTE] ==== -If you need more advanced tools for resolving tricky merge conflicts, we cover more on merging in <>. +Se você precisar de ferramentas mais avançadas para resolver conflitos de mesclagem complicados, cobriremos mais sobre mesclagem em <>. ==== -After you exit the merge tool, Git asks you if the merge was successful. -If you tell the script that it was, it stages the file to mark it as resolved for you. -You can run `git status` again to verify that all conflicts have been resolved: +Depois de sair da ferramenta de mesclagem, o Git pergunta se a mesclagem foi bem-sucedida. +Se você disser ao script que sim, ele prepara (stages) o arquivo para marcá-lo como resolvido para você. +Você pode executar `git status` novamente para verificar se todos os conflitos foram resolvidos: [source,console] ---- @@ -289,8 +289,8 @@ Changes to be committed: modified: index.html ---- -If you're happy with that, and you verify that everything that had conflicts has been staged, you can type `git commit` to finalize the merge commit. -The commit message by default looks something like this: +Se você estiver satisfeito com isso e verificar que tudo o que tinha conflitos foi preparado (staged), você pode digitar `git commit` para finalizar o merge commit. +A mensagem de commit, por padrão, se parece com isto: [source,console] ---- @@ -315,4 +315,4 @@ Conflicts: # ---- -If you think it would be helpful to others looking at this merge in the future, you can modify this commit message with details about how you resolved the merge and explain why you did the changes you made if these are not obvious. +Se você acha que seria útil para outras pessoas analisarem essa mesclagem no futuro, você pode modificar esta mensagem de commit com detalhes sobre como você resolveu a mesclagem e explicar por que você fez as alterações que fez, se elas não forem óbvias. diff --git a/book/03-git-branching/sections/branch-management.asc b/book/03-git-branching/sections/branch-management.asc index ae81e89a..b891b72e 100644 --- a/book/03-git-branching/sections/branch-management.asc +++ b/book/03-git-branching/sections/branch-management.asc @@ -1,11 +1,11 @@ [[_branch_management]] -=== Branch Management +=== Gerenciamento de Branches (((branches, managing))) -Now that you've created, merged, and deleted some branches, let's look at some branch-management tools that will come in handy when you begin using branches all the time. +Agora que você criou, mesclou (merged) e excluiu alguns branches, vamos dar uma olhada em algumas ferramentas de gerenciamento de branches que serão úteis quando você começar a usar branches o tempo todo. -The `git branch` command does more than just create and delete branches.(((git commands, branch))) -If you run it with no arguments, you get a simple listing of your current branches: +O comando `git branch` faz mais do que apenas criar e excluir branches.(((git commands, branch))) +Se você executá-lo sem argumentos, obterá uma listagem simples de seus branches atuais: [source,console] ---- @@ -15,9 +15,9 @@ $ git branch testing ---- -Notice the `*` character that prefixes the `master` branch: it indicates the branch that you currently have checked out (i.e., the branch that `HEAD` points to). -This means that if you commit at this point, the `master` branch will be moved forward with your new work. -To see the last commit on each branch, you can run `git branch -v`: +Observe o caractere `*` que antecede o branch `master`: ele indica o branch em que você fez checkout no momento (ou seja, o branch para o qual o `HEAD` aponta). +Isso significa que, se você fizer um commit neste ponto, o branch `master` será movido para frente com o seu novo trabalho. +Para ver o último commit em cada branch, você pode executar `git branch -v`: [source,console] ---- @@ -27,8 +27,8 @@ $ git branch -v testing 782fd34 Add scott to the author list in the readme ---- -The useful `--merged` and `--no-merged` options can filter this list to branches that you have or have not yet merged into the branch you're currently on. -To see which branches are already merged into the branch you're on, you can run `git branch --merged`: +As opções úteis `--merged` e `--no-merged` podem filtrar esta lista para branches que você tem ou ainda não mesclou no branch em que você está atualmente. +Para ver quais branches já estão mesclados (merged) no branch em que você está, você pode executar `git branch --merged`: [source,console] ---- @@ -37,10 +37,10 @@ $ git branch --merged * master ---- -Because you already merged in `iss53` earlier, you see it in your list. -Branches on this list without the `*` in front of them are generally fine to delete with `git branch -d`; you've already incorporated their work into another branch, so you're not going to lose anything. +Como você já mesclou o `iss53` anteriormente, você o vê na sua lista. +Branches nesta lista sem o `*` na frente geralmente podem ser excluídos sem problemas com o `git branch -d`; você já incorporou o trabalho deles a outro branch, então não perderá nada. -To see all the branches that contain work you haven't yet merged in, you can run `git branch --no-merged`: +Para ver todos os branches que contêm trabalho que você ainda não mesclou, você pode executar `git branch --no-merged`: [source,console] ---- @@ -48,8 +48,8 @@ $ git branch --no-merged testing ---- -This shows your other branch. -Because it contains work that isn't merged in yet, trying to delete it with `git branch -d` will fail: +Isso mostra o seu outro branch. +Como ele contém trabalho que ainda não foi mesclado, tentar excluí-lo com `git branch -d` falhará: [source,console] ---- @@ -58,13 +58,13 @@ error: The branch 'testing' is not fully merged. If you are sure you want to delete it, run 'git branch -D testing'. ---- -If you really do want to delete the branch and lose that work, you can force it with `-D`, as the helpful message points out. +Se você realmente deseja excluir o branch e perder esse trabalho, você pode forçar a exclusão com `-D`, como a mensagem de ajuda (helpful message) aponta. [TIP] ==== -The options described above, `--merged` and `--no-merged` will, if not given a commit or branch name as an argument, show you what is, respectively, merged or not merged into your _current_ branch. +As opções descritas acima, `--merged` e `--no-merged`, se não receberem um nome de commit ou de branch como argumento, mostrarão a você o que está, respectivamente, mesclado (merged) ou não mesclado (not merged) no seu branch _atual_. -You can always provide an additional argument to ask about the merge state with respect to some other branch without checking that other branch out first, as in, what is not merged into the `master` branch? +Você sempre pode fornecer um argumento adicional para perguntar sobre o estado de mesclagem (merge state) em relação a algum outro branch sem fazer checkout desse outro branch primeiro, como em: o que não está mesclado no branch `master`? [source,console] ---- $ git checkout testing @@ -74,34 +74,34 @@ $ git branch --no-merged master ---- ==== -==== Changing a branch name +==== Alterando o nome de um branch [CAUTION] ==== -Do not rename branches that are still in use by other collaborators. -Do not rename a branch like master/main/mainline without having read the section <<_changing_master>>. +Não renomeie branches que ainda estão em uso por outros colaboradores. +Não renomeie um branch como master/main/mainline sem ter lido a seção <<_changing_master>>. ==== -Suppose you have a branch that is called `bad-branch-name` and you want to change it to `corrected-branch-name`, while keeping all history. -You also want to change the branch name on the remote (GitHub, GitLab, other server). -How do you do this? +Suponha que você tenha um branch chamado `bad-branch-name` e queira alterá-lo para `corrected-branch-name`, mantendo todo o histórico. +Você também deseja alterar o nome do branch no remoto (GitHub, GitLab, outro servidor). +Como você faz isso? -Rename the branch locally with the `git branch --move` command: +Renomeie o branch localmente com o comando `git branch --move`: [source, console] ---- $ git branch --move bad-branch-name corrected-branch-name ---- -This replaces your `bad-branch-name` with `corrected-branch-name`, but this change is only local for now. -To let others see the corrected branch on the remote, push it: +Isso substitui o seu `bad-branch-name` por `corrected-branch-name`, mas essa alteração é apenas local por enquanto. +Para permitir que outras pessoas vejam o branch corrigido no remoto, faça o push dele: [source,console] ---- $ git push --set-upstream origin corrected-branch-name ---- -Now we'll take a brief look at where we are now: +Agora daremos uma breve olhada onde estamos agora: [source, console] ---- @@ -113,44 +113,44 @@ $ git branch --all remotes/origin/main ---- -Notice that you're on the branch `corrected-branch-name` and it's available on the remote. -However, the branch with the bad name is also still present there but you can delete it by executing the following command: +Observe que você está no branch `corrected-branch-name` e ele está disponível no remoto. +No entanto, o branch com o nome ruim também ainda está presente lá, mas você pode excluí-lo executando o seguinte comando: [source,console] ---- $ git push origin --delete bad-branch-name ---- -Now the bad branch name is fully replaced with the corrected branch name. +Agora, o nome do branch ruim foi totalmente substituído pelo nome do branch corrigido. [[_changing_master]] -===== Changing the master branch name +===== Alterando o nome do branch master [WARNING] ==== -Changing the name of a branch like master/main/mainline/default will break the integrations, services, helper utilities and build/release scripts that your repository uses. -Before you do this, make sure you consult with your collaborators. -Also, make sure you do a thorough search through your repo and update any references to the old branch name in your code and scripts. +Alterar o nome de um branch como master/main/mainline/default quebrará as integrações, os serviços, os utilitários auxiliares e os scripts de compilação/lançamento (build/release) que o seu repositório usa. +Antes de fazer isso, certifique-se de consultar os seus colaboradores. +Além disso, certifique-se de fazer uma pesquisa minuciosa no seu repositório e atualizar quaisquer referências ao nome antigo do branch no seu código e scripts. ==== -Rename your local `master` branch into `main` with the following command: +Renomeie o seu branch `master` local para `main` com o seguinte comando: [source,console] ---- $ git branch --move master main ---- -There's no local `master` branch anymore, because it's renamed to the `main` branch. +Não há mais branch `master` local, pois ele foi renomeado para branch `main`. -To let others see the new `main` branch, you need to push it to the remote. -This makes the renamed branch available on the remote. +Para permitir que outras pessoas vejam o novo branch `main`, você precisa fazer o push dele para o remoto. +Isso torna o branch renomeado disponível no remoto. [source,console] ---- $ git push --set-upstream origin main ---- -Now we end up with the following state: +Agora acabamos com o seguinte estado: [source,console] ---- @@ -161,21 +161,21 @@ $ git branch --all remotes/origin/master ---- -Your local `master` branch is gone, as it's replaced with the `main` branch. -The `main` branch is present on the remote. -However, the old `master` branch is still present on the remote. -Other collaborators will continue to use the `master` branch as the base of their work, until you make some further changes. +O seu branch `master` local se foi, pois foi substituído pelo branch `main`. +O branch `main` está presente no remoto. +No entanto, o branch `master` antigo ainda está presente no remoto. +Outros colaboradores continuarão a usar o branch `master` como base de seu trabalho, até que você faça algumas alterações adicionais. -Now you have a few more tasks in front of you to complete the transition: +Agora você tem mais algumas tarefas pela frente para concluir a transição: -* Any projects that depend on this one will need to update their code and/or configuration. -* Update any test-runner configuration files. -* Adjust build and release scripts. -* Redirect settings on your repo host for things like the repo's default branch, merge rules, and other things that match branch names. -* Update references to the old branch in documentation. -* Close or merge any pull requests that target the old branch. +* Quaisquer projetos que dependam deste precisarão atualizar o seu código e/ou configuração. +* Atualizar quaisquer arquivos de configuração do test-runner. +* Ajustar scripts de compilação (build) e lançamento (release). +* Redirecionar as configurações no host do seu repositório para coisas como o branch padrão do repositório, regras de mesclagem e outras coisas que correspondam a nomes de branch. +* Atualizar as referências ao branch antigo na documentação. +* Fechar ou mesclar quaisquer pull requests direcionados ao branch antigo. -After you've done all these tasks, and are certain the `main` branch performs just as the `master` branch, you can delete the `master` branch: +Depois de concluir todas essas tarefas e ter certeza de que o branch `main` funciona exatamente como o branch `master`, você pode excluir o branch `master`: [source, console] ---- diff --git a/book/03-git-branching/sections/nutshell.asc b/book/03-git-branching/sections/nutshell.asc index 2bffd5dd..c800e87c 100644 --- a/book/03-git-branching/sections/nutshell.asc +++ b/book/03-git-branching/sections/nutshell.asc @@ -1,15 +1,15 @@ [[_git_branches_overview]] -=== Branches in a Nutshell +=== Branches em Poucas Palavras -To really understand the way Git does branching, we need to take a step back and examine how Git stores its data. +Para realmente entender a maneira como o Git faz ramificação (branching), precisamos dar um passo atrás e examinar como o Git armazena seus dados. -As you may remember from <>, Git doesn't store data as a series of changesets or differences, but instead as a series of _snapshots_. +Como você deve se lembrar do <>, o Git não armazena dados como uma série de conjuntos de alterações (changesets) ou diferenças, mas sim como uma série de _snapshots_ (instantâneos). -When you make a commit, Git stores a commit object that contains a pointer to the snapshot of the content you staged. -This object also contains the author's name and email address, the message that you typed, and pointers to the commit or commits that directly came before this commit (its parent or parents): zero parents for the initial commit, one parent for a normal commit, and multiple parents for a commit that results from a merge of two or more branches. +Quando você faz um commit, o Git armazena um objeto de commit que contém um ponteiro para o snapshot do conteúdo que você preparou (staged). +Este objeto também contém o nome e o endereço de e-mail do autor, a mensagem que você digitou e ponteiros para o commit ou commits que vieram diretamente antes deste commit (seu pai ou pais): zero pais para o commit inicial, um pai para um commit normal e vários pais para um commit que resulta de uma mesclagem (merge) de dois ou mais branches. -To visualize this, let's assume that you have a directory containing three files, and you stage them all and commit. -Staging the files computes a checksum for each one (the SHA-1 hash we mentioned in <>), stores that version of the file in the Git repository (Git refers to them as _blobs_), and adds that checksum to the staging area: +Para visualizar isso, vamos assumir que você tem um diretório contendo três arquivos, e você prepara (stage) todos eles e faz o commit. +Preparar (staging) os arquivos calcula um checksum para cada um (o hash SHA-1 que mencionamos em <>), armazena essa versão do arquivo no repositório Git (o Git se refere a eles como _blobs_) e adiciona esse checksum à área de preparação (staging area): [source,console] ---- @@ -17,65 +17,65 @@ $ git add README test.rb LICENSE $ git commit -m 'Initial commit' ---- -When you create the commit by running `git commit`, Git checksums each subdirectory (in this case, just the root project directory) and stores them as a tree object in the Git repository. -Git then creates a commit object that has the metadata and a pointer to the root project tree so it can re-create that snapshot when needed.(((git commands, commit))) +Quando você cria o commit executando `git commit`, o Git calcula o checksum de cada subdiretório (neste caso, apenas o diretório raiz do projeto) e os armazena como um objeto de árvore (tree) no repositório Git. +O Git então cria um objeto de commit que tem os metadados e um ponteiro para a árvore do projeto raiz para que ele possa recriar aquele snapshot quando necessário.(((git commands, commit))) -Your Git repository now contains five objects: three _blobs_ (each representing the contents of one of the three files), one _tree_ that lists the contents of the directory and specifies which file names are stored as which blobs, and one _commit_ with the pointer to that root tree and all the commit metadata. +Seu repositório Git agora contém cinco objetos: três _blobs_ (cada um representando o conteúdo de um dos três arquivos), uma _árvore (tree)_ que lista o conteúdo do diretório e especifica quais nomes de arquivo são armazenados como quais blobs, e um _commit_ com o ponteiro para essa árvore raiz e todos os metadados do commit. -.A commit and its tree -image::images/commit-and-tree.png[A commit and its tree] +.Um commit e sua árvore +image::images/commit-and-tree.png[Um commit e sua árvore] -If you make some changes and commit again, the next commit stores a pointer to the commit that came immediately before it. +Se você fizer algumas alterações e fizer commit novamente, o próximo commit armazenará um ponteiro para o commit que veio imediatamente antes dele. -.Commits and their parents -image::images/commits-and-parents.png[Commits and their parents] +.Commits e seus pais +image::images/commits-and-parents.png[Commits e seus pais] -A branch in Git is simply a lightweight movable pointer to one of these commits. -The default branch name in Git is `master`. -As you start making commits, you're given a `master` branch that points to the last commit you made. -Every time you commit, the `master` branch pointer moves forward automatically. +Um branch no Git é simplesmente um ponteiro móvel e leve para um desses commits. +O nome do branch padrão no Git é `master`. +À medida que você começa a fazer commits, você recebe um branch `master` que aponta para o último commit que você fez. +Toda vez que você faz um commit, o ponteiro do branch `master` avança automaticamente. [NOTE] ==== -The "`master`" branch in Git is not a special branch.(((master))) -It is exactly like any other branch. -The only reason nearly every repository has one is that the `git init` command creates it by default and most people don't bother to change it. +O branch "`master`" no Git não é um branch especial.(((master))) +É exatamente como qualquer outro branch. +A única razão pela qual quase todo repositório tem um é que o comando `git init` o cria por padrão e a maioria das pessoas não se dá ao trabalho de alterá-lo. ==== -.A branch and its commit history -image::images/branch-and-history.png[A branch and its commit history] +.Um branch e seu histórico de commits +image::images/branch-and-history.png[Um branch e seu histórico de commits] [[_create_new_branch]] -==== Creating a New Branch +==== Criando um Novo Branch (((branches, creating))) -What happens when you create a new branch? -Well, doing so creates a new pointer for you to move around. -Let's say you want to create a new branch called `testing`. -You do this with the `git branch` command:(((git commands, branch))) +O que acontece quando você cria um novo branch? +Bem, fazer isso cria um novo ponteiro para você mover por aí. +Digamos que você queira criar um novo branch chamado `testing`. +Você faz isso com o comando `git branch`:(((git commands, branch))) [source,console] ---- $ git branch testing ---- -This creates a new pointer to the same commit you're currently on. +Isso cria um novo ponteiro para o mesmo commit em que você está no momento. -.Two branches pointing into the same series of commits -image::images/two-branches.png[Two branches pointing into the same series of commits] +.Dois branches apontando para a mesma série de commits +image::images/two-branches.png[Dois branches apontando para a mesma série de commits] -How does Git know what branch you're currently on? -It keeps a special pointer called `HEAD`. -Note that this is a lot different than the concept of `HEAD` in other VCSs you may be used to, such as Subversion or CVS. -In Git, this is a pointer to the local branch you're currently on. -In this case, you're still on `master`. -The `git branch` command only _created_ a new branch -- it didn't switch to that branch. +Como o Git sabe em qual branch você está no momento? +Ele mantém um ponteiro especial chamado `HEAD`. +Observe que isso é muito diferente do conceito de `HEAD` em outros VCSs aos quais você pode estar acostumado, como Subversion ou CVS. +No Git, este é um ponteiro para o branch local em que você está no momento. +Neste caso, você ainda está no `master`. +O comando `git branch` apenas _criou_ um novo branch -- ele não mudou para aquele branch. -.HEAD pointing to a branch -image::images/head-to-master.png[HEAD pointing to a branch] +.HEAD apontando para um branch +image::images/head-to-master.png[HEAD apontando para um branch] -You can easily see this by running a simple `git log` command that shows you where the branch pointers are pointing. -This option is called `--decorate`. +Você pode ver isso facilmente executando um comando simples `git log` que mostra para onde os ponteiros de branch estão apontando. +Esta opção é chamada `--decorate`. [source,console] ---- @@ -85,27 +85,27 @@ f30ab (HEAD -> master, testing) Add feature #32 - ability to add new formats to 98ca9 Initial commit ---- -You can see the `master` and `testing` branches that are right there next to the `f30ab` commit. +Você pode ver os branches `master` e `testing` que estão bem ali ao lado do commit `f30ab`. [[_switching_branches]] -==== Switching Branches +==== Mudando de Branches (((branches, switching))) -To switch to an existing branch, you run the `git checkout` command.(((git commands, checkout))) -Let's switch to the new `testing` branch: +Para mudar para um branch existente, você executa o comando `git checkout`.(((git commands, checkout))) +Vamos mudar para o novo branch `testing`: [source,console] ---- $ git checkout testing ---- -This moves `HEAD` to point to the `testing` branch. +Isso move o `HEAD` para apontar para o branch `testing`. -.HEAD points to the current branch -image::images/head-to-testing.png[HEAD points to the current branch] +.HEAD aponta para o branch atual +image::images/head-to-testing.png[HEAD aponta para o branch atual] -What is the significance of that? -Well, let's do another commit: +Qual o significado disso? +Bem, vamos fazer outro commit: [source,console] ---- @@ -113,11 +113,11 @@ $ vim test.rb $ git commit -a -m 'Make a change' ---- -.The HEAD branch moves forward when a commit is made -image::images/advance-testing.png[The HEAD branch moves forward when a commit is made] +.O branch HEAD avança quando um commit é feito +image::images/advance-testing.png[O branch HEAD avança quando um commit é feito] -This is interesting, because now your `testing` branch has moved forward, but your `master` branch still points to the commit you were on when you ran `git checkout` to switch branches. -Let's switch back to the `master` branch: +Isso é interessante, porque agora o seu branch `testing` avançou, mas o seu branch `master` ainda aponta para o commit em que você estava quando executou `git checkout` para mudar de branch. +Vamos voltar para o branch `master`: [source,console] ---- @@ -125,34 +125,34 @@ $ git checkout master ---- [NOTE] -.`git log` doesn't show _all_ the branches _all_ the time +.`git log` não mostra _todos_ os branches _o tempo todo_ ==== -If you were to run `git log` right now, you might wonder where the "testing" branch you just created went, as it would not appear in the output. +Se você executasse `git log` agora mesmo, poderia se perguntar para onde foi o branch "testing" que você acabou de criar, pois ele não apareceria na saída. -The branch hasn't disappeared; Git just doesn't know that you're interested in that branch and it is trying to show you what it thinks you're interested in. -In other words, by default, `git log` will only show commit history below the branch you've checked out. +O branch não desapareceu; o Git apenas não sabe que você está interessado naquele branch e está tentando mostrar o que ele acha que você está interessado. +Em outras palavras, por padrão, o `git log` mostrará apenas o histórico de commits abaixo do branch que você fez o checkout. -To show commit history for the desired branch you have to explicitly specify it: `git log testing`. -To show all of the branches, add `--all` to your `git log` command. +Para mostrar o histórico de commits do branch desejado, você deve especificá-lo explicitamente: `git log testing`. +Para mostrar todos os branches, adicione `--all` ao seu comando `git log`. ==== -.HEAD moves when you checkout -image::images/checkout-master.png[HEAD moves when you checkout] +.HEAD se move quando você faz checkout +image::images/checkout-master.png[HEAD se move quando você faz checkout] -That command did two things. -It moved the HEAD pointer back to point to the `master` branch, and it reverted the files in your working directory back to the snapshot that `master` points to. -This also means the changes you make from this point forward will diverge from an older version of the project. -It essentially rewinds the work you've done in your `testing` branch so you can go in a different direction. +Aquele comando fez duas coisas. +Ele moveu o ponteiro HEAD de volta para apontar para o branch `master`, e reverteu os arquivos no seu diretório de trabalho de volta para o snapshot para o qual o `master` aponta. +Isso também significa que as alterações feitas a partir deste ponto divergirão de uma versão anterior do projeto. +Ele essencialmente retrocede (rewinds) o trabalho que você fez no seu branch `testing` para que você possa seguir em uma direção diferente. [NOTE] -.Switching branches changes files in your working directory +.Mudar de branch altera os arquivos no seu diretório de trabalho ==== -It's important to note that when you switch branches in Git, files in your working directory will change. -If you switch to an older branch, your working directory will be reverted to look like it did the last time you committed on that branch. -If Git cannot do it cleanly, it will not let you switch at all. +É importante observar que quando você muda de branch no Git, os arquivos no seu diretório de trabalho serão alterados. +Se você mudar para um branch mais antigo, seu diretório de trabalho será revertido para ficar como na última vez em que você fez commit naquele branch. +Se o Git não conseguir fazer isso de forma limpa (cleanly), ele não permitirá a mudança. ==== -Let's make a few changes and commit again: +Vamos fazer algumas alterações e commitar novamente: [source,console] ---- @@ -160,17 +160,17 @@ $ vim test.rb $ git commit -a -m 'Make other changes' ---- -Now your project history has diverged (see <>). -You created and switched to a branch, did some work on it, and then switched back to your main branch and did other work. -Both of those changes are isolated in separate branches: you can switch back and forth between the branches and merge them together when you're ready. -And you did all that with simple `branch`, `checkout`, and `commit` commands. +Agora o histórico do seu projeto divergiu (veja <>). +Você criou e mudou para um branch, fez algum trabalho nele, e então mudou de volta para o seu branch principal e fez outro trabalho. +Ambas as alterações estão isoladas em branches separados: você pode alternar entre os branches e mesclá-los quando estiver pronto. +E você fez tudo isso com simples comandos `branch`, `checkout` e `commit`. [[divergent_history]] -.Divergent history -image::images/advance-master.png[Divergent history] +.Histórico divergente +image::images/advance-master.png[Histórico divergente] -You can also see this easily with the `git log` command. -If you run `git log --oneline --decorate --graph --all` it will print out the history of your commits, showing where your branch pointers are and how your history has diverged. +Você também pode ver isso facilmente com o comando `git log`. +Se você executar `git log --oneline --decorate --graph --all` ele imprimirá o histórico de seus commits, mostrando onde estão os ponteiros do seu branch e como o seu histórico divergiu. [source,console] ---- @@ -183,28 +183,28 @@ $ git log --oneline --decorate --graph --all * 98ca9 Initial commit of my project ---- -Because a branch in Git is actually a simple file that contains the 40 character SHA-1 checksum of the commit it points to, branches are cheap to create and destroy. -Creating a new branch is as quick and simple as writing 41 bytes to a file (40 characters and a newline). +Como um branch no Git é na verdade um arquivo simples que contém o checksum SHA-1 de 40 caracteres do commit para o qual ele aponta, os branches são baratos de criar e destruir. +Criar um novo branch é tão rápido e simples quanto gravar 41 bytes em um arquivo (40 caracteres e uma nova linha). -This is in sharp contrast to the way most older VCS tools branch, which involves copying all of the project's files into a second directory. -This can take several seconds or even minutes, depending on the size of the project, whereas in Git the process is always instantaneous. -Also, because we're recording the parents when we commit, finding a proper merge base for merging is automatically done for us and is generally very easy to do. -These features help encourage developers to create and use branches often. +Isso está em nítido contraste com a maneira como a maioria das ferramentas de VCS mais antigas ramificam (branch), o que envolve copiar todos os arquivos do projeto para um segundo diretório. +Isso pode levar alguns segundos ou até minutos, dependendo do tamanho do projeto, enquanto que no Git o processo é sempre instantâneo. +Além disso, como estamos registrando os pais quando fazemos o commit, encontrar uma base de mesclagem (merge base) adequada para a mesclagem é feito automaticamente para nós e geralmente é muito fácil de fazer. +Esses recursos ajudam a incentivar os desenvolvedores a criar e usar branches com frequência. -Let's see why you should do so. +Vamos ver por que você deve fazer isso. [NOTE] -.Creating a new branch and switching to it at the same time +.Criando um novo branch e mudando para ele ao mesmo tempo ==== -It's typical to create a new branch and want to switch to that new branch at the same time -- this can be done in one operation with `git checkout -b `. +É comum criar um novo branch e querer mudar para ele ao mesmo tempo -- isso pode ser feito em uma única operação com `git checkout -b `. ==== [NOTE] ==== -From Git version 2.23 onwards you can use `git switch` instead of `git checkout` to: +A partir do Git versão 2.23 em diante, você pode usar `git switch` em vez de `git checkout` para: -- Switch to an existing branch: `git switch testing-branch`. -- Create a new branch and switch to it: `git switch -c new-branch`. - The `-c` flag stands for create, you can also use the full flag: `--create`. -- Return to your previously checked out branch: `git switch -`. +- Mudar para um branch existente: `git switch testing-branch`. +- Criar um novo branch e mudar para ele: `git switch -c new-branch`. + A flag `-c` significa create (criar), você também pode usar a flag completa: `--create`. +- Retornar ao branch do qual você fez checkout anteriormente: `git switch -`. ==== diff --git a/book/03-git-branching/sections/rebasing.asc b/book/03-git-branching/sections/rebasing.asc index c6653524..c5387897 100644 --- a/book/03-git-branching/sections/rebasing.asc +++ b/book/03-git-branching/sections/rebasing.asc @@ -1,29 +1,29 @@ [[_rebasing]] -=== Rebasing +=== Rebase (Rebasing) (((rebasing))) -In Git, there are two main ways to integrate changes from one branch into another: the `merge` and the `rebase`. -In this section you'll learn what rebasing is, how to do it, why it's a pretty amazing tool, and in what cases you won't want to use it. +No Git, existem duas maneiras principais de integrar as alterações de um branch em outro: o `merge` (mesclagem) e o `rebase` (rebaseamento). +Nesta seção, você aprenderá o que é o rebase, como fazê-lo, por que é uma ferramenta tão incrível e em quais casos você não vai querer usá-lo. -==== The Basic Rebase +==== O Rebase Básico -If you go back to an earlier example from <<_basic_merging>>, you can see that you diverged your work and made commits on two different branches. +Se você voltar a um exemplo anterior em <<_basic_merging>>, você pode ver que você divergiu o seu trabalho e fez commits em dois branches diferentes. -.Simple divergent history -image::images/basic-rebase-1.png[Simple divergent history] +.Histórico divergente simples +image::images/basic-rebase-1.png[Histórico divergente simples] -The easiest way to integrate the branches, as we've already covered, is the `merge` command. -It performs a three-way merge between the two latest branch snapshots (`C3` and `C4`) and the most recent common ancestor of the two (`C2`), creating a new snapshot (and commit). +A maneira mais fácil de integrar os branches, como já abordamos, é com o comando `merge`. +Ele executa uma mesclagem de três vias (three-way merge) entre os dois snapshots (instantâneos) de branch mais recentes (`C3` e `C4`) e o ancestral comum mais recente dos dois (`C2`), criando um novo snapshot (e commit). [[rebasing-merging-example]] -.Merging to integrate diverged work history -image::images/basic-rebase-2.png[Merging to integrate diverged work history] +.Mesclando (Merging) para integrar histórico de trabalho divergente +image::images/basic-rebase-2.png[Mesclando (Merging) para integrar histórico de trabalho divergente] -However, there is another way: you can take the patch of the change that was introduced in `C4` and reapply it on top of `C3`. -In Git, this is called _rebasing_. -With the `rebase` command, you can take all the changes that were committed on one branch and replay them on a different branch.(((git commands, rebase))) +No entanto, há outra maneira: você pode pegar o patch da alteração que foi introduzida no `C4` e reaplicá-lo no topo do `C3`. +No Git, isso é chamado de _rebasing_ (rebaseamento). +Com o comando `rebase`, você pode pegar todas as alterações que foram comitadas em um branch e repeti-las (replay) em um branch diferente.(((git commands, rebase))) -For this example, you would check out the `experiment` branch, and then rebase it onto the `master` branch as follows: +Para este exemplo, você faria o checkout do branch `experiment` e então faria o rebase dele no branch `master` da seguinte maneira: [source,console] ---- @@ -33,12 +33,12 @@ First, rewinding head to replay your work on top of it... Applying: added staged command ---- -This operation works by going to the common ancestor of the two branches (the one you're on and the one you're rebasing onto), getting the diff introduced by each commit of the branch you're on, saving those diffs to temporary files, resetting the current branch to the same commit as the branch you are rebasing onto, and finally applying each change in turn. +Essa operação funciona indo ao ancestral comum dos dois branches (aquele em que você está e aquele para o qual você está fazendo o rebase), obtendo o diff introduzido por cada commit do branch em que você está, salvando esses diffs em arquivos temporários, redefinindo (resetting) o branch atual para o mesmo commit do branch para o qual você está fazendo o rebase e, finalmente, aplicando cada alteração uma por uma. -.Rebasing the change introduced in `C4` onto `C3` -image::images/basic-rebase-3.png[Rebasing the change introduced in `C4` onto `C3`] +.Fazendo o rebase da alteração introduzida em `C4` no `C3` +image::images/basic-rebase-3.png[Fazendo o rebase da alteração introduzida em `C4` no `C3`] -At this point, you can go back to the `master` branch and do a fast-forward merge. +Neste ponto, você pode voltar ao branch `master` e fazer uma mesclagem de avanço rápido (fast-forward merge). [source,console] ---- @@ -46,47 +46,47 @@ $ git checkout master $ git merge experiment ---- -.Fast-forwarding the `master` branch -image::images/basic-rebase-4.png[Fast-forwarding the `master` branch] +.Avanço rápido (Fast-forwarding) do branch `master` +image::images/basic-rebase-4.png[Avanço rápido (Fast-forwarding) do branch `master`] -Now, the snapshot pointed to by `C4'` is exactly the same as the one that was pointed to by `C5` in <>. -There is no difference in the end product of the integration, but rebasing makes for a cleaner history. -If you examine the log of a rebased branch, it looks like a linear history: it appears that all the work happened in series, even when it originally happened in parallel. +Agora, o snapshot apontado por `C4'` é exatamente o mesmo que o apontado por `C5` no <>. +Não há diferença no produto final da integração, mas o rebase proporciona um histórico mais limpo. +Se você examinar o log de um branch com rebase, ele se parece com um histórico linear: parece que todo o trabalho aconteceu em série, mesmo quando originalmente aconteceu em paralelo. -Often, you'll do this to make sure your commits apply cleanly on a remote branch -- perhaps in a project to which you're trying to contribute but that you don't maintain. -In this case, you'd do your work in a branch and then rebase your work onto `origin/master` when you were ready to submit your patches to the main project. -That way, the maintainer doesn't have to do any integration work -- just a fast-forward or a clean apply. +Geralmente, você fará isso para garantir que os seus commits sejam aplicados de forma limpa em um branch remoto -- talvez em um projeto para o qual você esteja tentando contribuir, mas que não mantém. +Neste caso, você faria o seu trabalho em um branch e então faria o rebase do seu trabalho em `origin/master` quando estivesse pronto para enviar os seus patches para o projeto principal. +Dessa forma, o mantenedor não precisa fazer nenhum trabalho de integração -- apenas um avanço rápido (fast-forward) ou uma aplicação limpa. -Note that the snapshot pointed to by the final commit you end up with, whether it's the last of the rebased commits for a rebase or the final merge commit after a merge, is the same snapshot -- it's only the history that is different. -Rebasing replays changes from one line of work onto another in the order they were introduced, whereas merging takes the endpoints and merges them together. +Observe que o snapshot apontado pelo commit final que você obtém, seja ele o último dos commits rebaseados para um rebase ou o commit de mesclagem (merge) final após um merge, é o mesmo snapshot -- apenas o histórico é diferente. +O rebase repete (replays) as alterações de uma linha de trabalho para outra na ordem em que foram introduzidas, ao passo que a mesclagem (merging) pega os pontos finais e os mescla. -==== More Interesting Rebases +==== Rebases Mais Interessantes -You can also have your rebase replay on something other than the rebase target branch. -Take a history like <>, for example. -You branched a topic branch (`server`) to add some server-side functionality to your project, and made a commit. -Then, you branched off that to make the client-side changes (`client`) and committed a few times. -Finally, you went back to your `server` branch and did a few more commits. +Você também pode fazer com que o seu rebase seja repetido (replay) em algo diferente do branch de destino do rebase. +Pegue um histórico como o <>, por exemplo. +Você ramificou (branched) um branch de tópico (`server`) para adicionar algumas funcionalidades do lado do servidor ao seu projeto e fez um commit. +Em seguida, você ramificou a partir dele para fazer as alterações no lado do cliente (`client`) e fez alguns commits. +Por fim, você voltou ao seu branch `server` e fez mais alguns commits. [[rbdiag_e]] -.A history with a topic branch off another topic branch -image::images/interesting-rebase-1.png[A history with a topic branch off another topic branch] +.Um histórico com um branch de tópico ramificado de outro branch de tópico +image::images/interesting-rebase-1.png[Um histórico com um branch de tópico ramificado de outro branch de tópico] -Suppose you decide that you want to merge your client-side changes into your mainline for a release, but you want to hold off on the server-side changes until it's tested further. -You can take the changes on `client` that aren't on `server` (`C8` and `C9`) and replay them on your `master` branch by using the `--onto` option of `git rebase`: +Suponha que você decida que deseja mesclar as suas alterações no lado do cliente na sua linha principal (mainline) para um lançamento (release), mas deseja adiar as alterações no lado do servidor até que elas sejam mais testadas. +Você pode pegar as alterações no `client` que não estão no `server` (`C8` e `C9`) e repeti-las (replay) no seu branch `master` usando a opção `--onto` do `git rebase`: [source,console] ---- $ git rebase --onto master server client ---- -This basically says, "`Take the `client` branch, figure out the patches since it diverged from the `server` branch, and replay these patches in the `client` branch as if it was based directly off the `master` branch instead.`" -It's a bit complex, but the result is pretty cool. +Isso basicamente diz: "`Pegue o branch `client`, descubra os patches desde que ele divergiu do branch `server` e repita (replay) esses patches no branch `client` como se ele fosse baseado diretamente no branch `master`.`" +É um pouco complexo, mas o resultado é muito legal. -.Rebasing a topic branch off another topic branch -image::images/interesting-rebase-2.png[Rebasing a topic branch off another topic branch] +.Fazendo o rebase de um branch de tópico a partir de outro branch de tópico +image::images/interesting-rebase-2.png[Fazendo o rebase de um branch de tópico a partir de outro branch de tópico] -Now you can fast-forward your `master` branch (see <>): +Agora você pode fazer o avanço rápido (fast-forward) do seu branch `master` (consulte <>): [source,console] ---- @@ -95,24 +95,24 @@ $ git merge client ---- [[rbdiag_g]] -.Fast-forwarding your `master` branch to include the `client` branch changes -image::images/interesting-rebase-3.png[Fast-forwarding your `master` branch to include the `client` branch changes] +.Avanço rápido (Fast-forwarding) do seu branch `master` para incluir as alterações do branch `client` +image::images/interesting-rebase-3.png[Avanço rápido (Fast-forwarding) do seu branch `master` para incluir as alterações do branch `client`] -Let's say you decide to pull in your `server` branch as well. -You can rebase the `server` branch onto the `master` branch without having to check it out first by running `git rebase ` -- which checks out the topic branch (in this case, `server`) for you and replays it onto the base branch (`master`): +Digamos que você decida fazer o pull do seu branch `server` também. +Você pode fazer o rebase do branch `server` no branch `master` sem precisar fazer o checkout dele primeiro executando `git rebase ` -- que faz o checkout do branch de tópico (neste caso, `server`) para você e o repete (replays) no branch base (`master`): [source,console] ---- $ git rebase master server ---- -This replays your `server` work on top of your `master` work, as shown in <>. +Isso repete (replays) o seu trabalho do `server` sobre o seu trabalho do `master`, como mostrado em <>. [[rbdiag_h]] -.Rebasing your `server` branch on top of your `master` branch -image::images/interesting-rebase-4.png[Rebasing your `server` branch on top of your `master` branch] +.Fazendo o rebase do seu branch `server` sobre o seu branch `master` +image::images/interesting-rebase-4.png[Fazendo o rebase do seu branch `server` sobre o seu branch `master`] -Then, you can fast-forward the base branch (`master`): +Em seguida, você pode fazer o avanço rápido (fast-forward) do branch base (`master`): [source,console] ---- @@ -120,7 +120,7 @@ $ git checkout master $ git merge server ---- -You can remove the `client` and `server` branches because all the work is integrated and you don't need them anymore, leaving your history for this entire process looking like <>: +Você pode remover os branches `client` e `server` porque todo o trabalho está integrado e você não precisa mais deles, deixando o seu histórico de todo este processo parecido com o <>: [source,console] ---- @@ -129,112 +129,112 @@ $ git branch -d server ---- [[rbdiag_i]] -.Final commit history -image::images/interesting-rebase-5.png[Final commit history] +.Histórico de commits final +image::images/interesting-rebase-5.png[Histórico de commits final] [[_rebase_peril]] -==== The Perils of Rebasing +==== Os Perigos do Rebase (Perils of Rebasing) (((rebasing, perils of))) -Ahh, but the bliss of rebasing isn't without its drawbacks, which can be summed up in a single line: +Ahh, mas a alegria do rebase não existe sem suas desvantagens, que podem ser resumidas em uma única linha: -*Do not rebase commits that exist outside your repository and that people may have based work on.* +*Não faça rebase de commits que existem fora do seu repositório e nos quais as pessoas possam ter baseado o trabalho delas.* -If you follow that guideline, you'll be fine. -If you don't, people will hate you, and you'll be scorned by friends and family. +Se você seguir essa diretriz, ficará tudo bem. +Se não o fizer, as pessoas o odiarão, e você será desprezado por amigos e familiares. -When you rebase stuff, you're abandoning existing commits and creating new ones that are similar but different. -If you push commits somewhere and others pull them down and base work on them, and then you rewrite those commits with `git rebase` and push them up again, your collaborators will have to re-merge their work and things will get messy when you try to pull their work back into yours. +Quando você faz rebase de coisas, você está abandonando os commits existentes e criando novos que são parecidos, mas diferentes. +Se você fizer o push de commits para algum lugar e outras pessoas fizerem o pull deles (pull down) e basearem o trabalho neles, e então você reescrever esses commits com o `git rebase` e fizer o push deles novamente, os seus colaboradores terão que mesclar (re-merge) o trabalho deles novamente e as coisas ficarão bagunçadas quando você tentar fazer o pull do trabalho deles de volta para o seu. -Let's look at an example of how rebasing work that you've made public can cause problems. -Suppose you clone from a central server and then do some work off that. -Your commit history looks like this: +Vejamos um exemplo de como fazer o rebase de um trabalho que você tornou público pode causar problemas. +Suponha que você clone de um servidor central e faça algum trabalho a partir dele. +O seu histórico de commits fica assim: -.Clone a repository, and base some work on it -image::images/perils-of-rebasing-1.png["Clone a repository, and base some work on it"] +.Clonar um repositório e basear algum trabalho nele +image::images/perils-of-rebasing-1.png["Clonar um repositório e basear algum trabalho nele"] -Now, someone else does more work that includes a merge, and pushes that work to the central server. -You fetch it and merge the new remote branch into your work, making your history look something like this: +Agora, outra pessoa faz mais trabalho que inclui uma mesclagem (merge) e faz o push desse trabalho para o servidor central. +Você faz um fetch e mescla (merge) o novo branch remoto no seu trabalho, fazendo com que o seu histórico fique parecido com isto: -.Fetch more commits, and merge them into your work -image::images/perils-of-rebasing-2.png["Fetch more commits, and merge them into your work"] +.Buscar (Fetch) mais commits e mesclá-los (merge) no seu trabalho +image::images/perils-of-rebasing-2.png["Buscar (Fetch) mais commits e mesclá-los (merge) no seu trabalho"] -Next, the person who pushed the merged work decides to go back and rebase their work instead; they do a `git push --force` to overwrite the history on the server. -You then fetch from that server, bringing down the new commits. +A seguir, a pessoa que fez o push do trabalho mesclado decide voltar e, em vez disso, fazer o rebase do trabalho dela; ela faz um `git push --force` para substituir o histórico no servidor. +Você então faz um fetch desse servidor, baixando os novos commits. [[_pre_merge_rebase_work]] -.Someone pushes rebased commits, abandoning commits you've based your work on -image::images/perils-of-rebasing-3.png["Someone pushes rebased commits, abandoning commits you've based your work on"] +.Alguém envia (pushes) commits em rebase, abandonando os commits nos quais você baseou o seu trabalho +image::images/perils-of-rebasing-3.png["Alguém envia (pushes) commits em rebase, abandonando os commits nos quais você baseou o seu trabalho"] -Now you're both in a pickle. -If you do a `git pull`, you'll create a merge commit which includes both lines of history, and your repository will look like this: +Agora vocês dois estão em apuros. +Se você fizer um `git pull`, você criará um commit de mesclagem (merge) que inclui ambas as linhas de histórico e o seu repositório ficará assim: [[_merge_rebase_work]] -.You merge in the same work again into a new merge commit -image::images/perils-of-rebasing-4.png[You merge in the same work again into a new merge commit] +.Você mescla (merge in) o mesmo trabalho novamente em um novo commit de mesclagem (merge commit) +image::images/perils-of-rebasing-4.png[Você mescla (merge in) o mesmo trabalho novamente em um novo commit de mesclagem (merge commit)] -If you run a `git log` when your history looks like this, you'll see two commits that have the same author, date, and message, which will be confusing. -Furthermore, if you push this history back up to the server, you'll reintroduce all those rebased commits to the central server, which can further confuse people. -It's pretty safe to assume that the other developer doesn't want `C4` and `C6` to be in the history; that's why they rebased in the first place. +Se você executar um `git log` quando o seu histórico estiver assim, você verá dois commits que têm o mesmo autor, data e mensagem, o que será confuso. +Além disso, se você fizer o push desse histórico de volta para o servidor, você reintroduzirá todos esses commits com rebase no servidor central, o que pode confundir ainda mais as pessoas. +É bastante seguro supor que o outro desenvolvedor não deseja que `C4` e `C6` estejam no histórico; foi por isso que ele fez o rebase em primeiro lugar. [[_rebase_rebase]] -==== Rebase When You Rebase +==== Rebase Quando Você Fizer Rebase -If you *do* find yourself in a situation like this, Git has some further magic that might help you out. -If someone on your team force pushes changes that overwrite work that you've based work on, your challenge is to figure out what is yours and what they've rewritten. +Se você *se* encontrar em uma situação como esta, o Git tem um pouco mais de mágica que pode ajudá-lo. +Se alguém na sua equipe forçar o push de alterações que substituem um trabalho no qual você baseou o seu trabalho, o seu desafio é descobrir o que é seu e o que foi reescrito. -It turns out that in addition to the commit SHA-1 checksum, Git also calculates a checksum that is based just on the patch introduced with the commit. -This is called a "`patch-id`". +Acontece que, além da soma de verificação (checksum) SHA-1 do commit, o Git também calcula um checksum baseado apenas no patch introduzido com o commit. +Isso é chamado de "`patch-id`". -If you pull down work that was rewritten and rebase it on top of the new commits from your partner, Git can often successfully figure out what is uniquely yours and apply them back on top of the new branch. +Se você fizer o pull de um trabalho que foi reescrito e fizer o rebase no topo dos novos commits do seu parceiro, o Git geralmente consegue descobrir com sucesso o que é exclusivamente seu e aplicá-lo novamente no topo do novo branch. -For instance, in the previous scenario, if instead of doing a merge when we're at <<_pre_merge_rebase_work>> we run `git rebase teamone/master`, Git will: +Por exemplo, no cenário anterior, se, em vez de fazer uma mesclagem (merge) quando estamos em <<_pre_merge_rebase_work>>, executarmos `git rebase teamone/master`, o Git irá: -* Determine what work is unique to our branch (`C2`, `C3`, `C4`, `C6`, `C7`) -* Determine which are not merge commits (`C2`, `C3`, `C4`) -* Determine which have not been rewritten into the target branch (just `C2` and `C3`, since `C4` is the same patch as `C4'`) -* Apply those commits to the top of `teamone/master` +* Determinar qual trabalho é exclusivo do nosso branch (`C2`, `C3`, `C4`, `C6`, `C7`) +* Determinar quais não são commits de mesclagem (merge commits) (`C2`, `C3`, `C4`) +* Determinar quais não foram reescritos no branch de destino (apenas `C2` e `C3`, já que `C4` é o mesmo patch que `C4'`) +* Aplicar esses commits no topo de `teamone/master` -So instead of the result we see in <<_merge_rebase_work>>, we would end up with something more like <<_rebase_rebase_work>>. +Então, em vez do resultado que vemos em <<_merge_rebase_work>>, terminaríamos com algo mais parecido com <<_rebase_rebase_work>>. [[_rebase_rebase_work]] -.Rebase on top of force-pushed rebase work -image::images/perils-of-rebasing-5.png[Rebase on top of force-pushed rebase work] +.Rebase no topo do trabalho com rebase e push forçado +image::images/perils-of-rebasing-5.png[Rebase no topo do trabalho com rebase e push forçado] -This only works if `C4` and `C4'` that your partner made are almost exactly the same patch. -Otherwise the rebase won't be able to tell that it's a duplicate and will add another `C4`-like patch (which will probably fail to apply cleanly, since the changes would already be at least somewhat there). +Isso só funciona se o `C4` e o `C4'` que o seu parceiro fez forem quase exatamente o mesmo patch. +Caso contrário, o rebase não conseguirá perceber que se trata de uma duplicata e adicionará outro patch semelhante a `C4` (que provavelmente falhará ao ser aplicado de forma limpa, já que as alterações já estariam lá pelo menos em parte). -You can also simplify this by running a `git pull --rebase` instead of a normal `git pull`. -Or you could do it manually with a `git fetch` followed by a `git rebase teamone/master` in this case. +Você também pode simplificar isso executando um `git pull --rebase` em vez de um `git pull` normal. +Ou você pode fazer isso manualmente com um `git fetch` seguido por um `git rebase teamone/master`, neste caso. -If you are using `git pull` and want to make `--rebase` the default, you can set the `pull.rebase` config value with something like `git config --global pull.rebase true`. +Se você está usando `git pull` e deseja tornar `--rebase` o padrão, você pode definir o valor de configuração `pull.rebase` com algo como `git config --global pull.rebase true`. -If you only ever rebase commits that have never left your own computer, you'll be just fine. -If you rebase commits that have been pushed, but that no one else has based commits from, you'll also be fine. -If you rebase commits that have already been pushed publicly, and people may have based work on those commits, then you may be in for some frustrating trouble, and the scorn of your teammates. +Se você fizer o rebase apenas de commits que nunca saíram do seu próprio computador, tudo ficará bem. +Se você fizer o rebase de commits que foram enviados (pushed), mas que ninguém mais baseou os seus commits neles, você também ficará bem. +Se você fizer rebase de commits que já foram enviados publicamente e as pessoas possam ter baseado trabalho nesses commits, então você poderá ter alguns problemas frustrantes e o desprezo dos seus colegas de equipe. -If you or a partner does find it necessary at some point, make sure everyone knows to run `git pull --rebase` to try to make the pain after it happens a little bit simpler. +Se você ou um parceiro achar necessário em algum momento, certifique-se de que todos saibam que devem executar `git pull --rebase` para tentar tornar a dor um pouco mais simples depois que isso acontecer. -==== Rebase vs. Merge +==== Rebase vs. Mesclar (Merge) (((rebasing, vs. merging)))(((merging, vs. rebasing))) -Now that you've seen rebasing and merging in action, you may be wondering which one is better. -Before we can answer this, let's step back a bit and talk about what history means. - -One point of view on this is that your repository's commit history is a *record of what actually happened.* -It's a historical document, valuable in its own right, and shouldn't be tampered with. -From this angle, changing the commit history is almost blasphemous; you're _lying_ about what actually transpired. -So what if there was a messy series of merge commits? -That's how it happened, and the repository should preserve that for posterity. - -The opposing point of view is that the commit history is the *story of how your project was made.* -You wouldn't publish the first draft of a book, so why show your messy work? -When you're working on a project, you may need a record of all your missteps and dead-end paths, but when it's time to show your work to the world, you may want to tell a more coherent story of how to get from A to B. -People in this camp use tools like `rebase` and `filter-branch` to rewrite their commits before they're merged into the mainline branch. -They use tools like `rebase` and `filter-branch`, to tell the story in the way that's best for future readers. - -Now, to the question of whether merging or rebasing is better: hopefully you'll see that it's not that simple. -Git is a powerful tool, and allows you to do many things to and with your history, but every team and every project is different. -Now that you know how both of these things work, it's up to you to decide which one is best for your particular situation. - -You can get the best of both worlds: rebase local changes before pushing to clean up your work, but never rebase anything that you've pushed somewhere. +Agora que você viu o rebase e o merge em ação, você pode estar se perguntando qual deles é o melhor. +Antes de respondermos a isso, vamos dar um passo atrás e falar sobre o que significa o histórico. + +Um ponto de vista sobre isso é que o histórico de commits do seu repositório é um *registro do que realmente aconteceu.* +É um documento histórico, valioso por si só, e não deve ser adulterado. +Desse ângulo, alterar o histórico de commits é quase uma blasfêmia; você está _mentindo_ sobre o que realmente aconteceu. +E daí se houve uma série bagunçada de commits de mesclagem (merge)? +Foi assim que aconteceu, e o repositório deve preservar isso para a posteridade. + +O ponto de vista oposto é que o histórico de commits é a *história de como o seu projeto foi feito.* +Você não publicaria o primeiro rascunho de um livro, então por que mostrar o seu trabalho bagunçado? +Ao trabalhar em um projeto, você pode precisar de um registro de todos os seus erros e becos sem saída, mas quando chegar a hora de mostrar o seu trabalho ao mundo, você pode querer contar uma história mais coerente de como ir de A a B. +As pessoas nesse campo (camp) usam ferramentas como `rebase` e `filter-branch` para reescrever os seus commits antes de serem mesclados (merged) no branch da linha principal (mainline). +Eles usam ferramentas como `rebase` e `filter-branch` para contar a história da maneira que for melhor para os futuros leitores. + +Agora, sobre a questão de saber se mesclar (merging) ou fazer rebase é melhor: esperamos que você perceba que não é tão simples. +O Git é uma ferramenta poderosa e permite que você faça muitas coisas no seu histórico e com ele, mas cada equipe e cada projeto são diferentes. +Agora que você sabe como as duas coisas funcionam, cabe a você decidir qual é a melhor para a sua situação em particular. + +Você pode obter o melhor dos dois mundos: faça o rebase das alterações locais antes de enviar (pushing) para limpar o seu trabalho, mas nunca faça o rebase de nada que você já tenha enviado (pushed) para algum lugar. diff --git a/book/03-git-branching/sections/remote-branches.asc b/book/03-git-branching/sections/remote-branches.asc index adbb8735..ac9cfa45 100644 --- a/book/03-git-branching/sections/remote-branches.asc +++ b/book/03-git-branching/sections/remote-branches.asc @@ -1,71 +1,71 @@ [[_remote_branches]] -=== Remote Branches +=== Branches Remotos (Remote Branches) (((branches, remote)))(((references, remote))) -Remote references are references (pointers) in your remote repositories, including branches, tags, and so on. -You can get a full list of remote references explicitly with `git ls-remote `, or `git remote show ` for remote branches as well as more information. -Nevertheless, a more common way is to take advantage of remote-tracking branches. +Referências remotas são referências (ponteiros) nos seus repositórios remotos, incluindo branches, tags e assim por diante. +Você pode obter uma lista completa de referências remotas explicitamente com `git ls-remote `, ou `git remote show ` para branches remotos, bem como mais informações. +No entanto, uma maneira mais comum é aproveitar os branches de rastreamento remoto (remote-tracking branches). -Remote-tracking branches are references to the state of remote branches. -They're local references that you can't move; Git moves them for you whenever you do any network communication, to make sure they accurately represent the state of the remote repository. -Think of them as bookmarks, to remind you where the branches in your remote repositories were the last time you connected to them. +Branches de rastreamento remoto são referências ao estado dos branches remotos. +Eles são referências locais que você não pode mover; o Git os move para você sempre que você faz qualquer comunicação de rede, para garantir que eles representem com precisão o estado do repositório remoto. +Pense neles como favoritos, para lembrá-lo de onde estavam os branches nos seus repositórios remotos da última vez que você se conectou a eles. -Remote-tracking branch names take the form `/`. -For instance, if you wanted to see what the `master` branch on your `origin` remote looked like as of the last time you communicated with it, you would check the `origin/master` branch. -If you were working on an issue with a partner and they pushed up an `iss53` branch, you might have your own local `iss53` branch, but the branch on the server would be represented by the remote-tracking branch `origin/iss53`. +Nomes de branches de rastreamento remoto assumem a forma `/`. +Por exemplo, se você quisesse ver como o branch `master` no seu remoto `origin` estava da última vez que você se comunicou com ele, você verificaria o branch `origin/master`. +Se você estivesse trabalhando em uma issue com um parceiro e ele fizesse o push de um branch `iss53`, você poderia ter o seu próprio branch local `iss53`, mas o branch no servidor seria representado pelo branch de rastreamento remoto `origin/iss53`. -This may be a bit confusing, so let's look at an example. -Let's say you have a Git server on your network at `git.ourcompany.com`. -If you clone from this, Git's `clone` command automatically names it `origin` for you, pulls down all its data, creates a pointer to where its `master` branch is, and names it `origin/master` locally. -Git also gives you your own local `master` branch starting at the same place as origin's `master` branch, so you have something to work from. +Isso pode ser um pouco confuso, então vamos ver um exemplo. +Digamos que você tenha um servidor Git na sua rede em `git.ourcompany.com`. +Se você clonar a partir dele, o comando `clone` do Git o nomeia automaticamente como `origin` para você, baixa todos os seus dados, cria um ponteiro para onde o branch `master` dele está e o nomeia como `origin/master` localmente. +O Git também fornece a você o seu próprio branch `master` local começando no mesmo lugar que o branch `master` do origin, para que você tenha algo a partir do qual trabalhar. [NOTE] -."`origin`" is not special +."`origin`" não é especial ==== -Just like the branch name "`master`" does not have any special meaning in Git, neither does "`origin`". -While "`master`" is the default name for a starting branch when you run `git init` which is the only reason it's widely used, "`origin`" is the default name for a remote when you run `git clone`. -If you run `git clone -o booyah` instead, then you will have `booyah/master` as your default remote branch.(((origin))) +Assim como o nome do branch "`master`" não tem nenhum significado especial no Git, o "`origin`" também não. +Enquanto "`master`" é o nome padrão para um branch inicial quando você executa o `git init`, o que é a única razão pela qual ele é amplamente utilizado, "`origin`" é o nome padrão para um remoto quando você executa o `git clone`. +Se, em vez disso, você executar `git clone -o booyah`, você terá `booyah/master` como o seu branch remoto padrão.(((origin))) ==== -.Server and local repositories after cloning -image::images/remote-branches-1.png[Server and local repositories after cloning] +.Repositórios locais e do servidor após clonar +image::images/remote-branches-1.png[Repositórios locais e do servidor após clonar] -If you do some work on your local `master` branch, and, in the meantime, someone else pushes to `git.ourcompany.com` and updates its `master` branch, then your histories move forward differently. -Also, as long as you stay out of contact with your `origin` server, your `origin/master` pointer doesn't move. +Se você fizer algum trabalho no seu branch local `master` e, nesse meio-tempo, outra pessoa fizer push para `git.ourcompany.com` e atualizar o branch `master` de lá, os seus históricos avançarão de forma diferente. +Além disso, enquanto você não se comunicar com o seu servidor `origin`, o seu ponteiro `origin/master` não se moverá. -.Local and remote work can diverge -image::images/remote-branches-2.png[Local and remote work can diverge] +.O trabalho local e o remoto podem divergir +image::images/remote-branches-2.png[O trabalho local e o remoto podem divergir] -To synchronize your work with a given remote, you run a `git fetch ` command (in our case, `git fetch origin`). -This command looks up which server "`origin`" is (in this case, it's `git.ourcompany.com`), fetches any data from it that you don't yet have, and updates your local database, moving your `origin/master` pointer to its new, more up-to-date position. +Para sincronizar o seu trabalho com um determinado remoto, você executa o comando `git fetch ` (no nosso caso, `git fetch origin`). +Esse comando verifica qual servidor é o "`origin`" (neste caso, é `git.ourcompany.com`), busca os dados que você ainda não tem e atualiza o seu banco de dados local, movendo o seu ponteiro `origin/master` para a sua posição nova e mais atualizada. -.`git fetch` updates your remote-tracking branches -image::images/remote-branches-3.png[`git fetch` updates your remote-tracking branches] +.`git fetch` atualiza os seus branches de rastreamento remoto +image::images/remote-branches-3.png[`git fetch` atualiza os seus branches de rastreamento remoto] -To demonstrate having multiple remote servers and what remote branches for those remote projects look like, let's assume you have another internal Git server that is used only for development by one of your sprint teams. -This server is at `git.team1.ourcompany.com`. -You can add it as a new remote reference to the project you're currently working on by running the `git remote add` command as we covered in <>. -Name this remote `teamone`, which will be your shortname for that whole URL. +Para demonstrar como ter vários servidores remotos e como se parecem os branches remotos para esses projetos remotos, vamos supor que você tenha outro servidor Git interno que é usado apenas para desenvolvimento por uma das suas equipes de sprint. +Este servidor está em `git.team1.ourcompany.com`. +Você pode adicioná-lo como uma nova referência remota ao projeto em que você está trabalhando atualmente executando o comando `git remote add`, conforme abordamos no <>. +Dê a este remoto o nome `teamone`, que será o seu nome abreviado (shortname) para toda a URL. -.Adding another server as a remote -image::images/remote-branches-4.png[Adding another server as a remote] +.Adicionando outro servidor como remoto +image::images/remote-branches-4.png[Adicionando outro servidor como remoto] -Now, you can run `git fetch teamone` to fetch everything the remote `teamone` server has that you don't have yet. -Because that server has a subset of the data your `origin` server has right now, Git fetches no data but sets a remote-tracking branch called `teamone/master` to point to the commit that `teamone` has as its `master` branch. +Agora, você pode executar o `git fetch teamone` para buscar tudo o que o servidor remoto `teamone` tem e que você ainda não tem. +Como esse servidor tem um subconjunto dos dados que o seu servidor `origin` tem no momento, o Git não busca dados, mas define um branch de rastreamento remoto chamado `teamone/master` para apontar para o commit que `teamone` tem como sendo o seu branch `master`. -.Remote-tracking branch for `teamone/master` -image::images/remote-branches-5.png[Remote-tracking branch for `teamone/master`] +.Branch de rastreamento remoto para `teamone/master` +image::images/remote-branches-5.png[Branch de rastreamento remoto para `teamone/master`] [[_pushing_branches]] -==== Pushing +==== Enviando (Pushing) (((pushing))) -When you want to share a branch with the world, you need to push it up to a remote to which you have write access. -Your local branches aren't automatically synchronized to the remotes you write to -- you have to explicitly push the branches you want to share. -That way, you can use private branches for work you don't want to share, and push up only the topic branches you want to collaborate on. +Quando você quiser compartilhar um branch com o mundo, você precisa fazer o push dele para um remoto no qual você tenha acesso de gravação. +Os seus branches locais não são sincronizados automaticamente com os remotos nos quais você grava -- você tem que fazer o push explicitamente dos branches que deseja compartilhar. +Dessa forma, você pode usar branches privados para trabalhos que não deseja compartilhar e fazer o push apenas dos branches de tópicos nos quais deseja colaborar. -If you have a branch named `serverfix` that you want to work on with others, you can push it up the same way you pushed your first branch. -Run `git push `:(((git commands, push))) +Se você tiver um branch chamado `serverfix` no qual deseja trabalhar com outras pessoas, você pode fazer o push dele da mesma forma que fez o push do seu primeiro branch. +Execute `git push `:(((git commands, push))) [source,console] ---- @@ -79,26 +79,26 @@ To https://github.com/schacon/simplegit * [new branch] serverfix -> serverfix ---- -This is a bit of a shortcut. -Git automatically expands the `serverfix` branchname out to `refs/heads/serverfix:refs/heads/serverfix`, which means, "`Take my `serverfix` local branch and push it to update the remote's `serverfix` branch.`" -We'll go over the `refs/heads/` part in detail in <>, but you can generally leave it off. -You can also do `git push origin serverfix:serverfix`, which does the same thing -- it says, "`Take my serverfix and make it the remote's serverfix.`" -You can use this format to push a local branch into a remote branch that is named differently. -If you didn't want it to be called `serverfix` on the remote, you could instead run `git push origin serverfix:awesomebranch` to push your local `serverfix` branch to the `awesomebranch` branch on the remote project. +Isso é um pouco de atalho. +O Git expande automaticamente o nome do branch `serverfix` para `refs/heads/serverfix:refs/heads/serverfix`, o que significa: "`Pegue meu branch local `serverfix` e faça o push para atualizar o branch `serverfix` do remoto.`" +Abordaremos a parte `refs/heads/` em detalhes em <>, mas geralmente você pode omiti-la. +Você também pode fazer `git push origin serverfix:serverfix`, que faz a mesma coisa -- ele diz: "`Pegue meu serverfix e faça dele o serverfix do remoto.`" +Você pode usar esse formato para fazer o push de um branch local em um branch remoto com nome diferente. +Se você não quisesse que ele fosse chamado de `serverfix` no remoto, você poderia executar `git push origin serverfix:awesomebranch` para fazer o push do seu branch local `serverfix` para o branch `awesomebranch` no projeto remoto. [NOTE] -.Don't type your password every time +.Não digite sua senha toda vez ==== -If you're using an HTTPS URL to push over, the Git server will ask you for your username and password for authentication. -By default it will prompt you on the terminal for this information so the server can tell if you're allowed to push. +Se você estiver usando uma URL HTTPS para fazer o push, o servidor Git solicitará o seu nome de usuário e senha para autenticação. +Por padrão, ele solicitará essas informações no terminal para que o servidor possa saber se você tem permissão para fazer o push. -If you don't want to type it every single time you push, you can set up a "`credential cache`". -The simplest is just to keep it in memory for a few minutes, which you can easily set up by running `git config --global credential.helper cache`. +Se você não quiser digitá-la todas as vezes que fizer um push, você pode configurar um "`cache de credenciais`" (credential cache). +A maneira mais simples é mantê-la na memória por alguns minutos, o que você pode configurar facilmente executando `git config --global credential.helper cache`. -For more information on the various credential caching options available, see <>. +Para obter mais informações sobre as várias opções de cache de credenciais disponíveis, consulte <>. ==== -The next time one of your collaborators fetches from the server, they will get a reference to where the server's version of `serverfix` is under the remote branch `origin/serverfix`: +Na próxima vez que um de seus colaboradores fizer um fetch do servidor, ele obterá uma referência de onde a versão do `serverfix` do servidor está no branch remoto `origin/serverfix`: [source,console] ---- @@ -111,11 +111,11 @@ From https://github.com/schacon/simplegit * [new branch] serverfix -> origin/serverfix ---- -It's important to note that when you do a fetch that brings down new remote-tracking branches, you don't automatically have local, editable copies of them. -In other words, in this case, you don't have a new `serverfix` branch -- you have only an `origin/serverfix` pointer that you can't modify. +É importante observar que, ao fazer um fetch que traz novos branches de rastreamento remoto, você não obtém automaticamente cópias locais editáveis deles. +Em outras palavras, neste caso, você não tem um novo branch `serverfix` -- você tem apenas um ponteiro `origin/serverfix` que não pode modificar. -To merge this work into your current working branch, you can run `git merge origin/serverfix`. -If you want your own `serverfix` branch that you can work on, you can base it off your remote-tracking branch: +Para mesclar (merge) esse trabalho no seu branch de trabalho atual, você pode executar `git merge origin/serverfix`. +Se você quiser o seu próprio branch `serverfix` no qual possa trabalhar, você pode baseá-lo no seu branch de rastreamento remoto: [source,console] ---- @@ -124,20 +124,20 @@ Branch serverfix set up to track remote branch serverfix from origin. Switched to a new branch 'serverfix' ---- -This gives you a local branch that you can work on that starts where `origin/serverfix` is. +Isso fornece a você um branch local no qual você pode trabalhar e que começa onde `origin/serverfix` está. [[_tracking_branches]] -==== Tracking Branches +==== Branches de Rastreamento (Tracking Branches) (((branches, tracking)))(((branches, upstream))) -Checking out a local branch from a remote-tracking branch automatically creates what is called a "`tracking branch`" (and the branch it tracks is called an "`upstream branch`"). -Tracking branches are local branches that have a direct relationship to a remote branch. -If you're on a tracking branch and type `git pull`, Git automatically knows which server to fetch from and which branch to merge in. +Fazer o checkout de um branch local a partir de um branch de rastreamento remoto cria automaticamente o que é chamado de "`branch de rastreamento`" (tracking branch) (e o branch que ele rastreia é chamado de "`branch upstream`"). +Branches de rastreamento são branches locais que têm uma relação direta com um branch remoto. +Se você estiver em um branch de rastreamento e digitar `git pull`, o Git saberá automaticamente de qual servidor buscar (fetch) e qual branch mesclar (merge in). -When you clone a repository, it generally automatically creates a `master` branch that tracks `origin/master`. -However, you can set up other tracking branches if you wish -- ones that track branches on other remotes, or don't track the `master` branch. -The simple case is the example you just saw, running `git checkout -b /`. -This is a common enough operation that Git provides the `--track` shorthand: +Quando você clona um repositório, ele geralmente cria automaticamente um branch `master` que rastreia `origin/master`. +No entanto, você pode configurar outros branches de rastreamento, se desejar -- aqueles que rastreiam branches em outros remotos, ou não rastreiam o branch `master`. +O caso simples é o exemplo que você acabou de ver, executando `git checkout -b /`. +Esta é uma operação comum o suficiente para que o Git forneça o atalho `--track`: [source,console] ---- @@ -146,8 +146,8 @@ Branch serverfix set up to track remote branch serverfix from origin. Switched to a new branch 'serverfix' ---- -In fact, this is so common that there's even a shortcut for that shortcut. -If the branch name you're trying to checkout (a) doesn't exist and (b) exactly matches a name on only one remote, Git will create a tracking branch for you: +Na verdade, isso é tão comum que há até um atalho para esse atalho. +Se o nome do branch que você está tentando fazer checkout (a) não existir e (b) corresponder exatamente a um nome em apenas um remoto, o Git criará um branch de rastreamento para você: [source,console] ---- @@ -156,7 +156,7 @@ Branch serverfix set up to track remote branch serverfix from origin. Switched to a new branch 'serverfix' ---- -To set up a local branch with a different name than the remote branch, you can easily use the first version with a different local branch name: +Para configurar um branch local com um nome diferente do branch remoto, você pode usar facilmente a primeira versão com um nome de branch local diferente: [source,console] ---- @@ -165,9 +165,9 @@ Branch sf set up to track remote branch serverfix from origin. Switched to a new branch 'sf' ---- -Now, your local branch `sf` will automatically pull from `origin/serverfix`. +Agora, o seu branch local `sf` fará o pull automaticamente de `origin/serverfix`. -If you already have a local branch and want to set it to a remote branch you just pulled down, or want to change the upstream branch you're tracking, you can use the `-u` or `--set-upstream-to` option to `git branch` to explicitly set it at any time. +Se você já tem um branch local e deseja defini-lo para um branch remoto do qual você acabou de fazer o pull (pulled down), ou deseja alterar o branch upstream que você está rastreando, você pode usar a opção `-u` ou `--set-upstream-to` para `git branch` para defini-lo explicitamente a qualquer momento. [source,console] ---- @@ -176,14 +176,14 @@ Branch serverfix set up to track remote branch serverfix from origin. ---- [NOTE] -.Upstream shorthand +.Atalho Upstream ==== -When you have a tracking branch set up, you can reference its upstream branch with the `@{upstream}` or `@{u}` shorthand. -So if you're on the `master` branch and it's tracking `origin/master`, you can say something like `git merge @{u}` instead of `git merge origin/master` if you wish.(((@{u})))(((@{upstream}))) +Quando você tem um branch de rastreamento configurado, você pode referenciar o seu branch upstream com o atalho `@{upstream}` ou `@{u}`. +Portanto, se você estiver no branch `master` e ele estiver rastreando `origin/master`, você pode dizer algo como `git merge @{u}` em vez de `git merge origin/master` se desejar.(((@{u})))(((@{upstream}))) ==== -If you want to see what tracking branches you have set up, you can use the `-vv` option to `git branch`. -This will list out your local branches with more information including what each branch is tracking and if your local branch is ahead, behind or both. +Se você quiser ver quais branches de rastreamento você configurou, você pode usar a opção `-vv` do `git branch`. +Isso listará os seus branches locais com mais informações, incluindo o que cada branch está rastreando e se o seu branch local está à frente (ahead), atrás (behind) ou ambos. [source,console] ---- @@ -194,36 +194,36 @@ $ git branch -vv testing 5ea463a Try something new ---- -So here we can see that our `iss53` branch is tracking `origin/iss53` and is "`ahead`" by two, meaning that we have two commits locally that are not pushed to the server. -We can also see that our `master` branch is tracking `origin/master` and is up to date. -Next we can see that our `serverfix` branch is tracking the `server-fix-good` branch on our `teamone` server and is ahead by three and behind by one, meaning that there is one commit on the server we haven't merged in yet and three commits locally that we haven't pushed. -Finally we can see that our `testing` branch is not tracking any remote branch. +Então, aqui podemos ver que o nosso branch `iss53` está rastreando `origin/iss53` e está "`à frente`" (ahead) por dois, o que significa que temos dois commits localmente que não foram enviados (pushed) para o servidor. +Também podemos ver que o nosso branch `master` está rastreando `origin/master` e está atualizado. +A seguir, podemos ver que o nosso branch `serverfix` está rastreando o branch `server-fix-good` no nosso servidor `teamone` e está à frente por três e atrás (behind) por um, o que significa que há um commit no servidor que ainda não mesclamos (merged in) e três commits localmente que não fizemos o push. +Finalmente, podemos ver que o nosso branch `testing` não está rastreando nenhum branch remoto. -It's important to note that these numbers are only since the last time you fetched from each server. -This command does not reach out to the servers, it's telling you about what it has cached from these servers locally. -If you want totally up to date ahead and behind numbers, you'll need to fetch from all your remotes right before running this. -You could do that like this: +É importante observar que esses números são apenas desde a última vez que você fez um fetch de cada servidor. +Esse comando não chega aos servidores, ele está dizendo o que tem em cache desses servidores localmente. +Se você deseja números totalmente atualizados sobre o que está à frente e atrás, você precisará fazer um fetch de todos os seus remotos logo antes de executar isso. +Você pode fazer isso assim: [source,console] ---- $ git fetch --all; git branch -vv ---- -==== Pulling +==== Obtendo (Pulling) (((pulling))) -While the `git fetch` command will fetch all the changes on the server that you don't have yet, it will not modify your working directory at all. -It will simply get the data for you and let you merge it yourself. -However, there is a command called `git pull` which is essentially a `git fetch` immediately followed by a `git merge` in most cases. -If you have a tracking branch set up as demonstrated in the last section, either by explicitly setting it or by having it created for you by the `clone` or `checkout` commands, `git pull` will look up what server and branch your current branch is tracking, fetch from that server and then try to merge in that remote branch. +Embora o comando `git fetch` busque todas as alterações no servidor que você ainda não tem, ele não modificará o seu diretório de trabalho de forma alguma. +Ele simplesmente obterá os dados para você e permitirá que você os mescle (merge) você mesmo. +No entanto, há um comando chamado `git pull` que é essencialmente um `git fetch` imediatamente seguido por um `git merge` na maioria dos casos. +Se você tiver um branch de rastreamento configurado conforme demonstrado na seção anterior, definindo-o explicitamente ou fazendo com que seja criado para você pelos comandos `clone` ou `checkout`, o `git pull` procurará qual servidor e branch o seu branch atual está rastreando, fará o fetch desse servidor e tentará mesclar (merge in) esse branch remoto. [[_delete_branches]] -==== Deleting Remote Branches +==== Excluindo Branches Remotos (((branches, deleting remote))) -Suppose you're done with a remote branch -- say you and your collaborators are finished with a feature and have merged it into your remote's `master` branch (or whatever branch your stable codeline is in). -You can delete a remote branch using the `--delete` option to `git push`. -If you want to delete your `serverfix` branch from the server, you run the following: +Suponha que você tenha terminado com um branch remoto -- digamos que você e seus colaboradores tenham terminado um recurso (feature) e o tenham mesclado (merged) no branch `master` do seu remoto (ou em qualquer branch em que a sua linha de código estável esteja). +Você pode excluir um branch remoto usando a opção `--delete` para `git push`. +Se você deseja excluir o seu branch `serverfix` do servidor, execute o seguinte: [source,console] ---- @@ -232,5 +232,5 @@ To https://github.com/schacon/simplegit - [deleted] serverfix ---- -Basically all this does is to remove the pointer from the server. -The Git server will generally keep the data there for a while until a garbage collection runs, so if it was accidentally deleted, it's often easy to recover. +Basicamente, tudo o que isso faz é remover o ponteiro do servidor. +O servidor Git geralmente manterá os dados lá por um tempo até que uma coleta de lixo (garbage collection) seja executada, então, se ele for excluído acidentalmente, geralmente é fácil de recuperar. diff --git a/book/03-git-branching/sections/workflows.asc b/book/03-git-branching/sections/workflows.asc index 9e6f3922..1a1ac4ea 100644 --- a/book/03-git-branching/sections/workflows.asc +++ b/book/03-git-branching/sections/workflows.asc @@ -1,63 +1,63 @@ -=== Branching Workflows +=== Fluxos de Trabalho de Branches (Branching Workflows) -Now that you have the basics of branching and merging down, what can or should you do with them? -In this section, we'll cover some common workflows that this lightweight branching makes possible, so you can decide if you would like to incorporate them into your own development cycle. +Agora que você tem o básico de ramificação e mesclagem (branching e merging), o que você pode ou deve fazer com eles? +Nesta seção, abordaremos alguns fluxos de trabalho comuns que essa ramificação leve torna possível, para que você possa decidir se gostaria de incorporá-los ao seu próprio ciclo de desenvolvimento. -==== Long-Running Branches +==== Branches de Longa Duração (Long-Running Branches) (((branches, long-running))) -Because Git uses a simple three-way merge, merging from one branch into another multiple times over a long period is generally easy to do. -This means you can have several branches that are always open and that you use for different stages of your development cycle; you can merge regularly from some of them into others. +Como o Git usa uma simples mesclagem de três vias (three-way merge), mesclar de um branch para outro várias vezes durante um longo período é geralmente fácil de fazer. +Isso significa que você pode ter vários branches que estão sempre abertos e que você usa para diferentes estágios do seu ciclo de desenvolvimento; você pode mesclar (merge) regularmente de alguns deles para outros. -Many Git developers have a workflow that embraces this approach, such as having only code that is entirely stable in their `master` branch -- possibly only code that has been or will be released. -They have another parallel branch named `develop` or `next` that they work from or use to test stability -- it isn't necessarily always stable, but whenever it gets to a stable state, it can be merged into `master`. -It's used to pull in topic branches (short-lived branches, like your earlier `iss53` branch) when they're ready, to make sure they pass all the tests and don't introduce bugs. +Muitos desenvolvedores Git têm um fluxo de trabalho que adota essa abordagem, como ter apenas código que seja totalmente estável no seu branch `master` -- possivelmente apenas código que foi ou será lançado (released). +Eles têm outro branch paralelo chamado `develop` ou `next` com o qual trabalham ou usam para testar a estabilidade -- não é necessariamente sempre estável, mas sempre que chega a um estado estável, pode ser mesclado (merged) no `master`. +Ele é usado para extrair (pull in) branches de tópicos (branches de curta duração, como seu branch `iss53` anterior) quando eles estiverem prontos, para garantir que passem em todos os testes e não introduzam bugs. -In reality, we're talking about pointers moving up the line of commits you're making. -The stable branches are farther down the line in your commit history, and the bleeding-edge branches are farther up the history. +Na realidade, estamos falando sobre ponteiros movendo-se na linha de commits que você está fazendo. +Os branches estáveis estão mais abaixo na linha do seu histórico de commits, e os branches de ponta (bleeding-edge) estão mais acima no histórico. -.A linear view of progressive-stability branching -image::images/lr-branches-1.png[A linear view of progressive-stability branching] +.Uma visão linear da ramificação de estabilidade progressiva +image::images/lr-branches-1.png[Uma visão linear da ramificação de estabilidade progressiva] -It's generally easier to think about them as work silos, where sets of commits graduate to a more stable silo when they're fully tested. +Geralmente, é mais fácil pensar neles como silos de trabalho, onde conjuntos de commits se formam para um silo mais estável quando são totalmente testados. [[lrbranch_b]] -.A "`silo`" view of progressive-stability branching -image::images/lr-branches-2.png[A “silo” view of progressive-stability branching] +.Uma visão em "`silo`" da ramificação de estabilidade progressiva +image::images/lr-branches-2.png[Uma visão em "silo" da ramificação de estabilidade progressiva] -You can keep doing this for several levels of stability. -Some larger projects also have a `proposed` or `pu` (proposed updates) branch that has integrated branches that may not be ready to go into the `next` or `master` branch. -The idea is that your branches are at various levels of stability; when they reach a more stable level, they're merged into the branch above them. -Again, having multiple long-running branches isn't necessary, but it's often helpful, especially when you're dealing with very large or complex projects. +Você pode continuar fazendo isso por vários níveis de estabilidade. +Alguns projetos maiores também têm um branch `proposed` ou `pu` (atualizações propostas) que integrou branches que podem não estar prontos para ir para o branch `next` ou `master`. +A ideia é que os seus branches estejam em vários níveis de estabilidade; quando eles atingem um nível mais estável, eles são mesclados (merged) no branch acima deles. +Novamente, ter vários branches de longa duração não é necessário, mas costuma ser útil, especialmente quando você está lidando com projetos muito grandes ou complexos. [[_topic_branch]] -==== Topic Branches +==== Branches de Tópicos (Topic Branches) (((branches, topic))) -Topic branches, however, are useful in projects of any size. -A topic branch is a short-lived branch that you create and use for a single particular feature or related work. -This is something you've likely never done with a VCS before because it's generally too expensive to create and merge branches. -But in Git it's common to create, work on, merge, and delete branches several times a day. +Os branches de tópicos, no entanto, são úteis em projetos de qualquer tamanho. +Um branch de tópico é um branch de curta duração que você cria e usa para um único recurso específico (feature) ou trabalho relacionado. +Isso é algo que você provavelmente nunca fez com um VCS (Sistema de Controle de Versão) antes, porque geralmente é muito caro criar e mesclar branches. +Mas no Git é comum criar, trabalhar, mesclar e excluir branches várias vezes ao dia. -You saw this in the last section with the `iss53` and `hotfix` branches you created. -You did a few commits on them and deleted them directly after merging them into your main branch. -This technique allows you to context-switch quickly and completely -- because your work is separated into silos where all the changes in that branch have to do with that topic, it's easier to see what has happened during code review and such. -You can keep the changes there for minutes, days, or months, and merge them in when they're ready, regardless of the order in which they were created or worked on. +Você viu isso na última seção com os branches `iss53` e `hotfix` que você criou. +Você fez alguns commits neles e os excluiu diretamente após mesclá-los (merging) no seu branch principal. +Esta técnica permite que você mude de contexto (context-switch) de forma rápida e completa -- como o seu trabalho é separado em silos onde todas as alterações daquele branch têm a ver com aquele tópico, é mais fácil ver o que aconteceu durante a revisão de código e afins. +Você pode manter as alterações lá por minutos, dias ou meses, e mesclá-las (merge) quando estiverem prontas, independentemente da ordem em que foram criadas ou trabalhadas. -Consider an example of doing some work (on `master`), branching off for an issue (`iss91`), working on it for a bit, branching off the second branch to try another way of handling the same thing (`iss91v2`), going back to your `master` branch and working there for a while, and then branching off there to do some work that you're not sure is a good idea (`dumbidea` branch). -Your commit history will look something like this: +Considere um exemplo de fazer algum trabalho (no `master`), ramificando (branching) para uma issue (`iss91`), trabalhando nela um pouco, ramificando o segundo branch para tentar outra maneira de lidar com a mesma coisa (`iss91v2`), voltando ao seu branch `master` e trabalhando lá por um tempo e, em seguida, ramificando para fazer um trabalho que você não tem certeza se é uma boa ideia (branch `dumbidea`). +O seu histórico de commits ficará parecido com isto: -.Multiple topic branches -image::images/topic-branches-1.png[Multiple topic branches] +.Múltiplos branches de tópicos +image::images/topic-branches-1.png[Múltiplos branches de tópicos] -Now, let's say you decide you like the second solution to your issue best (`iss91v2`); and you showed the `dumbidea` branch to your coworkers, and it turns out to be genius. -You can throw away the original `iss91` branch (losing commits `C5` and `C6`) and merge in the other two. -Your history then looks like this: +Agora, digamos que você decida que gosta mais da segunda solução para o seu problema (`iss91v2`); e você mostrou o branch `dumbidea` aos seus colegas de trabalho e ele acabou sendo genial. +Você pode descartar (throw away) o branch original `iss91` (perdendo os commits `C5` e `C6`) e mesclar os outros dois. +O seu histórico então fica assim: -.History after merging `dumbidea` and `iss91v2` -image::images/topic-branches-2.png[History after merging `dumbidea` and `iss91v2`] +.Histórico após mesclar `dumbidea` e `iss91v2` +image::images/topic-branches-2.png[Histórico após mesclar `dumbidea` e `iss91v2`] -We will go into more detail about the various possible workflows for your Git project in <>, so before you decide which branching scheme your next project will use, be sure to read that chapter. +Entraremos em mais detalhes sobre os vários fluxos de trabalho possíveis para o seu projeto Git em <>, portanto, antes de decidir qual esquema de ramificação (branching scheme) o seu próximo projeto usará, certifique-se de ler esse capítulo. -It's important to remember when you're doing all this that these branches are completely local. -When you're branching and merging, everything is being done only in your Git repository -- there is no communication with the server. +É importante lembrar ao fazer tudo isso que esses branches são completamente locais. +Quando você está ramificando e mesclando (branching e merging), tudo é feito apenas no seu repositório Git -- não há comunicação com o servidor. diff --git a/ch03-git-branching.asc b/ch03-git-branching.asc index 60d1a193..034d14ac 100644 --- a/ch03-git-branching.asc +++ b/ch03-git-branching.asc @@ -1,16 +1,16 @@ [[ch03-git-branching]] -== Git Branching +== Ramificação (Branching) no Git (((branches))) -Nearly every VCS has some form of branching support. -Branching means you diverge from the main line of development and continue to do work without messing with that main line. -In many VCS tools, this is a somewhat expensive process, often requiring you to create a new copy of your source code directory, which can take a long time for large projects. +Quase todos os VCSs têm alguma forma de suporte à ramificação (branching). +Branching (ramificação) significa que você diverge da linha principal de desenvolvimento e continua a fazer o trabalho sem mexer nessa linha principal. +Em muitas ferramentas de VCS, este é um processo um tanto custoso, muitas vezes exigindo que você crie uma nova cópia do diretório de código-fonte, o que pode levar muito tempo em projetos grandes. -Some people refer to Git's branching model as its "`killer feature,`" and it certainly sets Git apart in the VCS community. -Why is it so special? -The way Git branches is incredibly lightweight, making branching operations nearly instantaneous, and switching back and forth between branches generally just as fast. -Unlike many other VCSs, Git encourages workflows that branch and merge often, even multiple times in a day. -Understanding and mastering this feature gives you a powerful and unique tool and can entirely change the way that you develop. +Algumas pessoas se referem ao modelo de ramificação do Git como seu "`recurso matador (killer feature)`", e ele certamente destaca o Git na comunidade de VCS. +Por que é tão especial? +A maneira como o Git ramifica é incrivelmente leve, tornando as operações de ramificação quase instantâneas, e alternar entre as ramificações (branches) geralmente é igualmente rápido. +Ao contrário de muitos outros VCSs, o Git incentiva fluxos de trabalho que ramificam (branch) e mesclam (merge) frequentemente, até várias vezes ao dia. +Compreender e dominar esse recurso fornece a você uma ferramenta poderosa e única, e pode mudar completamente a maneira como você desenvolve. include::book/03-git-branching/sections/nutshell.asc[] @@ -24,9 +24,9 @@ include::book/03-git-branching/sections/remote-branches.asc[] include::book/03-git-branching/sections/rebasing.asc[] -=== Summary +=== Resumo -We've covered basic branching and merging in Git. -You should feel comfortable creating and switching to new branches, switching between branches and merging local branches together. -You should also be able to share your branches by pushing them to a shared server, working with others on shared branches and rebasing your branches before they are shared. -Next, we'll cover what you'll need to run your own Git repository-hosting server. +Cobrimos o básico sobre ramificação (branching) e mesclagem (merging) no Git. +Você deve se sentir confortável criando e mudando para novos branches, alternando entre branches e mesclando branches locais. +Você também deve ser capaz de compartilhar seus branches enviando-os (push) para um servidor compartilhado, trabalhando com outras pessoas em branches compartilhados e fazendo rebase de seus branches antes de eles serem compartilhados. +A seguir, abordaremos o que você precisará para executar seu próprio servidor de hospedagem de repositórios Git. From 4cabdc211ed76c1d7695e7359db3d4f22d2d2a3a Mon Sep 17 00:00:00 2001 From: "Sergio Cabral (AI Agent)" Date: Thu, 20 Aug 2026 13:51:58 -0300 Subject: [PATCH 06/16] =?UTF-8?q?Traduz:=20Cap=C3=ADtulo=204=20=E2=80=94?= =?UTF-8?q?=20Git=20no=20Servidor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../sections/generating-ssh-key.asc | 34 +-- book/04-git-server/sections/git-daemon.asc | 40 +-- .../sections/git-on-a-server.asc | 88 +++---- book/04-git-server/sections/gitlab.asc | 162 ++++++------ book/04-git-server/sections/gitweb.asc | 38 +-- book/04-git-server/sections/hosted.asc | 14 +- book/04-git-server/sections/protocols.asc | 240 +++++++++--------- .../sections/setting-up-server.asc | 66 ++--- book/04-git-server/sections/smart-http.asc | 44 ++-- ch04-git-on-the-server.asc | 40 +-- 10 files changed, 383 insertions(+), 383 deletions(-) diff --git a/book/04-git-server/sections/generating-ssh-key.asc b/book/04-git-server/sections/generating-ssh-key.asc index d1a61daf..ebf7189f 100644 --- a/book/04-git-server/sections/generating-ssh-key.asc +++ b/book/04-git-server/sections/generating-ssh-key.asc @@ -1,13 +1,13 @@ [[_generate_ssh_key]] -=== Generating Your SSH Public Key +=== Gerando a sua Chave Pública SSH (((SSH keys))) -Many Git servers authenticate using SSH public keys. -In order to provide a public key, each user in your system must generate one if they don't already have one. -This process is similar across all operating systems. -First, you should check to make sure you don't already have a key. -By default, a user's SSH keys are stored in that user's `~/.ssh` directory. -You can easily check to see if you have a key already by going to that directory and listing the contents: +Muitos servidores Git se autenticam usando chaves públicas SSH. +Para fornecer uma chave pública, cada usuário no seu sistema deve gerar uma se ainda não tiver. +Este processo é semelhante em todos os sistemas operacionais. +Primeiro, você deve verificar se já não tem uma chave. +Por padrão, as chaves SSH de um usuário são armazenadas no diretório `~/.ssh` desse usuário. +Você pode verificar facilmente se já tem uma chave acessando esse diretório e listando o conteúdo: [source,console] ---- @@ -17,9 +17,9 @@ authorized_keys2 id_dsa known_hosts config id_dsa.pub ---- -You're looking for a pair of files named something like `id_dsa` or `id_rsa` and a matching file with a `.pub` extension. -The `.pub` file is your public key, and the other file is the corresponding private key. -If you don't have these files (or you don't even have a `.ssh` directory), you can create them by running a program called `ssh-keygen`, which is provided with the SSH package on Linux/macOS systems and comes with Git for Windows: +Você está procurando um par de arquivos chamados algo como `id_dsa` ou `id_rsa` e um arquivo correspondente com a extensão `.pub`. +O arquivo `.pub` é a sua chave pública, e o outro arquivo é a chave privada correspondente. +Se você não tiver esses arquivos (ou nem mesmo tiver um diretório `.ssh`), pode criá-los executando um programa chamado `ssh-keygen`, que é fornecido com o pacote SSH nos sistemas Linux/macOS e vem com o Git para Windows: [source,console] ---- @@ -35,13 +35,13 @@ The key fingerprint is: d0:82:24:8e:d7:f1:bb:9b:33:53:96:93:49:da:9b:e3 schacon@mylaptop.local ---- -First it confirms where you want to save the key (`.ssh/id_rsa`), and then it asks twice for a passphrase, which you can leave empty if you don't want to type a password when you use the key. -However, if you do use a password, make sure to add the `-o` option; it saves the private key in a format that is more resistant to brute-force password cracking than is the default format. -You can also use the `ssh-agent` tool to prevent having to enter the password each time. +Primeiro ele confirma onde você quer salvar a chave (`.ssh/id_rsa`), e então pede duas vezes uma senha (passphrase), que você pode deixar em branco se não quiser digitar uma senha ao usar a chave. +No entanto, se você usar uma senha, certifique-se de adicionar a opção `-o`; ela salva a chave privada num formato que é mais resistente à quebra de senhas por força bruta do que o formato padrão. +Você também pode usar a ferramenta `ssh-agent` para evitar ter de digitar a senha toda vez. -Now, each user that does this has to send their public key to you or whoever is administrating the Git server (assuming you're using an SSH server setup that requires public keys). -All they have to do is copy the contents of the `.pub` file and email it. -The public keys look something like this: +Agora, cada usuário que faz isso precisa enviar a sua chave pública para você ou para quem estiver administrando o servidor Git (presumindo que você esteja usando uma configuração de servidor SSH que requer chaves públicas). +Tudo o que eles precisam fazer é copiar o conteúdo do arquivo `.pub` e enviá-lo por e-mail. +As chaves públicas se parecem com algo assim: [source,console] ---- @@ -54,4 +54,4 @@ mZ+AW4OZPnTPI89ZPmVMLuayrD2cE86Z/il8b+gw3r3+1nKatmIkjn2so1d01QraTlMqVSsbx NrRFi9wrf+M7Q== schacon@mylaptop.local ---- -For a more in-depth tutorial on creating an SSH key on multiple operating systems, see the GitHub guide on SSH keys at https://docs.github.com/en/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent[^]. +Para um tutorial mais detalhado sobre como criar uma chave SSH em vários sistemas operacionais, veja o guia do GitHub sobre chaves SSH em https://docs.github.com/en/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent[^]. diff --git a/book/04-git-server/sections/git-daemon.asc b/book/04-git-server/sections/git-daemon.asc index 1fe17237..734c3bb1 100644 --- a/book/04-git-server/sections/git-daemon.asc +++ b/book/04-git-server/sections/git-daemon.asc @@ -1,28 +1,28 @@ === Git Daemon (((serving repositories, git protocol))) -Next we'll set up a daemon serving repositories using the "`Git`" protocol. -This is a common choice for fast, unauthenticated access to your Git data. -Remember that since this is not an authenticated service, anything you serve over this protocol is public within its network. +Em seguida, configuraremos um daemon para servir repositórios usando o protocolo "`Git`". +Esta é uma escolha comum para acesso rápido e não autenticado aos seus dados Git. +Lembre-se de que, como este não é um serviço autenticado, qualquer coisa que você sirva através deste protocolo será pública dentro da sua rede. -If you're running this on a server outside your firewall, it should be used only for projects that are publicly visible to the world. -If the server you're running it on is inside your firewall, you might use it for projects that a large number of people or computers (continuous integration or build servers) have read-only access to, when you don't want to have to add an SSH key for each. +Se você estiver executando isso em um servidor fora do seu firewall, deve ser usado apenas para projetos que são publicamente visíveis para o mundo. +Se o servidor em que você o executa estiver dentro do seu firewall, você pode usá-lo para projetos aos quais um grande número de pessoas ou computadores (servidores de integração contínua ou de build) tem acesso de leitura, quando você não quer ter que adicionar uma chave SSH para cada um. -In any case, the Git protocol is relatively easy to set up. -Basically, you need to run this command in a daemonized manner:(((git commands, daemon))) +De qualquer forma, o protocolo Git é relativamente fácil de configurar. +Basicamente, você precisa executar este comando de maneira daemonizada (em segundo plano):(((git commands, daemon))) [source,console] ---- $ git daemon --reuseaddr --base-path=/srv/git/ /srv/git/ ---- -The `--reuseaddr` option allows the server to restart without waiting for old connections to time out, while the `--base-path` option allows people to clone projects without specifying the entire path, and the path at the end tells the Git daemon where to look for repositories to export. -If you're running a firewall, you'll also need to punch a hole in it at port 9418 on the box you're setting this up on. +A opção `--reuseaddr` permite que o servidor reinicie sem esperar que as conexões antigas atinjam o tempo limite, enquanto a opção `--base-path` permite que as pessoas clonem projetos sem especificar o caminho inteiro, e o caminho no final informa ao Git daemon onde procurar os repositórios a serem exportados. +Se você estiver executando um firewall, também precisará abrir um buraco (punch a hole) nele na porta 9418 da máquina em que está configurando isso. -You can daemonize this process a number of ways, depending on the operating system you're running. +Você pode daemonizar esse processo de várias maneiras, dependendo do sistema operacional que estiver executando. -Since `systemd` is the most common init system among modern Linux distributions, you can use it for that purpose. -Simply place a file in `/etc/systemd/system/git-daemon.service` with these contents: +Como o `systemd` é o sistema init mais comum entre as distribuições Linux modernas, você pode usá-lo para esse fim. +Basta colocar um arquivo em `/etc/systemd/system/git-daemon.service` com este conteúdo: [source,console] ---- @@ -46,16 +46,16 @@ Group=git WantedBy=multi-user.target ---- -You might have noticed that Git daemon is started here with `git` as both group and user. -Modify it to fit your needs and make sure the provided user exists on the system. -Also, check that the Git binary is indeed located at `/usr/bin/git` and change the path if necessary. +Você deve ter notado que o Git daemon é iniciado aqui com `git` como grupo e usuário. +Modifique-o para atender às suas necessidades e certifique-se de que o usuário fornecido exista no sistema. +Além disso, verifique se o binário do Git está realmente localizado em `/usr/bin/git` e altere o caminho se necessário. -Finally, you'll run `systemctl enable git-daemon` to automatically start the service on boot, and can start and stop the service with, respectively, `systemctl start git-daemon` and `systemctl stop git-daemon`. +Finalmente, você executará `systemctl enable git-daemon` para iniciar o serviço automaticamente na inicialização, e pode iniciar e parar o serviço com, respectivamente, `systemctl start git-daemon` e `systemctl stop git-daemon`. -On other systems, you may want to use `xinetd`, a script in your `sysvinit` system, or something else -- as long as you get that command daemonized and watched somehow. +Em outros sistemas, você pode querer usar `xinetd`, um script no seu sistema `sysvinit`, ou alguma outra coisa -- desde que você consiga que esse comando seja daemonizado e monitorado de alguma forma. -Next, you have to tell Git which repositories to allow unauthenticated Git server-based access to. -You can do this in each repository by creating a file named `git-daemon-export-ok`. +Em seguida, você precisa informar ao Git a quais repositórios ele deve permitir o acesso não autenticado baseado no servidor Git. +Você pode fazer isso em cada repositório criando um arquivo chamado `git-daemon-export-ok`. [source,console] ---- @@ -63,4 +63,4 @@ $ cd /path/to/project.git $ touch git-daemon-export-ok ---- -The presence of that file tells Git that it's OK to serve this project without authentication. +A presença desse arquivo informa ao Git que não há problema em servir este projeto sem autenticação. diff --git a/book/04-git-server/sections/git-on-a-server.asc b/book/04-git-server/sections/git-on-a-server.asc index 61847a99..389908d0 100644 --- a/book/04-git-server/sections/git-on-a-server.asc +++ b/book/04-git-server/sections/git-on-a-server.asc @@ -1,18 +1,18 @@ [[_getting_git_on_a_server]] -=== Getting Git on a Server +=== Colocando o Git em um Servidor -Now we'll cover setting up a Git service running these protocols on your own server. +Agora, abordaremos a configuração de um serviço Git executando esses protocolos no seu próprio servidor. [NOTE] ==== -Here we'll be demonstrating the commands and steps needed to do basic, simplified installations on a Linux-based server, though it's also possible to run these services on macOS or Windows servers. -Actually setting up a production server within your infrastructure will certainly entail differences in security measures or operating system tools, but hopefully this will give you the general idea of what's involved. +Aqui estaremos demonstrando os comandos e passos necessários para fazer instalações básicas e simplificadas em um servidor baseado em Linux, embora também seja possível executar esses serviços em servidores macOS ou Windows. +Na verdade, configurar um servidor de produção na sua infraestrutura certamente acarretará diferenças nas medidas de segurança ou nas ferramentas do sistema operacional, mas esperamos que isso lhe dê uma ideia geral do que está envolvido. ==== -In order to initially set up any Git server, you have to export an existing repository into a new bare repository -- a repository that doesn't contain a working directory. -This is generally straightforward to do. -In order to clone your repository to create a new bare repository, you run the clone command with the `--bare` option.(((git commands, clone, bare))) -By convention, bare repository directory names end with the suffix `.git`, like so: +Para configurar inicialmente qualquer servidor Git, você deve exportar um repositório existente para um novo repositório nu (bare repository) -- um repositório que não contém um diretório de trabalho. +Geralmente é simples de fazer. +Para clonar o seu repositório a fim de criar um novo repositório nu, você executa o comando clone com a opção `--bare`.(((git commands, clone, bare))) +Por convenção, os nomes de diretório de repositórios nus terminam com o sufixo `.git`, assim: [source,console] ---- @@ -21,41 +21,41 @@ Cloning into bare repository 'my_project.git'... done. ---- -You should now have a copy of the Git directory data in your `my_project.git` directory. +Agora você deve ter uma cópia dos dados do diretório Git no seu diretório `my_project.git`. -This is roughly equivalent to something like: +Isso é aproximadamente equivalente a algo como: [source,console] ---- $ cp -Rf my_project/.git my_project.git ---- -There are a couple of minor differences in the configuration file but, for your purpose, this is close to the same thing. -It takes the Git repository by itself, without a working directory, and creates a directory specifically for it alone. +Existem algumas pequenas diferenças no arquivo de configuração, mas, para o seu propósito, isso é quase a mesma coisa. +Ele pega o repositório Git por si só, sem um diretório de trabalho, e cria um diretório especificamente apenas para ele. [[_bare_repo]] -==== Putting the Bare Repository on a Server +==== Colocando o Repositório Nu (Bare) em um Servidor -Now that you have a bare copy of your repository, all you need to do is put it on a server and set up your protocols. -Let's say you've set up a server called `git.example.com` to which you have SSH access, and you want to store all your Git repositories under the `/srv/git` directory. -Assuming that `/srv/git` exists on that server, you can set up your new repository by copying your bare repository over: +Agora que você tem uma cópia nua do seu repositório, tudo o que você precisa fazer é colocá-la em um servidor e configurar os seus protocolos. +Digamos que você configurou um servidor chamado `git.example.com` ao qual você tem acesso SSH e deseja armazenar todos os seus repositórios Git no diretório `/srv/git`. +Supondo que `/srv/git` exista nesse servidor, você pode configurar o seu novo repositório copiando o seu repositório nu: [source,console] ---- $ scp -r my_project.git user@git.example.com:/srv/git ---- -At this point, other users who have SSH-based read access to the `/srv/git` directory on that server can clone your repository by running: +Neste ponto, outros usuários que tenham acesso de leitura baseado em SSH ao diretório `/srv/git` naquele servidor podem clonar o seu repositório executando: [source,console] ---- $ git clone user@git.example.com:/srv/git/my_project.git ---- -If a user SSHs into a server and has write access to the `/srv/git/my_project.git` directory, they will also automatically have push access. +Se um usuário fizer SSH em um servidor e tiver acesso de gravação ao diretório `/srv/git/my_project.git`, ele também terá acesso de push automaticamente. -Git will automatically add group write permissions to a repository properly if you run the `git init` command with the `--shared` option. -Note that by running this command, you will not destroy any commits, refs, etc. in the process.(((git commands, init, bare))) +O Git adicionará automaticamente permissões de gravação de grupo a um repositório adequadamente se você executar o comando `git init` com a opção `--shared`. +Observe que, ao executar este comando, você não destruirá nenhum commit, referência, etc. no processo.(((git commands, init, bare))) [source,console] ---- @@ -64,38 +64,38 @@ $ cd /srv/git/my_project.git $ git init --bare --shared ---- -You see how easy it is to take a Git repository, create a bare version, and place it on a server to which you and your collaborators have SSH access. -Now you're ready to collaborate on the same project. +Você vê como é fácil pegar um repositório Git, criar uma versão nua e colocá-lo em um servidor ao qual você e os seus colaboradores tenham acesso SSH. +Agora você está pronto para colaborar no mesmo projeto. -It's important to note that this is literally all you need to do to run a useful Git server to which several people have access -- just add SSH-able accounts on a server, and stick a bare repository somewhere that all those users have read and write access to. -You're ready to go -- nothing else needed. +É importante notar que isso é literalmente tudo o que você precisa fazer para executar um servidor Git útil ao qual várias pessoas tenham acesso -- basta adicionar contas com acesso SSH em um servidor e colocar um repositório nu em algum lugar onde todos esses usuários tenham acesso de leitura e gravação. +Você está pronto para começar -- nada mais é necessário. -In the next few sections, you'll see how to expand to more sophisticated setups. -This discussion will include not having to create user accounts for each user, adding public read access to repositories, setting up web UIs and more. -However, keep in mind that to collaborate with a couple of people on a private project, all you _need_ is an SSH server and a bare repository. +Nas próximas seções, você verá como expandir para configurações mais sofisticadas. +Essa discussão incluirá não ter que criar contas de usuário para cada usuário, adicionar acesso público de leitura a repositórios, configurar IUs da web e muito mais. +No entanto, tenha em mente que para colaborar com algumas pessoas em um projeto privado, tudo o que você _precisa_ é de um servidor SSH e um repositório nu. -==== Small Setups +==== Pequenas Configurações -If you're a small outfit or are just trying out Git in your organization and have only a few developers, things can be simple for you. -One of the most complicated aspects of setting up a Git server is user management. -If you want some repositories to be read-only for certain users and read/write for others, access and permissions can be a bit more difficult to arrange. +Se você é uma pequena equipe ou está apenas experimentando o Git na sua organização e tem apenas alguns desenvolvedores, as coisas podem ser simples para você. +Um dos aspectos mais complicados da configuração de um servidor Git é o gerenciamento de usuários. +Se você quiser que alguns repositórios sejam somente leitura para determinados usuários e leitura/gravação para outros, o acesso e as permissões podem ser um pouco mais difíceis de organizar. -===== SSH Access +===== Acesso SSH (((serving repositories, SSH))) -If you have a server to which all your developers already have SSH access, it's generally easiest to set up your first repository there, because you have to do almost no work (as we covered in the last section). -If you want more complex access control type permissions on your repositories, you can handle them with the normal filesystem permissions of your server's operating system. +Se você tem um servidor ao qual todos os seus desenvolvedores já têm acesso SSH, geralmente é mais fácil configurar o seu primeiro repositório lá, porque você não tem quase nenhum trabalho (como abordamos na última seção). +Se você quiser permissões de tipo de controle de acesso mais complexas nos seus repositórios, pode lidar com elas com as permissões normais do sistema de arquivos do sistema operacional do seu servidor. -If you want to place your repositories on a server that doesn't have accounts for everyone on your team for whom you want to grant write access, then you must set up SSH access for them. -We assume that if you have a server with which to do this, you already have an SSH server installed, and that's how you're accessing the server. +Se você quiser colocar os seus repositórios em um servidor que não tenha contas para todos na sua equipe para quem você deseja conceder acesso de gravação, você deve configurar o acesso SSH para eles. +Nós assumimos que se você tiver um servidor para fazer isso, você já tem um servidor SSH instalado, e é assim que você está acessando o servidor. -There are a few ways you can give access to everyone on your team. -The first is to set up accounts for everybody, which is straightforward but can be cumbersome. -You may not want to run `adduser` (or the possible alternative `useradd`) and have to set temporary passwords for every new user. +Existem algumas maneiras de dar acesso a todos na sua equipe. +A primeira é configurar contas para todos, o que é simples, mas pode ser trabalhoso. +Você pode não querer executar `adduser` (ou a possível alternativa `useradd`) e ter que definir senhas temporárias para cada novo usuário. -A second method is to create a single 'git' user account on the machine, ask every user who is to have write access to send you an SSH public key, and add that key to the `~/.ssh/authorized_keys` file of that new 'git' account. -At that point, everyone will be able to access that machine via the 'git' account. -This doesn't affect the commit data in any way -- the SSH user you connect as doesn't affect the commits you've recorded. +Um segundo método é criar uma única conta de usuário 'git' na máquina, pedir a todos os usuários que terão acesso de gravação que lhe enviem uma chave pública SSH e adicionar essa chave ao arquivo `~/.ssh/authorized_keys` dessa nova conta 'git'. +Nesse ponto, todos poderão acessar essa máquina através da conta 'git'. +Isso não afeta os dados do commit de forma alguma -- o usuário SSH como o qual você se conecta não afeta os commits que você gravou. -Another way to do it is to have your SSH server authenticate from an LDAP server or some other centralized authentication source that you may already have set up. -As long as each user can get shell access on the machine, any SSH authentication mechanism you can think of should work. +Outra maneira de fazer isso é fazer com que o seu servidor SSH se autentique a partir de um servidor LDAP ou alguma outra fonte de autenticação centralizada que você já possa ter configurado. +Desde que cada usuário possa obter acesso shell na máquina, qualquer mecanismo de autenticação SSH que você imaginar deve funcionar. diff --git a/book/04-git-server/sections/gitlab.asc b/book/04-git-server/sections/gitlab.asc index 97de7893..6bb3a412 100644 --- a/book/04-git-server/sections/gitlab.asc +++ b/book/04-git-server/sections/gitlab.asc @@ -1,130 +1,130 @@ === GitLab (((serving repositories, GitLab)))(((GitLab))) -GitWeb is pretty simplistic though. -If you're looking for a modern, fully featured Git server, there are several open source solutions out there that you can install instead. -As GitLab is one of the popular ones, we'll cover installing and using it as an example. -This is harder than the GitWeb option and will require more maintenance, but it is a fully featured option. +O GitWeb é bem simplista, no entanto. +Se você está procurando um servidor Git moderno e completo, há várias soluções de código aberto que você pode instalar. +Como o GitLab é um dos mais populares, vamos abordar a sua instalação e uso como exemplo. +Isso é mais difícil que a opção GitWeb e exigirá mais manutenção, mas é uma opção completa. -==== Installation +==== Instalação -GitLab is a database-backed web application, so its installation is more involved than some other Git servers. -Fortunately, this process is well-documented and supported. -GitLab strongly recommends installing GitLab on your server via the official Omnibus GitLab package. +O GitLab é uma aplicação web com suporte a banco de dados (database-backed), então a sua instalação é mais complexa do que a de alguns outros servidores Git. +Felizmente, esse processo é bem documentado e suportado. +O GitLab recomenda fortemente a instalação do GitLab no seu servidor através do pacote oficial Omnibus GitLab. -The other installation options are: +As outras opções de instalação são: -* GitLab Helm chart, for use with Kubernetes. -* Dockerized GitLab packages for use with Docker. -* From the source files. -* Cloud providers such as AWS, Google Cloud Platform, Azure, OpenShift and Digital Ocean. +* Gráfico (chart) GitLab Helm, para uso com o Kubernetes. +* Pacotes GitLab em Docker para uso com o Docker. +* A partir dos arquivos fonte (source files). +* Provedores de nuvem como AWS, Google Cloud Platform, Azure, OpenShift e Digital Ocean. -For more information read the https://gitlab.com/gitlab-org/gitlab-foss/-/blob/master/README.md[GitLab Community Edition (CE) readme^]. +Para mais informações, leia o https://gitlab.com/gitlab-org/gitlab-foss/-/blob/master/README.md[leia-me (readme) do GitLab Community Edition (CE)^]. -==== Administration +==== Administração -GitLab's administration interface is accessed over the web. -Simply point your browser to the hostname or IP address where GitLab is installed, and log in as the `root` user. -The password will depend on your installation type but by default, Omnibus GitLab automatically generates a password for and stores it to /etc/gitlab/initial_root_password for at least 24 hours. -Follow the documentation for more details. -After you've logged in, click the "`Admin area`" icon in the menu at the top right. +A interface de administração do GitLab é acessada pela web. +Basta apontar o seu navegador para o hostname ou endereço IP onde o GitLab está instalado e fazer o login como o usuário `root`. +A senha dependerá do seu tipo de instalação, mas por padrão, o Omnibus GitLab gera automaticamente uma senha e a armazena em /etc/gitlab/initial_root_password por pelo menos 24 horas. +Siga a documentação para mais detalhes. +Depois de logar, clique no ícone "`Admin area`" (área de Administração) no menu superior direito. [[gitlab_menu]] -.The "`Admin area`" item in the GitLab menu -image::images/gitlab-menu.png[The “Admin area” item in the GitLab menu] +.O item "`Admin area`" no menu do GitLab +image::images/gitlab-menu.png[O item "Admin area" no menu do GitLab] -===== Users +===== Usuários -Everybody using your GitLab server must have a user account. -User accounts are quite simple, they mainly contain personal information attached to login data. -Each user account has a *namespace*, which is a logical grouping of projects that belong to that user. -If the user +jane+ had a project named +project+, that project's URL would be `http://server/jane/project`. +Todo mundo que usa o seu servidor GitLab deve ter uma conta de usuário. +As contas de usuário são bem simples, elas contêm principalmente informações pessoais anexadas aos dados de login. +Cada conta de usuário tem um *namespace*, que é um agrupamento lógico de projetos que pertencem a esse usuário. +Se a usuária +jane+ tivesse um projeto chamado +project+, a URL desse projeto seria `http://server/jane/project`. [[gitlab_users]] -.The GitLab user administration screen -image::images/gitlab-users.png[The GitLab user administration screen] +.A tela de administração de usuários do GitLab +image::images/gitlab-users.png[A tela de administração de usuários do GitLab] -You can remove a user account in two ways: -"`Blocking`" a user prevents them from logging into the GitLab instance, but all of the data under that user's namespace will be preserved, and commits signed with that user's email address will still link back to their profile. +Você pode remover uma conta de usuário de duas maneiras: +"`Bloquear`" (Blocking) um usuário o impede de fazer login na instância do GitLab, mas todos os dados sob o namespace daquele usuário serão preservados, e os commits assinados com o endereço de e-mail daquele usuário ainda estarão vinculados ao seu perfil. -"`Destroying`" a user, on the other hand, completely removes them from the database and filesystem. -All projects and data in their namespace is removed, and any groups they own will also be removed. -This is obviously a much more permanent and destructive action, and you will rarely need it. +"`Destruir`" (Destroying) um usuário, por outro lado, o remove completamente do banco de dados e do sistema de arquivos. +Todos os projetos e dados no namespace dele são removidos, e quaisquer grupos que ele possua também serão removidos. +Esta é obviamente uma ação muito mais permanente e destrutiva, e você raramente precisará dela. [[_gitlab_groups_section]] -===== Groups +===== Grupos -A GitLab group is a collection of projects, along with data about how users can access those projects. -Each group has a project namespace (the same way that users do), so if the group +training+ has a project +materials+, its URL would be `http://server/training/materials`. +Um grupo do GitLab é uma coleção de projetos, juntamente com dados sobre como os usuários podem acessar esses projetos. +Cada grupo tem um namespace de projeto (da mesma forma que os usuários), então se o grupo +training+ tem um projeto +materials+, a sua URL seria `http://server/training/materials`. [[gitlab_groups]] -.The GitLab group administration screen -image::images/gitlab-groups.png[The GitLab group administration screen] +.A tela de administração de grupos do GitLab +image::images/gitlab-groups.png[A tela de administração de grupos do GitLab] -Each group is associated with a number of users, each of which has a level of permissions for the group's projects and the group itself. -These range from "`Guest`" (issues and chat only) to "`Owner`" (full control of the group, its members, and its projects). -The types of permissions are too numerous to list here, but GitLab has a helpful link on the administration screen. +Cada grupo está associado a um número de usuários, cada um dos quais tem um nível de permissões para os projetos do grupo e para o próprio grupo. +Estes variam de "`Convidado`" (Guest - apenas issues e chat) a "`Proprietário`" (Owner - controle total do grupo, seus membros e seus projetos). +Os tipos de permissões são numerosos demais para serem listados aqui, mas o GitLab tem um link útil na tela de administração. -===== Projects +===== Projetos -A GitLab project roughly corresponds to a single Git repository. -Every project belongs to a single namespace, either a user or a group. -If the project belongs to a user, the owner of the project has direct control over who has access to the project; if the project belongs to a group, the group's user-level permissions will take effect. +Um projeto do GitLab corresponde aproximadamente a um único repositório Git. +Cada projeto pertence a um único namespace, seja de um usuário ou de um grupo. +Se o projeto pertencer a um usuário, o proprietário do projeto tem controle direto sobre quem tem acesso ao projeto; se o projeto pertencer a um grupo, as permissões de nível de usuário do grupo entrarão em vigor. -Every project has a visibility level, which controls who has read access to that project's pages and repository. -If a project is _Private_, the project's owner must explicitly grant access to specific users. -An _Internal_ project is visible to any logged-in user, and a _Public_ project is visible to anyone. -Note that this controls both `git fetch` access as well as access to the web UI for that project. +Cada projeto tem um nível de visibilidade, que controla quem tem acesso de leitura às páginas e ao repositório desse projeto. +Se um projeto for _Privado_, o proprietário do projeto deve conceder acesso explicitamente a usuários específicos. +Um projeto _Interno_ é visível para qualquer usuário logado, e um projeto _Público_ é visível para qualquer pessoa. +Observe que isso controla tanto o acesso `git fetch` quanto o acesso à UI web para esse projeto. -===== Hooks +===== Ganchos (Hooks) -GitLab includes support for hooks, both at a project or system level. -For either of these, the GitLab server will perform an HTTP POST with some descriptive JSON whenever relevant events occur. -This is a great way to connect your Git repositories and GitLab instance to the rest of your development automation, such as CI servers, chat rooms, or deployment tools. +O GitLab inclui suporte para ganchos (hooks), tanto no nível de projeto quanto de sistema. +Para qualquer um desses, o servidor GitLab executará um HTTP POST com algum JSON descritivo sempre que eventos relevantes ocorrerem. +Essa é uma ótima maneira de conectar os seus repositórios Git e a instância do GitLab ao resto da sua automação de desenvolvimento, como servidores de CI, salas de bate-papo (chat rooms) ou ferramentas de implantação (deployment). -==== Basic Usage +==== Uso Básico -The first thing you'll want to do with GitLab is create a new project. -You can do this by clicking on the "`+`" icon on the toolbar. -You'll be asked for the project's name, which namespace it should belong to, and what its visibility level should be. -Most of what you specify here isn't permanent, and can be changed later through the settings interface. -Click "`Create Project`", and you're done. +A primeira coisa que você vai querer fazer com o GitLab é criar um novo projeto. +Você pode fazer isso clicando no ícone "`+`" na barra de ferramentas. +Você será solicitado a informar o nome do projeto, a qual namespace ele deve pertencer e qual deve ser o seu nível de visibilidade. +A maior parte do que você especifica aqui não é permanente e pode ser alterada posteriormente através da interface de configurações. +Clique em "`Criar Projeto`" (Create Project), e você está pronto. -Once the project exists, you'll probably want to connect it with a local Git repository. -Each project is accessible over HTTPS or SSH, either of which can be used to configure a Git remote. -The URLs are visible at the top of the project's home page. -For an existing local repository, this command will create a remote named `gitlab` to the hosted location: +Depois que o projeto existir, você provavelmente desejará conectá-lo a um repositório Git local. +Cada projeto é acessível via HTTPS ou SSH, qualquer um dos quais pode ser usado para configurar um remoto Git. +As URLs são visíveis no topo da página inicial do projeto. +Para um repositório local existente, este comando criará um remoto chamado `gitlab` para o local hospedado: [source,console] ---- $ git remote add gitlab https://server/namespace/project.git ---- -If you don't have a local copy of the repository, you can simply do this: +Se você não tiver uma cópia local do repositório, pode simplesmente fazer isto: [source,console] ---- $ git clone https://server/namespace/project.git ---- -The web UI provides access to several useful views of the repository itself. -Each project's home page shows recent activity, and links along the top will lead you to views of the project's files and commit log. +A interface web fornece acesso a várias visualizações úteis do próprio repositório. +A página inicial de cada projeto mostra a atividade recente, e os links na parte superior o levarão a visualizações dos arquivos e do log de commits do projeto. -==== Working Together +==== Trabalhando Juntos -The simplest way of working together on a GitLab project is by giving each user direct push access to the Git repository. -You can add a user to a project by going to the "`Members`" section of that project's settings, and associating the new user with an access level (the different access levels are discussed a bit in <<_gitlab_groups_section>>). -By giving a user an access level of "`Developer`" or above, that user can push commits and branches directly to the repository. +A maneira mais simples de trabalhar junto em um projeto do GitLab é dando a cada usuário acesso direto de push ao repositório Git. +Você pode adicionar um usuário a um projeto acessando a seção "`Membros`" (Members) das configurações desse projeto e associando o novo usuário a um nível de acesso (os diferentes níveis de acesso são discutidos um pouco em <<_gitlab_groups_section>>). +Ao dar a um usuário um nível de acesso "`Desenvolvedor`" (Developer) ou superior, esse usuário pode fazer o push de commits e branches diretamente para o repositório. -Another, more decoupled way of collaboration is by using merge requests. -This feature enables any user that can see a project to contribute to it in a controlled way. -Users with direct access can simply create a branch, push commits to it, and open a merge request from their branch back into `master` or any other branch. -Users who don't have push permissions for a repository can "`fork`" it to create their own copy, push commits to _their_ copy, and open a merge request from their fork back to the main project. -This model allows the owner to be in full control of what goes into the repository and when, while allowing contributions from untrusted users. +Outra forma de colaboração, mais desacoplada, é usar merge requests (solicitações de mesclagem). +Esse recurso permite que qualquer usuário que possa ver um projeto contribua com ele de forma controlada. +Usuários com acesso direto podem simplesmente criar um branch, fazer o push de commits para ele e abrir um merge request de seu branch de volta para a `master` ou qualquer outro branch. +Os usuários que não têm permissão de push para um repositório podem fazer o "`fork`" dele para criar sua própria cópia, fazer o push de commits para a cópia _deles_ e abrir um merge request de seu fork de volta para o projeto principal. +Esse modelo permite que o proprietário tenha controle total sobre o que entra no repositório e quando, ao mesmo tempo em que permite contribuições de usuários não confiáveis. -Merge requests and issues are the main units of long-lived discussion in GitLab. -Each merge request allows a line-by-line discussion of the proposed change (which supports a lightweight kind of code review), as well as a general overall discussion thread. -Both can be assigned to users, or organized into milestones. +Os merge requests e os issues (problemas/tarefas) são as principais unidades de discussão de longa duração no GitLab. +Cada merge request permite uma discussão linha por linha da alteração proposta (o que suporta um tipo leve de revisão de código), bem como um tópico de discussão geral (discussion thread). +Ambos podem ser atribuídos a usuários ou organizados em marcos (milestones). -This section is focused mainly on the Git-related features of GitLab, but as a mature project, it provides many other features to help your team work together, such as project wikis and system maintenance tools. -One benefit to GitLab is that, once the server is set up and running, you'll rarely need to tweak a configuration file or access the server via SSH; most administration and general usage can be done through the in-browser interface. +Esta seção é focada principalmente nos recursos do GitLab relacionados ao Git, mas como um projeto maduro, ele fornece muitos outros recursos para ajudar a sua equipe a trabalhar em conjunto, como wikis de projeto e ferramentas de manutenção do sistema. +Um benefício do GitLab é que, uma vez que o servidor esteja configurado e funcionando, você raramente precisará ajustar um arquivo de configuração ou acessar o servidor via SSH; a maior parte da administração e do uso geral pode ser feita por meio da interface no navegador. diff --git a/book/04-git-server/sections/gitweb.asc b/book/04-git-server/sections/gitweb.asc index 1565dc49..45964bc8 100644 --- a/book/04-git-server/sections/gitweb.asc +++ b/book/04-git-server/sections/gitweb.asc @@ -1,17 +1,17 @@ === GitWeb (((serving repositories, GitWeb)))(((GitWeb))) -Now that you have basic read/write and read-only access to your project, you may want to set up a simple web-based visualizer. -Git comes with a CGI script called GitWeb that is sometimes used for this. +Agora que você tem acesso básico de leitura/gravação e somente leitura ao seu projeto, pode querer configurar um visualizador simples baseado na web. +O Git vem com um script CGI chamado GitWeb que às vezes é usado para isso. [[gitweb]] -.The GitWeb web-based user interface -image::images/git-instaweb.png[The GitWeb web-based user interface] +.A interface de usuário baseada na web GitWeb +image::images/git-instaweb.png[A interface de usuário baseada na web GitWeb] -If you want to check out what GitWeb would look like for your project, Git comes with a command to fire up a temporary instance if you have a lightweight web server on your system like `lighttpd` or `webrick`. -On Linux machines, `lighttpd` is often installed, so you may be able to get it to run by typing `git instaweb` in your project directory. -If you're running macOS, Leopard comes preinstalled with Ruby, so `webrick` may be your best bet. -To start `instaweb` with a non-lighttpd handler, you can run it with the `--httpd` option.(((git commands, instaweb))) +Se você quiser conferir como o GitWeb ficaria no seu projeto, o Git vem com um comando para acionar uma instância temporária se você tiver um servidor web leve (lightweight) no seu sistema, como `lighttpd` ou `webrick`. +Em máquinas Linux, o `lighttpd` costuma estar instalado, então você pode conseguir executá-lo digitando `git instaweb` no diretório do seu projeto. +Se você estiver executando o macOS, o Leopard vem pré-instalado com Ruby, então o `webrick` pode ser a sua melhor aposta. +Para iniciar o `instaweb` com um manipulador não-lighttpd, você pode executá-lo com a opção `--httpd`.(((git commands, instaweb))) [source,console] ---- @@ -20,19 +20,19 @@ $ git instaweb --httpd=webrick [2009-02-21 10:02:21] INFO ruby 1.8.6 (2008-03-03) [universal-darwin9.0] ---- -That starts up an HTTPD server on port 1234 and then automatically starts a web browser that opens on that page. -It's pretty easy on your part. -When you're done and want to shut down the server, you can run the same command with the `--stop` option: +Isso inicia um servidor HTTPD na porta 1234 e então inicia automaticamente um navegador da web que abre nessa página. +É muito fácil da sua parte. +Quando terminar e quiser desligar o servidor, você pode executar o mesmo comando com a opção `--stop`: [source,console] ---- $ git instaweb --httpd=webrick --stop ---- -If you want to run the web interface on a server all the time for your team or for an open source project you're hosting, you'll need to set up the CGI script to be served by your normal web server. -Some Linux distributions have a `gitweb` package that you may be able to install via `apt` or `dnf`, so you may want to try that first. -We'll walk through installing GitWeb manually very quickly. -First, you need to get the Git source code, which GitWeb comes with, and generate the custom CGI script: +Se você quiser executar a interface da web em um servidor o tempo todo para a sua equipe ou para um projeto de código aberto que você está hospedando, precisará configurar o script CGI para ser servido pelo seu servidor web normal. +Algumas distribuições Linux têm um pacote `gitweb` que você pode conseguir instalar via `apt` ou `dnf`, então você pode querer tentar isso primeiro. +Veremos como instalar o GitWeb manualmente de forma muito rápida. +Primeiro, você precisa obter o código-fonte do Git, que vem com o GitWeb, e gerar o script CGI personalizado: [source,console] ---- @@ -47,8 +47,8 @@ make[2]: `GIT-VERSION-FILE' is up to date. $ sudo cp -Rf gitweb /var/www/ ---- -Notice that you have to tell the command where to find your Git repositories with the `GITWEB_PROJECTROOT` variable. -Now, you need to make Apache use CGI for that script, for which you can add a VirtualHost: +Observe que você deve dizer ao comando onde encontrar os seus repositórios Git com a variável `GITWEB_PROJECTROOT`. +Agora, você precisa fazer com que o Apache use CGI para esse script, para o qual você pode adicionar um VirtualHost: [source,console] ---- @@ -66,5 +66,5 @@ Now, you need to make Apache use CGI for that script, for which you can add a Vi ---- -Again, GitWeb can be served with any CGI or Perl capable web server; if you prefer to use something else, it shouldn't be difficult to set up. -At this point, you should be able to visit `http://gitserver/` to view your repositories online. +Novamente, o GitWeb pode ser servido com qualquer servidor web capaz de rodar CGI ou Perl; se você preferir usar outra coisa, não deve ser difícil de configurar. +Neste ponto, você deve conseguir visitar `http://gitserver/` para visualizar os seus repositórios online. diff --git a/book/04-git-server/sections/hosted.asc b/book/04-git-server/sections/hosted.asc index 54eb7933..05e8883f 100644 --- a/book/04-git-server/sections/hosted.asc +++ b/book/04-git-server/sections/hosted.asc @@ -1,10 +1,10 @@ -=== Third Party Hosted Options +=== Opções de Hospedagem de Terceiros -If you don't want to go through all of the work involved in setting up your own Git server, you have several options for hosting your Git projects on an external dedicated hosting site. -Doing so offers a number of advantages: a hosting site is generally quick to set up and easy to start projects on, and no server maintenance or monitoring is involved. -Even if you set up and run your own server internally, you may still want to use a public hosting site for your open source code -- it's generally easier for the open source community to find and help you with. +Se você não quiser passar por todo o trabalho de configurar o seu próprio servidor Git, você tem várias opções para hospedar os seus projetos Git em um site de hospedagem externo dedicado. +Fazer isso oferece uma série de vantagens: um site de hospedagem geralmente é rápido de configurar e fácil para iniciar projetos, e nenhuma manutenção ou monitoramento de servidor está envolvido. +Mesmo se você configurar e executar o seu próprio servidor internamente, ainda pode querer usar um site de hospedagem público para o seu código de fonte aberto (open source) -- geralmente é mais fácil para a comunidade de código aberto encontrar e ajudá-lo. -These days, you have a huge number of hosting options to choose from, each with different advantages and disadvantages. -To see an up-to-date list, check out the GitHosting page on the main Git wiki at https://archive.kernel.org/oldwiki/git.wiki.kernel.org/index.php/GitHosting.html[^]. +Atualmente, você tem um grande número de opções de hospedagem para escolher, cada uma com diferentes vantagens e desvantagens. +Para ver uma lista atualizada, confira a página GitHosting na wiki principal do Git em https://archive.kernel.org/oldwiki/git.wiki.kernel.org/index.php/GitHosting.html[^]. -We'll cover using GitHub in detail in <>, as it is the largest Git host out there and you may need to interact with projects hosted on it in any case, but there are dozens more to choose from should you not want to set up your own Git server. +Abordaremos o uso do GitHub em detalhes no <>, pois é o maior host Git existente e você pode precisar interagir com projetos hospedados nele de qualquer forma, mas há dezenas de outros para escolher se você não quiser configurar o seu próprio servidor Git. diff --git a/book/04-git-server/sections/protocols.asc b/book/04-git-server/sections/protocols.asc index ff226d1e..5cd67ba2 100644 --- a/book/04-git-server/sections/protocols.asc +++ b/book/04-git-server/sections/protocols.asc @@ -1,98 +1,98 @@ -=== The Protocols +=== Os Protocolos -Git can use four distinct protocols to transfer data: Local, HTTP, Secure Shell (SSH) and Git. -Here we'll discuss what they are and in what basic circumstances you would want (or not want) to use them. +O Git pode usar quatro protocolos distintos para transferir dados: Local, HTTP, Secure Shell (SSH) e Git. +Aqui, discutiremos o que eles são e em quais circunstâncias básicas você gostaria (ou não gostaria) de usá-los. -==== Local Protocol +==== Protocolo Local (((protocols, local))) -The most basic is the _Local protocol_, in which the remote repository is in another directory on the same host. -This is often used if everyone on your team has access to a shared filesystem such as an https://en.wikipedia.org/wiki/Network_File_System[NFS^] mount, or in the less likely case that everyone logs in to the same computer. -The latter wouldn't be ideal, because all your code repository instances would reside on the same computer, making a catastrophic loss much more likely. +O mais básico é o _protocolo Local_, no qual o repositório remoto está em outro diretório no mesmo host. +Isso é frequentemente usado se todos na sua equipe tiverem acesso a um sistema de arquivos compartilhado, como uma montagem https://en.wikipedia.org/wiki/Network_File_System[NFS^], ou no caso menos provável de que todos façam login no mesmo computador. +Este último não seria o ideal, pois todas as suas instâncias de repositório de código residiriam no mesmo computador, tornando uma perda catastrófica muito mais provável. -If you have a shared mounted filesystem, then you can clone, push to, and pull from a local file-based repository. -To clone a repository like this, or to add one as a remote to an existing project, use the path to the repository as the URL. -For example, to clone a local repository, you can run something like this: +Se você tiver um sistema de arquivos compartilhado montado, poderá clonar, fazer o push e o pull de um repositório local baseado em arquivo. +Para clonar um repositório como esse ou para adicioná-lo como remoto a um projeto existente, use o caminho para o repositório como a URL. +Por exemplo, para clonar um repositório local, você pode executar algo assim: [source,console] ---- $ git clone /srv/git/project.git ---- -Or you can do this: +Ou você pode fazer isso: [source,console] ---- $ git clone file:///srv/git/project.git ---- -Git operates slightly differently if you explicitly specify `file://` at the beginning of the URL. -If you just specify the path, Git tries to use hardlinks or directly copy the files it needs. -If you specify `file://`, Git fires up the processes that it normally uses to transfer data over a network, which is generally much less efficient. -The main reason to specify the `file://` prefix is if you want a clean copy of the repository with extraneous references or objects left out -- generally after an import from another VCS or something similar (see <> for maintenance tasks). -We'll use the normal path here because doing so is almost always faster. +O Git opera de forma ligeiramente diferente se você especificar explicitamente `file://` no início da URL. +Se você apenas especificar o caminho, o Git tentará usar hardlinks (links físicos) ou copiar diretamente os arquivos de que precisa. +Se você especificar `file://`, o Git aciona os processos que ele normalmente usa para transferir dados por uma rede, o que geralmente é muito menos eficiente. +O principal motivo para especificar o prefixo `file://` é se você quiser uma cópia limpa do repositório, sem as referências estranhas (extraneous) ou os objetos deixados de fora -- geralmente após uma importação de outro VCS ou algo semelhante (consulte <> para tarefas de manutenção). +Usaremos o caminho normal aqui porque fazer isso é quase sempre mais rápido. -To add a local repository to an existing Git project, you can run something like this: +Para adicionar um repositório local a um projeto Git existente, você pode executar algo assim: [source,console] ---- $ git remote add local_proj /srv/git/project.git ---- -Then, you can push to and pull from that remote via your new remote name `local_proj` as though you were doing so over a network. +Então, você pode fazer o push e o pull desse remoto através do seu novo nome de remoto `local_proj` como se estivesse fazendo isso por uma rede. -===== The Pros +===== Os Prós -The pros of file-based repositories are that they're simple and they use existing file permissions and network access. -If you already have a shared filesystem to which your whole team has access, setting up a repository is very easy. -You stick the bare repository copy somewhere everyone has shared access to and set the read/write permissions as you would for any other shared directory. -We'll discuss how to export a bare repository copy for this purpose in <>. +Os prós dos repositórios baseados em arquivos são que eles são simples e usam as permissões de arquivos e o acesso à rede existentes. +Se você já tem um sistema de arquivos compartilhado ao qual toda a sua equipe tem acesso, configurar um repositório é muito fácil. +Você coloca a cópia do repositório nu em algum lugar ao qual todos tenham acesso compartilhado e define as permissões de leitura/gravação como faria para qualquer outro diretório compartilhado. +Discutiremos como exportar uma cópia do repositório nu para este propósito em <>. -This is also a nice option for quickly grabbing work from someone else's working repository. -If you and a co-worker are working on the same project and they want you to check something out, running a command like `git pull /home/john/project` is often easier than them pushing to a remote server and you subsequently fetching from it. +Essa também é uma ótima opção para obter rapidamente o trabalho do repositório de trabalho de outra pessoa. +Se você e um colega de trabalho estiverem trabalhando no mesmo projeto e eles quiserem que você verifique algo, executar um comando como `git pull /home/john/project` costuma ser mais fácil do que eles fazerem o push para um servidor remoto e você, em seguida, fazer o fetch a partir dele. -===== The Cons +===== Os Contras -The cons of this method are that shared access is generally more difficult to set up and reach from multiple locations than basic network access. -If you want to push from your laptop when you're at home, you have to mount the remote disk, which can be difficult and slow compared to network-based access. +Os contras deste método são que o acesso compartilhado geralmente é mais difícil de configurar e alcançar de vários locais do que o acesso básico à rede. +Se você deseja fazer o push do seu laptop quando está em casa, precisa montar o disco remoto, o que pode ser difícil e lento em comparação com o acesso baseado em rede. -It's important to mention that this isn't necessarily the fastest option if you're using a shared mount of some kind. -A local repository is fast only if you have fast access to the data. -A repository on NFS is often slower than the repository over SSH on the same server, allowing Git to run off local disks on each system. +É importante mencionar que esta não é necessariamente a opção mais rápida se você estiver usando um tipo de montagem compartilhada. +Um repositório local só é rápido se você tiver acesso rápido aos dados. +Um repositório em NFS geralmente é mais lento do que o repositório via SSH no mesmo servidor, permitindo que o Git seja executado nos discos locais de cada sistema. -Finally, this protocol does not protect the repository against accidental damage. -Every user has full shell access to the "`remote`" directory, and there is nothing preventing them from changing or removing internal Git files and corrupting the repository. +Finalmente, esse protocolo não protege o repositório contra danos acidentais. +Cada usuário tem acesso shell total ao diretório "`remoto`", e não há nada que o impeça de alterar ou remover arquivos internos do Git e corromper o repositório. -==== The HTTP Protocols +==== Os Protocolos HTTP -Git can communicate over HTTP using two different modes. -Prior to Git 1.6.6, there was only one way it could do this which was very simple and generally read-only. -In version 1.6.6, a new, smarter protocol was introduced that involved Git being able to intelligently negotiate data transfer in a manner similar to how it does over SSH. -In the last few years, this new HTTP protocol has become very popular since it's simpler for the user and smarter about how it communicates. -The newer version is often referred to as the _Smart_ HTTP protocol and the older way as _Dumb_ HTTP. -We'll cover the newer Smart HTTP protocol first. +O Git pode se comunicar via HTTP usando dois modos diferentes. +Antes do Git 1.6.6, havia apenas uma maneira de fazer isso, que era muito simples e geralmente apenas para leitura (read-only). +Na versão 1.6.6, um protocolo novo e mais inteligente foi introduzido, que envolvia o Git sendo capaz de negociar inteligentemente a transferência de dados de uma maneira semelhante a como ele faz via SSH. +Nos últimos anos, esse novo protocolo HTTP se tornou muito popular, pois é mais simples para o usuário e mais inteligente sobre como se comunica. +A versão mais recente costuma ser chamada de protocolo HTTP _Inteligente_ (Smart HTTP) e a maneira mais antiga como HTTP _Burro_ (Dumb HTTP). +Abordaremos primeiro o novo protocolo Smart HTTP. ===== Smart HTTP (((protocols, smart HTTP))) -Smart HTTP operates very similarly to the SSH or Git protocols but runs over standard HTTPS ports and can use various HTTP authentication mechanisms, meaning it's often easier on the user than something like SSH, since you can use things like username/password authentication rather than having to set up SSH keys. +O Smart HTTP opera de forma muito semelhante aos protocolos SSH ou Git, mas roda sobre portas HTTPS padrão e pode usar vários mecanismos de autenticação HTTP, o que significa que geralmente é mais fácil para o usuário do que algo como o SSH, já que você pode usar coisas como autenticação de nome de usuário/senha em vez de ter que configurar chaves SSH. -It has probably become the most popular way to use Git now, since it can be set up to both serve anonymously like the `git://` protocol, and can also be pushed over with authentication and encryption like the SSH protocol. -Instead of having to set up different URLs for these things, you can now use a single URL for both. -If you try to push and the repository requires authentication (which it normally should), the server can prompt for a username and password. -The same goes for read access. +Provavelmente se tornou a maneira mais popular de usar o Git agora, já que ele pode ser configurado tanto para servir anonimamente como o protocolo `git://`, quanto para fazer push com autenticação e criptografia como o protocolo SSH. +Em vez de ter que configurar URLs diferentes para essas coisas, agora você pode usar uma única URL para ambas. +Se você tentar fazer o push e o repositório exigir autenticação (o que normalmente deveria), o servidor pode solicitar um nome de usuário e uma senha. +O mesmo vale para o acesso de leitura. -In fact, for services like GitHub, the URL you use to view the repository online (for example, https://github.com/schacon/simplegit[^]) is the same URL you can use to clone and, if you have access, push over. +Na verdade, para serviços como o GitHub, a URL que você usa para visualizar o repositório online (por exemplo, https://github.com/schacon/simplegit[^]) é a mesma URL que você pode usar para clonar e, se tiver acesso, para fazer push. ===== Dumb HTTP (((protocols, dumb HTTP))) -If the server does not respond with a Git HTTP smart service, the Git client will try to fall back to the simpler _Dumb_ HTTP protocol. -The Dumb protocol expects the bare Git repository to be served like normal files from the web server. -The beauty of Dumb HTTP is the simplicity of setting it up. -Basically, all you have to do is put a bare Git repository under your HTTP document root and set up a specific `post-update` hook, and you're done (see <>). -At that point, anyone who can access the web server under which you put the repository can also clone your repository. -To allow read access to your repository over HTTP, do something like this: +Se o servidor não responder com um serviço inteligente (smart service) HTTP do Git, o cliente Git tentará recorrer (fall back) ao protocolo _Dumb_ HTTP, mais simples. +O protocolo Dumb espera que o repositório Git nu (bare) seja servido como arquivos normais do servidor da web. +A beleza do Dumb HTTP é a simplicidade de configurá-lo. +Basicamente, tudo o que você precisa fazer é colocar um repositório Git nu (bare) sob a raiz do documento HTTP e configurar um gancho (hook) específico de `post-update`, e pronto (consulte <>). +A partir desse ponto, qualquer um que possa acessar o servidor da web no qual você colocou o repositório também poderá cloná-lo. +Para permitir acesso de leitura ao seu repositório via HTTP, faça algo assim: [source,console] ---- @@ -103,109 +103,109 @@ $ mv hooks/post-update.sample hooks/post-update $ chmod a+x hooks/post-update ---- -That's all.(((hooks, post-update))) -The `post-update` hook that comes with Git by default runs the appropriate command (`git update-server-info`) to make HTTP fetching and cloning work properly. -This command is run when you push to this repository (over SSH perhaps); then, other people can clone via something like: +Isso é tudo.(((hooks, post-update))) +O hook `post-update` que vem com o Git por padrão executa o comando apropriado (`git update-server-info`) para fazer com que a busca (fetching) e a clonagem HTTP funcionem corretamente. +Este comando é executado quando você faz o push para este repositório (via SSH, talvez); então, outras pessoas podem clonar via algo como: [source,console] ---- $ git clone https://example.com/gitproject.git ---- -In this particular case, we're using the `/var/www/htdocs` path that is common for Apache setups, but you can use any static web server -- just put the bare repository in its path. -The Git data is served as basic static files (see the <> chapter for details about exactly how it's served). +Neste caso particular, estamos usando o caminho `/var/www/htdocs`, que é comum para configurações do Apache, mas você pode usar qualquer servidor da web estático -- basta colocar o repositório nu no seu caminho. +Os dados do Git são servidos como arquivos estáticos básicos (consulte o capítulo <> para obter detalhes sobre como exatamente ele é servido). -Generally you would either choose to run a read/write Smart HTTP server or simply have the files accessible as read-only in the Dumb manner. -It's rare to run a mix of the two services. +Geralmente, você optaria por executar um servidor Smart HTTP de leitura/gravação ou simplesmente ter os arquivos acessíveis como leitura (read-only) da maneira Dumb. +É raro executar uma mistura dos dois serviços. -===== The Pros +===== Os Prós -We'll concentrate on the pros of the Smart version of the HTTP protocol. +Nós nos concentraremos nos prós da versão Smart do protocolo HTTP. -The simplicity of having a single URL for all types of access and having the server prompt only when authentication is needed makes things very easy for the end user. -Being able to authenticate with a username and password is also a big advantage over SSH, since users don't have to generate SSH keys locally and upload their public key to the server before being able to interact with it. -For less sophisticated users, or users on systems where SSH is less common, this is a major advantage in usability. -It is also a very fast and efficient protocol, similar to the SSH one. +A simplicidade de ter uma única URL para todos os tipos de acesso e ter o servidor solicitando autenticação apenas quando ela é necessária torna as coisas muito fáceis para o usuário final. +Ser capaz de se autenticar com um nome de usuário e uma senha também é uma grande vantagem sobre o SSH, já que os usuários não precisam gerar chaves SSH localmente e fazer o upload da chave pública deles para o servidor antes de poder interagir com ele. +Para usuários menos sofisticados, ou usuários em sistemas em que o SSH é menos comum, essa é uma grande vantagem na usabilidade. +Também é um protocolo muito rápido e eficiente, semelhante ao SSH. -You can also serve your repositories read-only over HTTPS, which means you can encrypt the content transfer; or you can go so far as to make the clients use specific signed SSL certificates. +Você também pode servir os seus repositórios no modo de leitura (read-only) via HTTPS, o que significa que você pode criptografar a transferência de conteúdo; ou você pode ir tão longe a ponto de fazer os clientes usarem certificados SSL assinados específicos. -Another nice thing is that HTTP and HTTPS are such commonly used protocols that corporate firewalls are often set up to allow traffic through their ports. +Outra coisa boa é que HTTP e HTTPS são protocolos tão comumente usados ​​que os firewalls corporativos costumam ser configurados para permitir o tráfego em suas portas. -===== The Cons +===== Os Contras -Git over HTTPS can be a little more tricky to set up compared to SSH on some servers. -Other than that, there is very little advantage that other protocols have over Smart HTTP for serving Git content. +O Git via HTTPS pode ser um pouco mais complicado de configurar em comparação com o SSH em alguns servidores. +Fora isso, há muito pouca vantagem que outros protocolos tenham sobre o Smart HTTP para servir conteúdo Git. -If you're using HTTP for authenticated pushing, providing your credentials is sometimes more complicated than using keys over SSH. -There are, however, several credential caching tools you can use, including Keychain access on macOS and Credential Manager on Windows, to make this pretty painless. -Read <> to see how to set up secure HTTP password caching on your system. +Se você estiver usando HTTP para fazer o push autenticado, fornecer as suas credenciais às vezes é mais complicado do que usar chaves via SSH. +Há, no entanto, várias ferramentas de armazenamento em cache (caching tools) de credenciais que você pode usar, incluindo o acesso ao Keychain no macOS e o Gerenciador de Credenciais (Credential Manager) no Windows, para tornar isso bem indolor. +Leia <> para ver como configurar o cache de senha HTTP seguro no seu sistema. -==== The SSH Protocol +==== O Protocolo SSH (((protocols, SSH))) -A common transport protocol for Git when self-hosting is over SSH. -This is because SSH access to servers is already set up in most places -- and if it isn't, it's easy to do. -SSH is also an authenticated network protocol and, because it's ubiquitous, it's generally easy to set up and use. +Um protocolo de transporte comum para o Git ao fazer a auto-hospedagem (self-hosting) é sobre SSH. +Isso ocorre porque o acesso SSH a servidores já está configurado na maioria dos lugares -- e se não estiver, é fácil de fazer. +O SSH também é um protocolo de rede autenticado e, por ser onipresente, geralmente é fácil de configurar e usar. -To clone a Git repository over SSH, you can specify an `ssh://` URL like this: +Para clonar um repositório Git via SSH, você pode especificar uma URL `ssh://` como esta: [source,console] ---- $ git clone ssh://[user@]server/project.git ---- -Or you can use the shorter scp-like syntax for the SSH protocol: +Ou você pode usar a sintaxe mais curta, semelhante a scp, para o protocolo SSH: [source,console] ---- $ git clone [user@]server:project.git ---- -In both cases above, if you don't specify the optional username, Git assumes the user you're currently logged in as. +Em ambos os casos acima, se você não especificar o nome de usuário opcional, o Git assume o usuário com o qual você está logado no momento. -===== The Pros +===== Os Prós -The pros of using SSH are many. -First, SSH is relatively easy to set up -- SSH daemons are commonplace, many network admins have experience with them, and many OS distributions are set up with them or have tools to manage them. -Next, access over SSH is secure -- all data transfer is encrypted and authenticated. -Last, like the HTTPS, Git and Local protocols, SSH is efficient, making the data as compact as possible before transferring it. +Os prós do uso de SSH são muitos. +Primeiro, o SSH é relativamente fácil de configurar -- os daemons SSH são comuns, muitos administradores de rede têm experiência com eles e muitas distribuições de sistema operacional são configuradas com eles ou têm ferramentas para gerenciá-los. +Em seguida, o acesso via SSH é seguro -- toda a transferência de dados é criptografada e autenticada. +Por último, como os protocolos HTTPS, Git e Local, o SSH é eficiente, tornando os dados os mais compactos possíveis antes de transferi-los. -===== The Cons +===== Os Contras -The negative aspect of SSH is that it doesn't support anonymous access to your Git repository. -If you're using SSH, people _must_ have SSH access to your machine, even in a read-only capacity, which doesn't make SSH conducive to open source projects for which people might simply want to clone your repository to examine it. -If you're using it only within your corporate network, SSH may be the only protocol you need to deal with. -If you want to allow anonymous read-only access to your projects and also want to use SSH, you'll have to set up SSH for you to push over but something else for others to fetch from. +O aspecto negativo do SSH é que ele não suporta acesso anônimo ao seu repositório Git. +Se você estiver usando SSH, as pessoas _devem_ ter acesso SSH à sua máquina, mesmo em uma capacidade somente leitura (read-only), o que não torna o SSH propício para projetos de código aberto (open source) nos quais as pessoas podem simplesmente querer clonar o seu repositório para examiná-lo. +Se você estiver usando-o apenas na sua rede corporativa, o SSH pode ser o único protocolo com o qual você precise lidar. +Se você quiser permitir acesso anônimo somente leitura (read-only) aos seus projetos e também quiser usar SSH, terá que configurar o SSH para você fazer push, mas usar outra coisa para que os outros façam fetch. -==== The Git Protocol +==== O Protocolo Git (((protocols, git))) -Finally, we have the Git protocol. -This is a special daemon that comes packaged with Git; it listens on a dedicated port (9418) that provides a service similar to the SSH protocol, but with absolutely no authentication or cryptography. -In order for a repository to be served over the Git protocol, you must create a `git-daemon-export-ok` file -- the daemon won't serve a repository without that file in it -- but, other than that, there is no security. -Either the Git repository is available for everyone to clone, or it isn't. -This means that there is generally no pushing over this protocol. -You can enable push access but, given the lack of authentication, anyone on the internet who finds your project's URL could push to that project. -Suffice it to say that this is rare. - -===== The Pros - -The Git protocol is often the fastest network transfer protocol available. -If you're serving a lot of traffic for a public project or serving a very large project that doesn't require user authentication for read access, it's likely that you'll want to set up a Git daemon to serve your project. -It uses the same data-transfer mechanism as the SSH protocol but without the encryption and authentication overhead. - -===== The Cons - -Due to the lack of TLS or other cryptography, cloning over `git://` might lead to an arbitrary code execution vulnerability, and should therefore be avoided unless you know what you are doing. - -* If you run `git clone git://example.com/project.git`, an attacker who controls e.g your router can modify the repo you just cloned, inserting malicious code into it. - If you then compile/run the code you just cloned, you will execute the malicious code. - Running `git clone http://example.com/project.git` should be avoided for the same reason. -* Running `git clone https://example.com/project.git` does not suffer from the same problem (unless the attacker can provide a TLS certificate for example.com). - Running `git clone git@example.com:project.git` only suffers from this problem if you accept a wrong SSH key fingerprint. - -It also has no authentication, i.e. anyone can clone the repo (although this is often exactly what you want). -It's also probably the most difficult protocol to set up. -It must run its own daemon, which requires `xinetd` or `systemd` configuration or the like, which isn't always a walk in the park. -It also requires firewall access to port 9418, which isn't a standard port that corporate firewalls always allow. -Behind big corporate firewalls, this obscure port is commonly blocked. +Por fim, temos o protocolo Git. +Trata-se de um daemon especial que vem empacotado com o Git; ele escuta em uma porta dedicada (9418) que fornece um serviço semelhante ao protocolo SSH, mas sem nenhuma autenticação ou criptografia. +Para que um repositório seja servido por meio do protocolo Git, você deve criar um arquivo `git-daemon-export-ok` -- o daemon não servirá um repositório sem que esse arquivo esteja lá -- mas, além disso, não há segurança. +O repositório Git está disponível para qualquer pessoa clonar ou não está. +Isso significa que geralmente não há push por meio deste protocolo. +Você pode habilitar o acesso de push, mas, dada a falta de autenticação, qualquer pessoa na internet que encontre a URL do seu projeto pode fazer push para esse projeto. +Basta dizer que isso é raro. + +===== Os Prós + +O protocolo Git geralmente é o protocolo de transferência de rede mais rápido disponível. +Se você estiver servindo muito tráfego para um projeto público ou servindo um projeto muito grande que não requer autenticação de usuário para acesso de leitura (read access), é provável que você queira configurar um daemon do Git para servir o seu projeto. +Ele usa o mesmo mecanismo de transferência de dados que o protocolo SSH, mas sem a sobrecarga (overhead) de criptografia e autenticação. + +===== Os Contras + +Devido à falta de TLS ou outra criptografia, a clonagem por meio de `git://` pode levar a uma vulnerabilidade de execução arbitrária de código e, portanto, deve ser evitada, a menos que você saiba o que está fazendo. + +* Se você executar `git clone git://example.com/project.git`, um invasor que controle, por exemplo, o seu roteador, poderá modificar o repositório que você acabou de clonar, inserindo código malicioso nele. + Se você então compilar/executar o código que acabou de clonar, você executará o código malicioso. + Executar `git clone http://example.com/project.git` deve ser evitado pelo mesmo motivo. +* Executar `git clone https://example.com/project.git` não sofre do mesmo problema (a menos que o invasor consiga fornecer um certificado TLS para example.com). + Executar `git clone git@example.com:project.git` só sofre deste problema se você aceitar uma impressão digital (fingerprint) de chave SSH errada. + +Também não possui autenticação, ou seja, qualquer pessoa pode clonar o repositório (embora isso seja frequentemente exatamente o que você deseja). +Também é, provavelmente, o protocolo mais difícil de configurar. +Ele deve executar o seu próprio daemon, o que requer configuração do `xinetd` ou `systemd` ou algo semelhante, o que nem sempre é um passeio no parque (walk in the park). +Também requer acesso de firewall à porta 9418, que não é uma porta padrão que os firewalls corporativos sempre permitem. +Atrás de grandes firewalls corporativos, essa porta obscura geralmente é bloqueada. diff --git a/book/04-git-server/sections/setting-up-server.asc b/book/04-git-server/sections/setting-up-server.asc index bbb08295..aa9bf9c2 100644 --- a/book/04-git-server/sections/setting-up-server.asc +++ b/book/04-git-server/sections/setting-up-server.asc @@ -1,16 +1,16 @@ [[_setting_up_server]] -=== Setting Up the Server +=== Configurando o Servidor -Let's walk through setting up SSH access on the server side. -In this example, you'll use the `authorized_keys` method for authenticating your users. -We also assume you're running a standard Linux distribution like Ubuntu. +Vamos percorrer a configuração do acesso SSH no lado do servidor. +Neste exemplo, você usará o método `authorized_keys` para autenticar os seus usuários. +Também presumimos que você esteja executando uma distribuição Linux padrão como o Ubuntu. [NOTE] ==== -A good deal of what is described here can be automated by using the `ssh-copy-id` command, rather than manually copying and installing public keys. +Grande parte do que é descrito aqui pode ser automatizado usando o comando `ssh-copy-id`, em vez de copiar e instalar manualmente chaves públicas. ==== -First, you create a `git` user account and a `.ssh` directory for that user. +Primeiro, você cria uma conta de usuário `git` e um diretório `.ssh` para esse usuário. [source,console] ---- @@ -21,9 +21,9 @@ $ mkdir .ssh && chmod 700 .ssh $ touch .ssh/authorized_keys && chmod 600 .ssh/authorized_keys ---- -Next, you need to add some developer SSH public keys to the `authorized_keys` file for the `git` user. -Let's assume you have some trusted public keys and have saved them to temporary files. -Again, the public keys look something like this: +Em seguida, você precisa adicionar algumas chaves públicas SSH de desenvolvedor ao arquivo `authorized_keys` para o usuário `git`. +Vamos supor que você tenha algumas chaves públicas confiáveis e as tenha salvo em arquivos temporários. +Novamente, as chaves públicas se parecem com algo assim: [source,console] ---- @@ -36,7 +36,7 @@ O7TCUSBdLQlgMVOFq1I2uPWQOkOWQAHukEOmfjy2jctxSDBQ220ymjaNsHT4kgtZg2AYYgPq dAv8JggJICUvax2T9va5 gsg-keypair ---- -You just append them to the `git` user's `authorized_keys` file in its `.ssh` directory: +Basta anexá-las ao arquivo `authorized_keys` do usuário `git` em seu diretório `.ssh`: [source,console] ---- @@ -45,7 +45,7 @@ $ cat /tmp/id_rsa.josie.pub >> ~/.ssh/authorized_keys $ cat /tmp/id_rsa.jessica.pub >> ~/.ssh/authorized_keys ---- -Now, you can set up an empty repository for them by running `git init` with the `--bare` option, which initializes the repository without a working directory:(((git commands, init, bare))) +Agora, você pode configurar um repositório vazio para eles executando `git init` com a opção `--bare`, que inicializa o repositório sem um diretório de trabalho:(((git commands, init, bare))) [source,console] ---- @@ -56,10 +56,10 @@ $ git init --bare Initialized empty Git repository in /srv/git/project.git/ ---- -Then, John, Josie, or Jessica can push the first version of their project into that repository by adding it as a remote and pushing up a branch. -Note that someone must shell onto the machine and create a bare repository every time you want to add a project. -Let's use `gitserver` as the hostname of the server on which you've set up your `git` user and repository. -If you're running it internally, and you set up DNS for `gitserver` to point to that server, then you can use the commands pretty much as is (assuming that `myproject` is an existing project with files in it): +Então, John, Josie ou Jessica podem fazer o push da primeira versão do projeto deles para esse repositório, adicionando-o como remoto e fazendo o push de um branch. +Observe que alguém deve acessar o shell da máquina e criar um repositório nu toda vez que você quiser adicionar um projeto. +Vamos usar `gitserver` como o hostname do servidor no qual você configurou o seu usuário `git` e repositório. +Se você o estiver executando internamente e configurar o DNS do `gitserver` para apontar para esse servidor, poderá usar os comandos da mesma forma (assumindo que `myproject` é um projeto existente com arquivos nele): [source,console] ---- @@ -72,7 +72,7 @@ $ git remote add origin git@gitserver:/srv/git/project.git $ git push origin master ---- -At this point, the others can clone it down and push changes back up just as easily: +Neste ponto, os outros podem clonar e fazer o push das alterações de volta com a mesma facilidade: [source,console] ---- @@ -83,15 +83,15 @@ $ git commit -am 'Fix for README file' $ git push origin master ---- -With this method, you can quickly get a read/write Git server up and running for a handful of developers. +Com este método, você pode colocar um servidor Git de leitura/gravação em funcionamento rapidamente para um punhado de desenvolvedores. -You should note that currently all these users can also log into the server and get a shell as the `git` user. -If you want to restrict that, you will have to change the shell to something else in the `/etc/passwd` file. +Você deve notar que atualmente todos esses usuários também podem logar no servidor e obter um shell como o usuário `git`. +Se você quiser restringir isso, terá que alterar o shell para outra coisa no arquivo `/etc/passwd`. -You can easily restrict the `git` user account to only Git-related activities with a limited shell tool called `git-shell` that comes with Git. -If you set this as the `git` user account's login shell, then that account can't have normal shell access to your server. -To use this, specify `git-shell` instead of `bash` or `csh` for that account's login shell. -To do so, you must first add the full pathname of the `git-shell` command to `/etc/shells` if it's not already there: +Você pode restringir facilmente a conta de usuário `git` a apenas atividades relacionadas ao Git com uma ferramenta de shell limitado chamada `git-shell` que vem com o Git. +Se você definir isso como o login shell da conta de usuário `git`, então essa conta não poderá ter acesso de shell normal ao seu servidor. +Para usar isso, especifique `git-shell` em vez de `bash` ou `csh` para o login shell dessa conta. +Para fazer isso, você deve primeiro adicionar o nome do caminho completo (pathname) do comando `git-shell` em `/etc/shells`, se ele ainda não estiver lá: [source,console] ---- @@ -100,15 +100,15 @@ $ which git-shell # make sure git-shell is installed on your system. $ sudo -e /etc/shells # and add the path to git-shell from last command ---- -Now you can edit the shell for a user using `chsh -s `: +Agora você pode editar o shell para um usuário usando `chsh -s `: [source,console] ---- $ sudo chsh git -s $(which git-shell) ---- -Now, the `git` user can still use the SSH connection to push and pull Git repositories but can't shell onto the machine. -If you try, you'll see a login rejection like this: +Agora, o usuário `git` ainda pode usar a conexão SSH para fazer o push e o pull de repositórios Git, mas não pode usar o shell na máquina. +Se você tentar, verá uma rejeição de login como esta: [source,console] ---- @@ -118,15 +118,15 @@ hint: ~/git-shell-commands should exist and have read and execute access. Connection to gitserver closed. ---- -At this point, users are still able to use SSH port forwarding to access any host the git server is able to reach. -If you want to prevent that, you can edit the `authorized_keys` file and prepend the following options to each key you'd like to restrict: +Neste ponto, os usuários ainda conseguem usar o encaminhamento de porta SSH para acessar qualquer host que o servidor git consiga alcançar. +Se você quiser evitar isso, pode editar o arquivo `authorized_keys` e adicionar as seguintes opções antes de cada chave que gostaria de restringir: [source,console] ---- no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty ---- -The result should look like this: +O resultado deve ficar assim: [source,console] ---- @@ -143,7 +143,7 @@ no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDEwENNMomTboYI+LJieaAY16qiXiH3wuvENhBG... ---- -Now Git network commands will still work just fine but the users won't be able to get a shell. -As the output states, you can also set up a directory in the `git` user's home directory that customizes the `git-shell` command a bit. -For instance, you can restrict the Git commands that the server will accept or you can customize the message that users see if they try to SSH in like that. -Run `git help shell` for more information on customizing the shell.(((git commands, help))) +Agora, os comandos de rede do Git ainda funcionarão perfeitamente, mas os usuários não conseguirão obter um shell. +Como a saída (output) indica, você também pode configurar um diretório no diretório inicial (home) do usuário `git` que personaliza um pouco o comando `git-shell`. +Por exemplo, você pode restringir os comandos Git que o servidor aceitará ou pode personalizar a mensagem que os usuários veem se tentarem fazer SSH dessa forma. +Execute `git help shell` para obter mais informações sobre a personalização do shell.(((git commands, help))) diff --git a/book/04-git-server/sections/smart-http.asc b/book/04-git-server/sections/smart-http.asc index 753d34cd..74e70bf5 100644 --- a/book/04-git-server/sections/smart-http.asc +++ b/book/04-git-server/sections/smart-http.asc @@ -1,14 +1,14 @@ === Smart HTTP (((serving repositories, HTTP))) -We now have authenticated access through SSH and unauthenticated access through `git://`, but there is also a protocol that can do both at the same time. -Setting up Smart HTTP is basically just enabling a CGI script that is provided with Git called `git-http-backend` on the server.(((git commands, "http-backend"))) -This CGI will read the path and headers sent by a `git fetch` or `git push` to an HTTP URL and determine if the client can communicate over HTTP (which is true for any client since version 1.6.6). -If the CGI sees that the client is smart, it will communicate smartly with it; otherwise it will fall back to the dumb behavior (so it is backward compatible for reads with older clients). +Agora temos acesso autenticado via SSH e acesso não autenticado via `git://`, mas também há um protocolo que pode fazer as duas coisas ao mesmo tempo. +Configurar o Smart HTTP é basicamente habilitar um script CGI que é fornecido com o Git chamado `git-http-backend` no servidor.(((git commands, "http-backend"))) +Este CGI lerá o caminho e os cabeçalhos enviados por um `git fetch` ou `git push` para uma URL HTTP e determinará se o cliente pode se comunicar por HTTP (o que é verdadeiro para qualquer cliente desde a versão 1.6.6). +Se o CGI vir que o cliente é inteligente (smart), ele se comunicará inteligentemente com ele; caso contrário, recorrerá (fall back) ao comportamento burro (dumb behavior) (portanto, é retrocompatível para leituras com clientes mais antigos). -Let's walk through a very basic setup. -We'll set this up with Apache as the CGI server. -If you don't have Apache setup, you can do so on a Linux box with something like this:(((Apache))) +Vamos analisar uma configuração muito básica. +Vamos configurar isso com o Apache como servidor CGI. +Se você não tem o Apache configurado, você pode fazê-lo em uma máquina Linux com algo assim:(((Apache))) [source,console] ---- @@ -16,16 +16,16 @@ $ sudo apt-get install apache2 apache2-utils $ a2enmod cgi alias env ---- -This also enables the `mod_cgi`, `mod_alias`, and `mod_env` modules, which are all needed for this to work properly. +Isso também habilita os módulos `mod_cgi`, `mod_alias` e `mod_env`, que são todos necessários para que isso funcione corretamente. -You'll also need to set the Unix user group of the `/srv/git` directories to `www-data` so your web server can read- and write-access the repositories, because the Apache instance running the CGI script will (by default) be running as that user: +Você também precisará definir o grupo de usuários Unix dos diretórios `/srv/git` para `www-data` para que o seu servidor web possa ter acesso de leitura e gravação aos repositórios, porque a instância do Apache executando o script CGI estará (por padrão) sendo executada como aquele usuário: [source,console] ---- $ chgrp -R www-data /srv/git ---- -Next we need to add some things to the Apache configuration to run the `git-http-backend` as the handler for anything coming into the `/git` path of your web server. +Em seguida, precisamos adicionar algumas coisas à configuração do Apache para executar o `git-http-backend` como o manipulador (handler) de qualquer coisa que chegue ao caminho `/git` do seu servidor web. [source,console] ---- @@ -34,9 +34,9 @@ SetEnv GIT_HTTP_EXPORT_ALL ScriptAlias /git/ /usr/lib/git-core/git-http-backend/ ---- -If you leave out `GIT_HTTP_EXPORT_ALL` environment variable, then Git will only serve to unauthenticated clients the repositories with the `git-daemon-export-ok` file in them, just like the Git daemon did. +Se você omitir a variável de ambiente `GIT_HTTP_EXPORT_ALL`, o Git servirá aos clientes não autenticados apenas os repositórios com o arquivo `git-daemon-export-ok` neles, assim como o Git daemon fez. -Finally you'll want to tell Apache to allow requests to `git-http-backend` and make writes be authenticated somehow, possibly with an Auth block like this: +Finalmente, você vai querer dizer ao Apache para permitir requisições ao `git-http-backend` e fazer com que as gravações sejam autenticadas de alguma forma, possivelmente com um bloco Auth como este: [source,console] ---- @@ -49,24 +49,24 @@ Finally you'll want to tell Apache to allow requests to `git-http-backend` and m ---- -That will require you to create a `.htpasswd` file containing the passwords of all the valid users. -Here is an example of adding a "`schacon`" user to the file: +Isso exigirá que você crie um arquivo `.htpasswd` contendo as senhas de todos os usuários válidos. +Aqui está um exemplo de adição de um usuário "`schacon`" ao arquivo: [source,console] ---- $ htpasswd -c /srv/git/.htpasswd schacon ---- -There are tons of ways to have Apache authenticate users, you'll have to choose and implement one of them. -This is just the simplest example we could come up with. -You'll also almost certainly want to set this up over SSL so all this data is encrypted. +Há inúmeras maneiras de fazer o Apache autenticar usuários, você terá que escolher e implementar uma delas. +Este é apenas o exemplo mais simples que pudemos imaginar. +Você quase certamente também vai querer configurar isso com SSL para que todos esses dados sejam criptografados. -We don't want to go too far down the rabbit hole of Apache configuration specifics, since you could well be using a different server or have different authentication needs. -The idea is that Git comes with a CGI called `git-http-backend` that when invoked will do all the negotiation to send and receive data over HTTP. -It does not implement any authentication itself, but that can easily be controlled at the layer of the web server that invokes it. -You can do this with nearly any CGI-capable web server, so go with the one that you know best. +Não queremos nos aprofundar muito na toca do coelho (rabbit hole) dos detalhes da configuração do Apache, pois você pode muito bem estar usando um servidor diferente ou ter necessidades de autenticação diferentes. +A ideia é que o Git vem com um CGI chamado `git-http-backend` que, quando invocado, fará toda a negociação para enviar e receber dados via HTTP. +Ele não implementa nenhuma autenticação em si, mas isso pode ser facilmente controlado na camada do servidor web que o invoca. +Você pode fazer isso com quase qualquer servidor web com capacidade para CGI, então escolha o que você conhece melhor. [NOTE] ==== -For more information on configuring authentication in Apache, check out the Apache docs here: https://httpd.apache.org/docs/current/howto/auth.html[^]. +Para mais informações sobre a configuração de autenticação no Apache, confira a documentação do Apache aqui: https://httpd.apache.org/docs/current/howto/auth.html[^]. ==== diff --git a/ch04-git-on-the-server.asc b/ch04-git-on-the-server.asc index a867a63c..7d2c6f0f 100644 --- a/ch04-git-on-the-server.asc +++ b/ch04-git-on-the-server.asc @@ -1,24 +1,24 @@ [[ch04-git-on-the-server]] -== Git on the Server +== Git no Servidor (((serving repositories))) -At this point, you should be able to do most of the day-to-day tasks for which you'll be using Git. -However, in order to do any collaboration in Git, you'll need to have a remote Git repository. -Although you can technically push changes to and pull changes from individuals' repositories, doing so is discouraged because you can fairly easily confuse what they're working on if you're not careful. -Furthermore, you want your collaborators to be able to access the repository even if your computer is offline -- having a more reliable common repository is often useful. -Therefore, the preferred method for collaborating with someone is to set up an intermediate repository that you both have access to, and push to and pull from that. +Neste ponto, você deve ser capaz de realizar a maioria das tarefas do dia a dia para as quais usará o Git. +No entanto, para fazer qualquer colaboração no Git, você precisará ter um repositório Git remoto. +Embora você possa tecnicamente fazer push de alterações e pull de alterações dos repositórios de indivíduos, fazer isso é desencorajado porque você pode facilmente confundir no que eles estão trabalhando se não for cuidadoso. +Além disso, você quer que seus colaboradores possam acessar o repositório mesmo se o seu computador estiver offline -- ter um repositório comum mais confiável costuma ser útil. +Portanto, o método preferido para colaborar com alguém é configurar um repositório intermediário ao qual ambos tenham acesso e fazer push e pull dele. -Running a Git server is fairly straightforward. -First, you choose which protocols you want your server to support. -The first section of this chapter will cover the available protocols and the pros and cons of each. -The next sections will explain some typical setups using those protocols and how to get your server running with them. -Last, we'll go over a few hosted options, if you don't mind hosting your code on someone else's server and don't want to go through the hassle of setting up and maintaining your own server. +Executar um servidor Git é bastante simples. +Primeiro, você escolhe quais protocolos deseja que o seu servidor suporte. +A primeira seção deste capítulo abordará os protocolos disponíveis e os prós e contras de cada um. +As próximas seções explicarão algumas configurações típicas usando esses protocolos e como colocar o seu servidor para rodar com eles. +Por último, abordaremos algumas opções hospedadas (hosted), se você não se importa em hospedar o seu código no servidor de outra pessoa e não quer passar pelo aborrecimento de configurar e manter o seu próprio servidor. -If you have no interest in running your own server, you can skip to the last section of the chapter to see some options for setting up a hosted account and then move on to the next chapter, where we discuss the various ins and outs of working in a distributed source control environment. +Se você não tem interesse em executar o seu próprio servidor, pode pular para a última seção do capítulo para ver algumas opções para configurar uma conta hospedada (hosted account) e depois passar para o próximo capítulo, onde discutimos os vários detalhes do trabalho em um ambiente de controle de fonte distribuído. -A remote repository is generally a _bare repository_ -- a Git repository that has no working directory. -Because the repository is only used as a collaboration point, there is no reason to have a snapshot checked out on disk; it's just the Git data. -In the simplest terms, a bare repository is the contents of your project's `.git` directory and nothing else. +Um repositório remoto geralmente é um _bare repository_ (repositório nu) -- um repositório Git que não tem diretório de trabalho. +Como o repositório é usado apenas como um ponto de colaboração, não há motivo para ter um snapshot com checkout no disco; são apenas os dados do Git. +Nos termos mais simples, um repositório nu é o conteúdo do diretório `.git` do seu projeto e nada mais. include::book/04-git-server/sections/protocols.asc[] @@ -38,11 +38,11 @@ include::book/04-git-server/sections/gitlab.asc[] include::book/04-git-server/sections/hosted.asc[] -=== Summary +=== Resumo -You have several options to get a remote Git repository up and running so that you can collaborate with others or share your work. +Você tem várias opções para colocar um repositório Git remoto em funcionamento para poder colaborar com outras pessoas ou compartilhar o seu trabalho. -Running your own server gives you a lot of control and allows you to run the server within your own firewall, but such a server generally requires a fair amount of your time to set up and maintain. -If you place your data on a hosted server, it's easy to set up and maintain; however, you have to be able to keep your code on someone else's servers, and some organizations don't allow that. +Executar o seu próprio servidor lhe dá muito controle e permite que você execute o servidor dentro do seu próprio firewall, mas um servidor assim geralmente requer uma boa quantidade do seu tempo para configurar e manter. +Se você colocar os seus dados em um servidor hospedado, é fácil configurar e manter; no entanto, você precisa ser capaz de manter o seu código nos servidores de outra pessoa, e algumas organizações não permitem isso. -It should be fairly straightforward to determine which solution or combination of solutions is appropriate for you and your organization. +Deve ser bastante simples determinar qual solução ou combinação de soluções é apropriada para você e a sua organização. From 0369ef0e27fc55cb31fdd54f077f5b3bd841a192 Mon Sep 17 00:00:00 2001 From: "Sergio Cabral (AI Agent)" Date: Thu, 20 Aug 2026 13:51:58 -0300 Subject: [PATCH 07/16] =?UTF-8?q?Traduz:=20Cap=C3=ADtulo=205=20=E2=80=94?= =?UTF-8?q?=20Git=20Distribu=C3=ADdo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../sections/contributing.asc | 490 +++++++++--------- .../sections/distributed-workflows.asc | 136 ++--- .../sections/maintaining.asc | 396 +++++++------- ch05-distributed-git.asc | 16 +- 4 files changed, 519 insertions(+), 519 deletions(-) diff --git a/book/05-distributed-git/sections/contributing.asc b/book/05-distributed-git/sections/contributing.asc index 2c6b0851..db7d9039 100644 --- a/book/05-distributed-git/sections/contributing.asc +++ b/book/05-distributed-git/sections/contributing.asc @@ -1,66 +1,66 @@ [[_contributing_project]] -=== Contributing to a Project +=== Contribuindo com um Projeto (((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 para um projeto são as inúmeras variações sobre como fazer isso. +Como o Git é muito flexível, as pessoas podem e trabalham juntas de muitas maneiras, e é problemático descrever como você deve contribuir -- cada projeto é um pouco diferente. +Algumas das variáveis envolvidas são a contagem de contribuidores ativos, o fluxo de trabalho escolhido, o seu acesso de commit e possivelmente o método de contribuição externa. + +A primeira variável é a contagem de contribuidores ativos -- quantos usuários estão contribuindo ativamente com código para este projeto e com que frequência? +Em muitos casos, você terá dois ou três desenvolvedores com alguns commits por dia, ou possivelmente menos para projetos um tanto inativos (dormant). +Para empresas ou projetos maiores, o número de desenvolvedores pode ser na casa dos milhares, com centenas ou milhares de commits chegando a cada dia. +Isso é importante porque, com cada vez mais desenvolvedores, você se depara com mais problemas para garantir que o seu código se aplique de forma limpa ou possa ser facilmente mesclado. +As alterações que você envia podem se tornar obsoletas ou gravemente corrompidas por trabalhos que são mesclados enquanto você estava trabalhando ou enquanto as suas alterações estavam aguardando para serem aprovadas ou aplicadas. +Como você pode manter o seu código consistentemente atualizado e os seus commits válidos? + +A próxima variável é o fluxo de trabalho em uso para o projeto. +Ele é centralizado, com cada desenvolvedor tendo igual acesso de gravação à linha de código principal? +O projeto tem um mantenedor ou gerente de integração que verifica todos os patches? +Todos os patches são revisados por pares e aprovados? +Você está envolvido nesse processo? +Existe um sistema de tenentes (lieutenant) em vigor, e você tem que submeter o seu trabalho a eles primeiro? + +A próxima variável é o seu acesso de commit. +O fluxo de trabalho necessário para contribuir para um projeto é muito diferente se você tem acesso de gravação ao projeto do que se você não tem. +Se você não tem acesso de gravação, como o projeto prefere aceitar o trabalho contribuído? +Ele sequer tem uma política? +Quanto trabalho você está contribuindo de uma vez? +Com que frequência você contribui? + +Todas essas questões podem afetar como você contribui de forma eficaz para um projeto e quais fluxos de trabalho são preferidos ou estão disponíveis para você. +Abordaremos aspectos de cada uma delas em uma série de casos de uso, passando do simples para o mais complexo; você deve ser capaz de construir os fluxos de trabalho específicos de que precisa na prática a partir desses exemplos. [[_commit_guidelines]] -==== Commit Guidelines +==== Diretrizes de Commit -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 começarmos a examinar os casos de uso específicos, aqui vai uma nota rápida sobre mensagens de commit. +Ter uma boa diretriz para criar commits e cumpri-la torna o trabalho com o Git e a colaboração com outras pessoas muito mais fáceis. +O projeto Git fornece um documento que expõe várias boas dicas para criar commits a partir dos quais 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, as suas submissões não devem conter erros de espaço em branco (whitespace). +O Git fornece uma maneira fácil de verificar isso -- antes de fazer o commit, execute `git diff --check`, o qual identifica possíveis erros de espaço em branco e os lista para você. -.Output of `git diff --check` -image::images/git-diff-check.png[Output of `git diff --check`] +.Saída do `git diff --check` +image::images/git-diff-check.png[Saída do `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 esse comando antes de fazer o commit, poderá saber se está prestes a commitar problemas de espaço em branco que podem irritar 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. +Em seguida, tente fazer de cada commit um conjunto de alterações (changeset) logicamente separado. +Se puder, tente tornar as suas alterações digeríveis -- não codifique um fim de semana inteiro sobre cinco issues diferentes e depois as envie todas como um único commit enorme na segunda-feira. +Mesmo que você não faça commits durante o fim de semana, use a área de preparo (staging area) na segunda-feira para dividir o seu trabalho em pelo menos um commit por issue, com uma mensagem útil por commit. +Se algumas das alterações modificarem o mesmo arquivo, tente usar `git add --patch` para preparar arquivos parcialmente (abordado em detalhes em <>). +O snapshot do projeto na ponta do branch é idêntico quer você faça um ou cinco commits, desde que todas as alterações sejam adicionadas em algum momento, então tente facilitar as coisas para os seus colegas desenvolvedores quando eles tiverem que revisar as suas alterações. -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 torna mais fácil extrair ou reverter um dos conjuntos de alterações se você precisar mais tarde. +A seção <> descreve uma série de truques úteis do Git para reescrever o histórico e preparar arquivos interativamente -- use essas ferramentas para ajudar a criar um histórico limpo e compreensível antes de enviar o trabalho para outra pessoa. -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 a ter em mente é a mensagem de commit. +Adquirir o hábito de criar mensagens de commit de qualidade torna o uso e a colaboração com o Git muito mais fáceis. +Como regra geral, as suas mensagens devem começar com uma única linha que não tenha mais de 50 caracteres e que descreva o conjunto de alterações de forma concisa, seguida por uma linha em branco, seguida por uma explicação mais detalhada. +O projeto Git requer que a explicação mais detalhada inclua a sua motivação para a alteração e contraste a sua implementação com o comportamento anterior -- esta é uma boa diretriz a seguir. +Escreva sua mensagem de commit no imperativo: "Fix bug", e não "Fixed bug" nem "Fixes bug.". +Aqui está um modelo (template) que você pode seguir, o qual adaptamos levemente de um https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html[originalmente escrito por Tim Pope^]: [source,text] ---- @@ -87,30 +87,30 @@ Further paragraphs come after blank lines. - Use a hanging indent ---- -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 para os desenvolvedores com quem você colabora. +O projeto Git tem mensagens de commit bem formatadas -- tente rodar `git log --no-merges` nele para ver como se parece o histórico de commits de um projeto bem formatado. [NOTE] -.Do as we say, not as we do. +.Faça o que dizemos, não o que fazemos. ==== -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 fins de concisão, muitos dos exemplos neste livro não têm mensagens de commit bem formatadas como esta; em vez disso, nós simplesmente usamos a opção `-m` com o `git commit`. -In short, do as we say, not as we do. +Em resumo, faça o que dizemos, não o que fazemos. ==== [[_private_team]] -==== Private Small Team +==== Equipe Pequena Privada (((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ê provavelmente encontrará é um projeto privado com um ou dois outros desenvolvedores. +"`Privado`" (Private), neste contexto, significa código fechado (closed-source) -- não acessível ao mundo exterior. +Você e todos os outros desenvolvedores têm acesso de push ao 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 semelhante ao que faria ao usar o Subversion ou outro sistema centralizado. +Você ainda obtém as vantagens de coisas como commits offline e ramificações e mesclagens muito mais simples, mas o fluxo de trabalho pode ser muito semelhante; a principal diferença é que os merges acontecem do lado do cliente em vez de no servidor na hora do commit. +Vamos ver como isso pode ser quando dois desenvolvedores começam a trabalhar juntos com um repositório compartilhado. +O primeiro desenvolvedor, John, clona o repositório, faz uma alteração e faz o commit localmente. +As mensagens de protocolo foram substituídas por `...` nesses exemplos para encurtá-las um pouco. [source,console] ---- @@ -125,7 +125,7 @@ $ git commit -am 'Remove invalid default value' 1 files changed, 1 insertions(+), 1 deletions(-) ---- -The second developer, Jessica, does the same thing -- clones the repository and commits a change: +A segunda desenvolvedora, Jessica, faz a mesma coisa -- clona o repositório e faz o commit de uma alteração: [source,console] ---- @@ -140,7 +140,7 @@ $ git commit -am 'Add reset task' 1 files changed, 1 insertions(+), 0 deletions(-) ---- -Now, Jessica pushes her work to the server, which works just fine: +Agora, Jessica faz o push do seu trabalho para o servidor, o que funciona muito bem: [source,console] ---- @@ -151,12 +151,12 @@ 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 da saída acima mostra uma mensagem de retorno útil da operação push. +O formato básico é `.. fromref -> toref`, onde `oldref` significa a referência antiga, `newref` significa a nova referência, `fromref` é o nome da referência local sofrendo o push, e `toref` é o nome da referência remota sendo atualizada. +Você verá saídas semelhantes a esta nas discussões a seguir, portanto, ter uma ideia básica do significado ajudará a entender os vários estados dos repositórios. +Mais detalhes estão disponíveis na documentação do 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 tempo depois, John faz algumas alterações, faz o commit delas no seu repositório local e tenta fazer o push para o mesmo servidor: [source,console] ---- @@ -167,12 +167,12 @@ To john@githost:simplegit.git 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 de John falha por causa do push anterior de Jessica com as alterações _dela_. +Isso é especialmente importante de entender se você estiver acostumado com o Subversion, porque você notará que os dois desenvolvedores não editaram o mesmo arquivo. +Embora o Subversion faça tal mesclagem (merge) automaticamente no servidor se arquivos diferentes forem editados, com o Git, você deve _primeiro_ mesclar os commits localmente. +Em outras palavras, John deve primeiro fazer o fetch das alterações upstream de Jessica e mesclá-las no seu repositório local antes de ter permissão para fazer o 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 primeiro passo, John faz o fetch do trabalho de Jessica (isso apenas _faz o fetch_ do trabalho upstream de Jessica, ainda não o mescla no trabalho de John): [source,console] ---- @@ -182,12 +182,12 @@ 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 de John se parece com isso: -.John's divergent history -image::images/small-team-1.png[John's divergent history] +.Histórico divergente de John +image::images/small-team-1.png[Histórico divergente de John] -Now John can merge Jessica's work that he fetched into his own local work: +Agora John pode mesclar o trabalho de Jessica que ele buscou (fetched) no seu próprio trabalho local: [source,console] ---- @@ -197,12 +197,12 @@ Merge made by the 'recursive' strategy. 1 files changed, 1 insertions(+), 0 deletions(-) ---- -As long as that local merge goes smoothly, John's updated history will now look like this: +Desde que essa mesclagem local ocorra sem problemas, o histórico atualizado de John agora se parecerá com isso: -.John's repository after merging `origin/master` -image::images/small-team-2.png[John's repository after merging `origin/master`] +.Repositório de John após mesclar `origin/master` +image::images/small-team-2.png[Repositório de John após mesclar 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 pode querer testar este novo código para garantir que nenhum dos trabalhos de Jessica afete o dele e, desde que tudo pareça bem, ele pode finalmente fazer o push do novo trabalho mesclado para o servidor: [source,console] ---- @@ -212,18 +212,18 @@ To john@githost:simplegit.git fbff5bc..72bbc59 master -> master ---- -In the end, John's commit history will look like this: +No final, o histórico de commits de John ficará assim: -.John's history after pushing to the `origin` server -image::images/small-team-3.png[John's history after pushing to the `origin` server] +.Histórico de John após o push para o servidor `origin` +image::images/small-team-3.png[Histórico de John após o push para o servidor origin] -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 de tópico chamado `issue54`, e fez três commits nesse branch. +Ela ainda não fez o fetch das alterações de John, então o histórico de commits dela é este: -.Jessica's topic branch -image::images/small-team-4.png[Jessica's topic branch] +.Branch de tópico de Jessica +image::images/small-team-4.png[Branch de tópico de Jessica] -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 descobre que John fez o push de um novo trabalho para o servidor e ela quer dar uma olhada, então ela pode fazer o fetch de todo o conteúdo novo do servidor que ela ainda não tem, com: [source,console] ---- @@ -234,14 +234,14 @@ 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: +Isso puxa (pulls down) o trabalho que John fez o push enquanto isso. +O histórico de Jessica agora está assim: -.Jessica's history after fetching John's changes -image::images/small-team-5.png[Jessica's history after fetching John's changes] +.Histórico de Jessica após buscar (fetching) as alterações de John +image::images/small-team-5.png[Histórico de Jessica após buscar as alterações de John] -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 o seu branch de tópico está pronto, mas ela quer saber qual parte do trabalho que ela buscou de John ela tem que mesclar no trabalho dela para que ela possa fazer o push. +Ela executa `git log` para descobrir: [source,console] ---- @@ -253,15 +253,15 @@ Date: Fri May 29 16:01:27 2009 -0700 Remove invalid default value ---- -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`) and 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 para exibir apenas os commits que estão no último branch (neste caso `origin/master`) e que não estão no primeiro branch (neste caso `issue54`). +Abordaremos essa sintaxe detalhadamente 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. +A partir da saída acima, podemos ver que há um único commit que John fez que Jessica não mesclou em seu trabalho local. +Se ela mesclar `origin/master`, esse é o único commit que modificará o 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 o seu trabalho de tópico no seu branch `master`, mesclar o trabalho de John (`origin/master`) no seu branch `master` e, em seguida, fazer o push de volta para o servidor novamente. -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 o commit de todo o trabalho no seu branch de tópico `issue54`), Jessica muda de volta para o seu branch `master` em preparação para integrar todo esse trabalho: [source,console] ---- @@ -270,9 +270,9 @@ Switched to branch 'master' Your branch is behind 'origin/master' by 2 commits, 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` quanto `issue54` primeiro -- ambos são upstream, então a ordem não importa. +O snapshot final deve ser idêntico, não importa qual ordem ela escolha; apenas o histórico será diferente. +Ela escolhe mesclar o branch `issue54` primeiro: [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 mesclagem fast-forward. +Jessica agora conclui o processo de mesclagem local mesclando o trabalho de John buscado (fetched) anteriormente que está 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 se mescla de forma limpa, e o histórico de Jessica agora fica assim: -.Jessica's history after merging John's changes -image::images/small-team-6.png[Jessica's history after merging John's changes] +.Histórico de Jessica após mesclar as alterações de John +image::images/small-team-6.png[Histórico de Jessica após mesclar as alterações de John] -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` pode ser alcançado a partir do branch `master` de Jessica, então ela deve ser capaz de fazer o push com sucesso (supondo que John não tenha feito o push de ainda mais alterações nesse meio tempo): [source,console] ---- @@ -311,32 +311,32 @@ 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 commits e mesclou o trabalho do outro com sucesso. -.Jessica's history after pushing all changes back to the server -image::images/small-team-7.png[Jessica's history after pushing all changes back to the server] +.Histórico de Jessica após o push de todas as alterações de volta para o servidor +image::images/small-team-7.png[Histórico de Jessica após o push de todas as alterações de volta para o servidor] -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: +Esse é um dos fluxos de trabalho mais simples. +Você trabalha por um tempo (geralmente em um branch de tópico), e mescla esse trabalho no seu branch `master` quando ele estiver pronto para ser integrado. +Quando você quiser compartilhar esse trabalho, você faz o fetch e o merge do seu `master` a partir do `origin/master` se ele tiver mudado, e finalmente faz o push para o branch `master` no servidor. +A sequência geral é algo assim: -.General sequence of events for a simple multiple-developer Git workflow -image::images/small-team-flow.png[General sequence of events for a simple multiple-developer Git workflow] +.Sequência geral de eventos para um fluxo de trabalho Git simples com múltiplos desenvolvedores +image::images/small-team-flow.png[Sequência geral de eventos para um fluxo de trabalho Git simples com múltiplos desenvolvedores] -==== Private Managed Team +==== Equipe Gerenciada Privada (((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. +Neste próximo cenário, você analisará os papéis dos contribuidores em um grupo privado maior. +Você aprenderá como trabalhar em um ambiente onde pequenos grupos colaboram em recursos, após o qual essas contribuições baseadas em equipe são integradas por outra parte. -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 estejam trabalhando juntos em um recurso (vamos chamá-lo de "`featureA`"), enquanto Jessica e uma terceira desenvolvedora, Josie, estão trabalhando em um segundo (digamos, "`featureB`"). +Neste caso, a empresa está usando um tipo de fluxo de trabalho de gerente de integração onde o trabalho dos grupos individuais é integrado apenas por certos engenheiros, e o branch `master` do repositório principal pode ser atualizado apenas por esses engenheiros. +Neste cenário, todo o trabalho é feito em branches baseados em equipe e puxados (pulled) juntos pelos integradores mais tarde. -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 seguir o fluxo de trabalho de Jessica enquanto ela trabalha nos seus dois recursos, colaborando em paralelo com dois desenvolvedores diferentes neste ambiente. +Supondo que ela já tenha o seu repositório clonado, ela decide trabalhar em `featureA` primeiro. +Ela cria um novo branch para o recurso e trabalha um pouco nele lá: [source,console] ---- @@ -349,8 +349,8 @@ $ git commit -am 'Add limit to log function' 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 o seu trabalho com John, então ela faz o push dos commits do seu branch `featureA` para o servidor. +Jessica não tem acesso de push ao branch `master` -- apenas os integradores têm -- então ela tem que fazer o push para outro branch para colaborar com John: [source,console] ---- @@ -360,9 +360,9 @@ 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 envia um e-mail para John para avisá-lo que ela fez o push de algum trabalho em um branch chamado `featureA` e que ele pode dar uma olhada agora. +Enquanto ela espera pelo feedback de John, Jessica decide começar a trabalhar no `featureB` com Josie. +Para começar, ela inicia um novo branch de recurso, baseando-o no branch `master` do servidor: [source,console] ---- @@ -372,7 +372,7 @@ $ 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 commits no branch `featureB`: [source,console] ---- @@ -386,14 +386,14 @@ $ git commit -am 'Add ls-files' 1 files changed, 5 insertions(+), 0 deletions(-) ---- -Jessica's repository now looks like this: +O repositório de Jessica agora está assim: -.Jessica's initial commit history -image::images/managed-team-1.png[Jessica's initial commit history] +.Histórico inicial de commits de Jessica +image::images/managed-team-1.png[Histórico inicial de commits de Jessica] -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 está pronta para fazer o push do seu trabalho, mas recebe um e-mail de Josie dizendo que um branch com algum trabalho inicial de "`featureB`" já sofreu push no servidor como o branch `featureBee`. +Jessica precisa mesclar essas alterações com as suas próprias antes que ela possa fazer o push do seu trabalho para o servidor. +Primeiro, Jessica faz o fetch das alterações 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`: +Supondo que Jessica ainda esteja no seu branch `featureB` verificado (checked-out), ela agora pode mesclar o trabalho de Josie nesse 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 fazer o push de todo esse trabalho "`featureB`" mesclado de volta para o servidor, mas ela não quer simplesmente fazer o push do seu próprio branch `featureB`. +Em vez disso, como Josie já iniciou um branch upstream `featureBee`, Jessica quer fazer o push para _esse_ branch, o que ela faz com: [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. +Isso é chamado de _refspec_ (especificação de referência). +Consulte <> para uma discussão mais detalhada sobre refspecs do Git e coisas diferentes que você pode fazer com eles. +Observe também a flag `-u`; esta é uma abreviação para `--set-upstream`, que configura os branches para facilitar pushes e pulls (puxar) posteriormente. -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 e-mail de John, que lhe diz que ele fez o push de algumas alterações para o branch `featureA` no qual eles estão colaborando, e ele pede que Jessica dê uma olhada nelas. +Novamente, Jessica executa um simples `git fetch` para buscar _todo_ o conteúdo novo do servidor, incluindo (claro) o trabalho mais recente 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` recém-buscado (fetched) com a sua cópia local do mesmo branch: [source,console] ---- @@ -452,7 +452,7 @@ Date: Fri May 29 19:57:33 2009 -0700 Increase log output to 30 from 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 mesclar o novo trabalho de John no seu branch `featureA` local com: [source,console] ---- @@ -465,7 +465,7 @@ 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: +Por fim, Jessica pode querer fazer algumas pequenas alterações em todo esse conteúdo mesclado, então ela é livre para fazer essas alterações, fazer o commit delas no seu branch `featureA` local e fazer o push do resultado final de volta para o servidor: [source,console] ---- @@ -478,36 +478,36 @@ To jessica@githost:simplegit.git 3300904..774b3ed featureA -> featureA ---- -Jessica's commit history now looks something like this: +O histórico de commits de Jessica agora está mais ou menos assim: -.Jessica's history after committing on a feature branch -image::images/managed-team-2.png[Jessica's history after committing on a feature branch] +.Histórico de Jessica após fazer um commit num branch de recurso +image::images/managed-team-2.png[Histórico de Jessica após fazer um commit num branch de recurso] -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 momento, Jessica, Josie e John informam aos integradores que os branches `featureA` e `featureBee` no servidor estão prontos para integração na linha principal (mainline). +Depois que os integradores mesclam esses branches na linha principal, um fetch trará o novo commit de mesclagem (merge commit), deixando o histórico assim: -.Jessica's history after merging both her topic branches -image::images/managed-team-3.png[Jessica's history after merging both her topic branches] +.Histórico de Jessica após mesclar os seus dois branches de tópico +image::images/managed-team-3.png[Histórico de Jessica após mesclar os seus dois branches de tópico] -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 mudam para o Git devido a essa capacidade de ter várias equipes trabalhando em paralelo, mesclando as diferentes linhas de trabalho no final do processo. +A capacidade de subgrupos menores de uma equipe de colaborarem via branches remotos, sem necessariamente ter que envolver ou impedir a equipe inteira, é um benefício enorme do Git. +A sequência para o fluxo de trabalho que você viu aqui é algo assim: -.Basic sequence of this managed-team workflow -image::images/managed-team-flow.png[Basic sequence of this managed-team workflow] +.Sequência básica deste fluxo de trabalho de equipe gerenciada +image::images/managed-team-flow.png[Sequência básica deste fluxo de trabalho de equipe gerenciada] [[_public_project]] -==== Forked Public Project +==== Projeto Público Bifurcado (Forked) (((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. +Contribuir para projetos públicos é um pouco diferente. +Como você não tem as permissões para atualizar diretamente os branches no projeto, tem que levar o trabalho aos mantenedores de alguma outra forma. +Este primeiro exemplo descreve a contribuição por meio de bifurcação (forking) em hosts Git que suportam forking facilmente. +Muitos sites de hospedagem suportam isso (incluindo GitHub, BitBucket, repo.or.cz e outros), e muitos mantenedores de projetos esperam esse estilo de contribuição. +A próxima seção trata de projetos que preferem aceitar patches contribuídos por e-mail. -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 vai querer clonar o repositório principal, criar um branch de tópico para o patch ou série de patches com os quais planeja contribuir, e fazer o seu trabalho nele. +A sequência se parece basicamente com isto: [source,console] ---- @@ -522,23 +522,23 @@ $ 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 esmagar (squash) o seu trabalho em um único commit ou reorganizar o trabalho nos commits para tornar o patch mais fácil para o mantenedor revisar -- veja <> para obter mais informações sobre rebasing 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 o trabalho do seu branch terminar e você estiver pronto para contribuir de volta aos mantenedores, vá para a página original do projeto e clique no botão "`Fork`", criando o seu próprio fork gravável do projeto. +Você então precisará adicionar a URL deste repositório como um novo remoto do seu repositório local; neste exemplo, vamos chamá-lo de `myfork`: [source,console] ---- $ git remote add myfork ---- -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 precisará fazer o push do seu novo trabalho para este repositório. +É mais fácil fazer o push do branch de tópico em que você está trabalhando para o seu repositório originado de um fork, em vez de mesclar esse trabalho no seu branch `master` e fazer o push disso. +O motivo é que, se o seu trabalho não for aceito ou for escolhido a dedo (cherry-picked), você não precisa voltar atrás no seu branch `master` (a operação `cherry-pick` do Git é abordada com mais detalhes em <>). +Se os mantenedores usarem `merge`, `rebase` ou `cherry-pick` no seu trabalho, você eventualmente o receberá de volta puxando (pulling) do repositório deles de qualquer maneira. -In any event, you can push your work with: +Em qualquer caso, você pode fazer o push do seu trabalho com: [source,console] ---- @@ -546,11 +546,11 @@ $ git push -u myfork 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. +Depois que o seu trabalho for enviado para o fork do repositório, você precisará notificar os mantenedores do projeto original que tem um trabalho que gostaria que eles mesclassem. +Isso costuma ser chamado de _pull request_ (solicitação de pull), e você normalmente gera essa solicitação por meio do site -- o GitHub tem o seu próprio mecanismo "`Pull Request`" que abordaremos em <> -- ou você pode executar o comando `git request-pull` e enviar a saída resultante por e-mail 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` recebe o branch base no qual você deseja que o seu branch de tópico seja puxado (pulled) e a URL do repositório Git de onde você quer que eles o puxem, e produz um resumo de todas as alterações que você está solicitando. +Por exemplo, se Jessica quiser enviar um pull request a John e tiver feito dois commits no branch de tópico que ela acabou de dar push, ela pode executar isto: [source,console] ---- @@ -571,11 +571,11 @@ Jessica Smith (2): 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. +Esta saída pode ser enviada para o mantenedor -- ela informa a ele de onde o trabalho foi ramificado (branched), resume os commits e identifica de onde o novo trabalho deve ser puxado. -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 do qual você não é o mantenedor, geralmente é mais fácil ter um branch como `master` que rastreie o `origin/master` e fazer o seu trabalho em branches de tópicos que podem ser facilmente descartados caso sejam rejeitados. +Ter os temas de trabalho isolados em branches de tópicos também facilita o rebase do seu trabalho se a ponta (tip) do repositório principal se moveu nesse meio tempo e seus commits não se aplicam mais de forma limpa. +Por exemplo, se você quiser submeter um segundo tópico de trabalho para o projeto, não continue trabalhando no branch de tópico que você acabou de dar o push -- comece do zero a partir do branch `master` do repositório principal: [source,console] ---- @@ -588,13 +588,13 @@ $ git request-pull origin/master myfork $ 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 de seus tópicos está contido em um silo -- semelhante a uma fila de patches -- que você pode reescrever, fazer o rebase e modificar sem que os tópicos interfiram ou dependam uns dos outros, assim: -.Initial commit history with `featureB` work -image::images/public-small-1.png[Initial commit history with `featureB` work] +.Histórico inicial de commits com o trabalho `featureB` +image::images/public-small-1.png[Histórico inicial de commits com o trabalho featureB] -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 puxou vários outros patches e tentou o seu primeiro branch, mas ele não se mescla mais de forma limpa. +Neste caso, você pode tentar fazer o rebase desse branch no topo do `origin/master`, resolver os conflitos para o mantenedor, e então reenviar as suas alterações: [source,console] ---- @@ -603,18 +603,18 @@ $ git rebase origin/master $ git push -f myfork featureA ---- -This rewrites your history to now look like <>. +Isso reescreve o seu histórico para agora se parecer com <>. [[psp_b]] -.Commit history after `featureA` work -image::images/public-small-2.png[Commit history after `featureA` work] +.Histórico de commits após o trabalho `featureA` +image::images/public-small-2.png[Histórico de commits após o trabalho featureA] -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ê fez o rebase do branch, você tem que especificar o `-f` para o seu comando de push a fim de conseguir substituir o branch `featureA` no servidor por um commit que não é descendente dele. +Uma alternativa seria fazer o push deste novo trabalho para 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 analisar mais um cenário possível: o mantenedor olhou o trabalho no seu segundo branch e gostou do conceito, mas gostaria que você mudasse um detalhe de implementação. +Você também aproveitará essa oportunidade para mover o trabalho e baseá-lo no branch `master` atual do projeto. +Você inicia um novo branch baseado no branch `origin/master` atual, usa o squash nas alterações de `featureB` ali, resolve os conflitos, faz a alteração de implementação e, em seguida, faz o push disso como um novo branch: (((git commands, merge, squash))) [source,console] @@ -626,25 +626,25 @@ $ git commit $ git push myfork 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 do branch mesclado e usa squash num único changeset, produzindo o estado do repositório como se uma mesclagem (merge) real tivesse acontecido, sem na verdade criar um merge commit. +Isso significa que o seu commit futuro terá apenas um pai e permite que você introduza todas as alterações de outro branch e então faça mais alterações antes de registrar o novo commit. +Além disso, a opção `--no-commit` pode ser útil para atrasar o merge commit no caso do processo de merge 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 o mantenedor que você fez as alterações solicitadas, e que eles podem encontrar essas alterações no seu branch `featureBv2`. -.Commit history after `featureBv2` work -image::images/public-small-3.png[Commit history after `featureBv2` work] +.Histórico de commits após o trabalho `featureBv2` +image::images/public-small-3.png[Histórico de commits após o trabalho featureBv2] [[_project_over_email]] -==== Public Project over Email +==== Projeto Público Grande (((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 maiores estabeleceram procedimentos para aceitar patches -- você precisará verificar as regras específicas de cada projeto, porque elas serão diferentes. +Como há vários projetos mais antigos e maiores que aceitam patches via uma lista de discussão de desenvolvedores, examinaremos um exemplo disso 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 é semelhante ao caso de uso anterior -- você cria branches de tópicos para cada série de patches em que trabalha. +A diferença está em como você as submete ao projeto. +Em vez de fazer o fork do projeto e fazer o push para a sua própria versão gravável, você gera versões de e-mail de cada série de commits e as envia por e-mail para a lista de discussão de desenvolvedores: [source,console] ---- @@ -656,9 +656,9 @@ $ 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 commits que deseja enviar para a lista de discussão. +Você usa `git format-patch` para gerar os arquivos no formato mbox que você pode enviar por e-mail para a lista -- ele transforma cada commit em uma mensagem de e-mail com a primeira linha da mensagem de commit como o assunto e o resto da mensagem mais o patch que o commit introduz como o corpo. +O lado bom disso é que aplicar um patch a partir de um e-mail gerado com `format-patch` preserva adequadamente todas as informações do commit. [source,console] ---- @@ -667,9 +667,9 @@ $ git format-patch -M origin/master 0002-increase-log-output-to-30-from-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` imprime os nomes dos arquivos de patch que ele cria. +A opção `-M` diz ao Git para procurar por renomeações. +Os arquivos acabam ficando assim: [source,console] ---- @@ -702,17 +702,17 @@ 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 esses arquivos de patch para adicionar mais informações para a lista de e-mail que você não quer que apareçam na mensagem de commit. +Se você adicionar texto entre a linha `---` e o início do patch (a linha `diff --git`), os desenvolvedores poderão lê-lo, mas esse conteúdo é ignorado pelo processo de aplicação 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 isso por e-mail a uma lista de discussão, você pode colar o arquivo no seu programa de e-mail ou enviá-lo através de um programa de linha de comando. +Colar o texto muitas vezes causa problemas de formatação, especialmente com clientes "`mais inteligentes`" que não preservam as quebras de linha e outros espaços em branco adequadamente. +Felizmente, o Git fornece uma ferramenta para ajudá-lo a enviar patches devidamente formatados via IMAP, o que pode ser mais fácil para você. +Nós demonstraremos como enviar um patch via Gmail, que por acaso é o agente de e-mail que conhecemos melhor; você pode ler instruções detalhadas para diversos programas de e-mail no final do já 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ê precisa configurar a seção imap no seu arquivo `~/.gitconfig`. +Você pode definir cada valor separadamente com uma série de comandos `git config`, ou você pode adicioná-los manualmente, mas no final seu arquivo de configuração deve se parecer com isso: [source,ini] ---- @@ -725,8 +725,8 @@ You can set each value separately with a series of `git config` commands, or you 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 usar SSL, as duas últimas linhas provavelmente não são necessárias, e o valor do host será `imap://` em vez de `imaps://`. +Quando isso estiver configurado, você pode usar `git imap-send` para colocar a série de patches na pasta Drafts (Rascunhos) do servidor IMAP especificado: [source,console] ---- @@ -738,10 +738,10 @@ 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 ser capaz de ir até a sua pasta de Rascunhos, alterar o campo Para (To) para a lista de discussão para a qual você está enviando o patch, possivelmente colocar em cópia (CC) o mantenedor ou a pessoa responsável por aquela seção, e enviá-lo. -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 por meio de um servidor SMTP. +Como antes, você pode definir cada valor separadamente com uma série de comandos `git config`, ou pode adicioná-los manualmente na seção sendemail do seu arquivo `~/.gitconfig`: [source,ini] ---- @@ -752,7 +752,7 @@ As before, you can set each value separately with a series of `git config` comma smtpserverport = 587 ---- -After this is done, you can use `git send-email` to send your patches: +Depois que isso for feito, você pode usar `git send-email` para enviar os seus patches: [source,console] ---- @@ -765,7 +765,7 @@ 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 cospe um monte de informações de log parecidas com isto para cada patch que você está enviando: [source,text] ---- @@ -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 https://git-send-email.io[git-send-email.io^]. +Para obter ajuda sobre a configuração do seu sistema e e-mail, mais dicas e truques e um sandbox para enviar um patch de teste por e-mail, acesse https://git-send-email.io[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, abordamos vários fluxos de trabalho e falamos sobre as diferenças entre trabalhar como parte de uma pequena equipe em projetos de código fechado em vez de contribuir para um grande projeto público. +Você sabe verificar erros de espaço em branco antes de fazer um commit e sabe escrever uma ótima mensagem de commit. +Você aprendeu como formatar patches e enviá-los por e-mail a uma lista de discussão de desenvolvedores. +Lidar com mesclagens também foi abordado no contexto dos diferentes fluxos de trabalho. +Agora você está bem preparado para colaborar em 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 do outro lado da moeda: mantendo um projeto Git. +Você aprenderá como ser um ditador benevolente ou gerente de integração. diff --git a/book/05-distributed-git/sections/distributed-workflows.asc b/book/05-distributed-git/sections/distributed-workflows.asc index b61289dc..5eb9bc42 100644 --- a/book/05-distributed-git/sections/distributed-workflows.asc +++ b/book/05-distributed-git/sections/distributed-workflows.asc @@ -1,102 +1,102 @@ -=== Distributed Workflows +=== Fluxos de Trabalho Distribuídos (((workflows))) -In contrast with Centralized Version Control Systems (CVCSs), the distributed nature of Git allows you to be far more flexible in how developers collaborate on projects. -In centralized systems, every developer is a node working more or less equally with a central hub. -In Git, however, every developer is potentially both a node and a hub; that is, every developer can both contribute code to other repositories and maintain a public repository on which others can base their work and which they can contribute to. -This presents a vast range of workflow possibilities for your project and/or your team, so we'll cover a few common paradigms that take advantage of this flexibility. -We'll go over the strengths and possible weaknesses of each design; you can choose a single one to use, or you can mix and match features from each. +Em contraste com os Sistemas de Controle de Versão Centralizados (CVCSs), a natureza distribuída do Git permite que você seja muito mais flexível na forma como os desenvolvedores colaboram em projetos. +Em sistemas centralizados, cada desenvolvedor é um nó trabalhando de forma mais ou menos igual com um hub central. +No Git, no entanto, todo desenvolvedor é potencialmente tanto um nó quanto um hub; ou seja, todo desenvolvedor pode contribuir com código para outros repositórios e manter um repositório público no qual outros podem basear o seu trabalho e para o qual podem contribuir. +Isso apresenta uma vasta gama de possibilidades de fluxo de trabalho para o seu projeto e/ou equipe, então abordaremos alguns paradigmas comuns que aproveitam essa flexibilidade. +Analisaremos os pontos fortes e as possíveis fraquezas de cada design; você pode escolher apenas um para usar, ou pode misturar e combinar (mix and match) recursos de cada um. -==== Centralized Workflow +==== Fluxo de Trabalho Centralizado (((workflows, centralized))) -In centralized systems, there is generally a single collaboration model -- the centralized workflow. -One central hub, or _repository_, can accept code, and everyone synchronizes their work with it. -A number of developers are nodes -- consumers of that hub -- and synchronize with that centralized location. +Em sistemas centralizados, geralmente há um único modelo de colaboração -- o fluxo de trabalho centralizado. +Um hub central, ou _repositório_, pode aceitar código, e todos sincronizam o seu trabalho com ele. +Um número de desenvolvedores são nós -- consumidores daquele hub -- e sincronizam com esse local centralizado. -.Centralized workflow -image::images/centralized_workflow.png[Centralized workflow] +.Fluxo de trabalho centralizado +image::images/centralized_workflow.png[Fluxo de trabalho centralizado] -This means that if two developers clone from the hub and both make changes, the first developer to push their changes back up can do so with no problems. -The second developer must merge in the first one's work before pushing changes up, so as not to overwrite the first developer's changes. -This concept is as true in Git as it is in Subversion(((Subversion))) (or any CVCS), and this model works perfectly well in Git. +Isso significa que, se dois desenvolvedores clonarem do hub e ambos fizerem alterações, o primeiro desenvolvedor a fazer o push das suas alterações de volta pode fazê-lo sem problemas. +O segundo desenvolvedor deve fazer o merge do trabalho do primeiro antes de fazer o push das alterações, para não substituir as alterações do primeiro desenvolvedor. +Esse conceito é tão verdadeiro no Git quanto no Subversion(((Subversion))) (ou em qualquer CVCS), e esse modelo funciona perfeitamente bem no Git. -If you are already comfortable with a centralized workflow in your company or team, you can easily continue using that workflow with Git. -Simply set up a single repository, and give everyone on your team push access; Git won't let users overwrite each other. +Se você já estiver confortável com um fluxo de trabalho centralizado na sua empresa ou equipe, poderá continuar usando esse fluxo de trabalho com o Git facilmente. +Basta configurar um único repositório e dar acesso de push a todos na sua equipe; o Git não permitirá que os usuários sobrescrevam os trabalhos uns dos outros. -Say John and Jessica both start working at the same time. -John finishes his change and pushes it to the server. -Then Jessica tries to push her changes, but the server rejects them. -She is told that she's trying to push non-fast-forward changes and that she won't be able to do so until she fetches and merges. -This workflow is attractive to a lot of people because it's a paradigm that many are familiar and comfortable with. +Digamos que John e Jessica comecem a trabalhar ao mesmo tempo. +John termina a sua alteração e faz o push para o servidor. +Então, Jessica tenta fazer o push de suas alterações, mas o servidor as rejeita. +Ela é informada de que está tentando fazer um push de alterações non-fast-forward e que não conseguirá fazê-lo até fazer o fetch e o merge. +Este fluxo de trabalho é atraente para muitas pessoas porque é um paradigma com o qual muitos estão familiarizados e confortáveis. -This is also not limited to small teams. -With Git's branching model, it's possible for hundreds of developers to successfully work on a single project through dozens of branches simultaneously. +Isso também não se limita a equipes pequenas. +Com o modelo de ramificação (branching model) do Git, é possível que centenas de desenvolvedores trabalhem com sucesso em um único projeto através de dezenas de branches simultaneamente. [[_integration_manager]] -==== Integration-Manager Workflow +==== Fluxo de Trabalho do Gerente de Integração (Integration-Manager) (((workflows, integration manager))) -Because Git allows you to have multiple remote repositories, it's possible to have a workflow where each developer has write access to their own public repository and read access to everyone else's. -This scenario often includes a canonical repository that represents the "`official`" project. -To contribute to that project, you create your own public clone of the project and push your changes to it. -Then, you can send a request to the maintainer of the main project to pull in your changes. -The maintainer can then add your repository as a remote, test your changes locally, merge them into their branch, and push back to their repository. -The process works as follows (see <>): - -1. The project maintainer pushes to their public repository. -2. A contributor clones that repository and makes changes. -3. The contributor pushes to their own public copy. -4. The contributor sends the maintainer an email asking them to pull changes. -5. The maintainer adds the contributor's repository as a remote and merges locally. -6. The maintainer pushes merged changes to the main repository. +Como o Git permite que você tenha vários repositórios remotos, é possível ter um fluxo de trabalho em que cada desenvolvedor tem acesso de gravação ao seu próprio repositório público e acesso de leitura aos de todos os outros. +Esse cenário geralmente inclui um repositório canônico que representa o projeto "`oficial`". +Para contribuir com esse projeto, você cria o seu próprio clone público do projeto e faz o push das suas alterações para ele. +Então, você pode enviar uma solicitação ao mantenedor do projeto principal para fazer o pull das suas alterações. +O mantenedor pode então adicionar o seu repositório como remoto, testar as suas alterações localmente, mesclá-las no branch dele e fazer o push de volta para o repositório dele. +O processo funciona da seguinte forma (veja <>): + +1. O mantenedor do projeto faz o push para o seu repositório público. +2. Um contribuidor clona esse repositório e faz alterações. +3. O contribuidor faz o push para a sua própria cópia pública. +4. O contribuidor envia um e-mail ao mantenedor pedindo que ele faça o pull das alterações. +5. O mantenedor adiciona o repositório do contribuidor como um remoto e faz o merge localmente. +6. O mantenedor faz o push das alterações mescladas (merged changes) para o repositório principal. [[wfdiag_b]] -.Integration-manager workflow -image::images/integration-manager.png[Integration-manager workflow] +.Fluxo de trabalho do Gerente de Integração (Integration-manager) +image::images/integration-manager.png[Fluxo de trabalho do Gerente de Integração] (((forking))) -This is a very common workflow with hub-based tools like GitHub or GitLab, where it's easy to fork a project and push your changes into your fork for everyone to see. -One of the main advantages of this approach is that you can continue to work, and the maintainer of the main repository can pull in your changes at any time. -Contributors don't have to wait for the project to incorporate their changes -- each party can work at their own pace. +Este é um fluxo de trabalho muito comum com ferramentas baseadas em hub como o GitHub ou GitLab, onde é fácil fazer um fork de um projeto e fazer o push das suas alterações para o seu fork para que todos vejam. +Uma das principais vantagens dessa abordagem é que você pode continuar a trabalhar, e o mantenedor do repositório principal pode fazer o pull das suas alterações a qualquer momento. +Os contribuidores não precisam esperar que o projeto incorpore as suas alterações -- cada parte pode trabalhar no seu próprio ritmo. -==== Dictator and Lieutenants Workflow +==== Fluxo de Trabalho Ditador e Tenentes (Dictator and Lieutenants) (((workflows, dictator and lieutenants))) -This is a variant of a multiple-repository workflow. -It's generally used by huge projects with hundreds of collaborators; one famous example is the Linux kernel. -Various integration managers are in charge of certain parts of the repository; they're called _lieutenants_. -All the lieutenants have one integration manager known as the benevolent dictator. -The benevolent dictator pushes from their directory to a reference repository from which all the collaborators need to pull. -The process works like this (see <>): - -1. Regular developers work on their topic branch and rebase their work on top of `master`. - The `master` branch is that of the reference repository to which the dictator pushes. -2. Lieutenants merge the developers' topic branches into their `master` branch. -3. The dictator merges the lieutenants' `master` branches into the dictator's `master` branch. -4. Finally, the dictator pushes that `master` branch to the reference repository so the other developers can rebase on it. +Esta é uma variante de um fluxo de trabalho de múltiplos repositórios. +Geralmente é usado por projetos enormes com centenas de colaboradores; um exemplo famoso é o kernel do Linux. +Vários gerentes de integração são responsáveis por certas partes do repositório; eles são chamados de _tenentes_ (lieutenants). +Todos os tenentes têm um gerente de integração conhecido como o ditador benevolente (benevolent dictator). +O ditador benevolente faz o push do seu diretório para um repositório de referência do qual todos os colaboradores precisam fazer o pull. +O processo funciona assim (veja <>): + +1. Desenvolvedores regulares trabalham em seu branch de tópico e fazem o rebase do seu trabalho no topo da `master`. + O branch `master` é aquele do repositório de referência para o qual o ditador faz o push. +2. Os tenentes mesclam (merge) os branches de tópico dos desenvolvedores em seu branch `master`. +3. O ditador mescla os branches `master` dos tenentes no branch `master` do ditador. +4. Finalmente, o ditador faz o push desse branch `master` para o repositório de referência para que os outros desenvolvedores possam fazer o rebase nele. [[wfdiag_c]] -.Benevolent dictator workflow -image::images/benevolent-dictator.png[Benevolent dictator workflow] +.Fluxo de trabalho do ditador benevolente (Benevolent dictator) +image::images/benevolent-dictator.png[Fluxo de trabalho do ditador benevolente] -This kind of workflow isn't common, but can be useful in very big projects, or in highly hierarchical environments. -It allows the project leader (the dictator) to delegate much of the work and collect large subsets of code at multiple points before integrating them. +Esse tipo de fluxo de trabalho não é comum, mas pode ser útil em projetos muito grandes ou em ambientes altamente hierárquicos. +Ele permite que o líder do projeto (o ditador) delegue grande parte do trabalho e colete grandes subconjuntos de código em vários pontos antes de integrá-los. [[_patterns_for_managing_source_code_branches]] -==== Patterns for Managing Source Code Branches +==== Padrões para Gerenciar Branches de Código-Fonte [NOTE] ==== -Martin Fowler has made a guide "Patterns for Managing Source Code Branches". -This guide covers all the common Git workflows, and explains how/when to use them. -There's also a section comparing high and low integration frequencies. +Martin Fowler criou um guia "Patterns for Managing Source Code Branches" (Padrões para Gerenciar Branches de Código-Fonte). +Este guia abrange todos os fluxos de trabalho comuns do Git e explica como/quando usá-los. +Há também uma seção comparando frequências de integração altas e baixas. https://martinfowler.com/articles/branching-patterns.html[^] ==== -==== Workflows Summary +==== Resumo dos Fluxos de Trabalho -These are some commonly used workflows that are possible with a distributed system like Git, but you can see that many variations are possible to suit your particular real-world workflow. -Now that you can (hopefully) determine which workflow combination may work for you, we'll cover some more specific examples of how to accomplish the main roles that make up the different flows. -In the next section, you'll learn about a few common patterns for contributing to a project. +Estes são alguns fluxos de trabalho comumente usados que são possíveis com um sistema distribuído como o Git, mas você pode ver que muitas variações são possíveis para se adequar ao seu fluxo de trabalho particular do mundo real. +Agora que você pode (esperamos) determinar qual combinação de fluxo de trabalho pode funcionar para você, abordaremos alguns exemplos mais específicos de como cumprir os papéis principais que compõem os diferentes fluxos. +Na próxima seção, você aprenderá sobre alguns padrões comuns para contribuir com um projeto. diff --git a/book/05-distributed-git/sections/maintaining.asc b/book/05-distributed-git/sections/maintaining.asc index c377bb68..bce9afc5 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. +Além de saber como contribuir efetivamente para um projeto, você provavelmente precisará 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 alterações em branches remotos de repositórios que você adicionou como remotos ao seu projeto. +Quer você mantenha um repositório canônico ou queira ajudar verificando ou aprovando patches, você precisa saber como aceitar o trabalho de uma forma que seja mais clara para outros contribuidores e sustentável para você a longo prazo. -==== Working in Topic Branches +==== Trabalhando em Branches de Tópicos (((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: +Quando você estiver pensando em integrar um novo trabalho, geralmente é uma boa ideia testá-lo em um _branch de tópico_ (topic branch) -- um branch temporário feito especificamente para testar esse novo trabalho. +Dessa forma, é fácil ajustar um patch individualmente e deixá-lo se não estiver funcionando até que você tenha tempo de voltar a ele. +Se você criar um nome de branch simples com base no tema do trabalho que vai testar, como `ruby_client` ou algo similarmente descritivo, poderá se lembrar dele facilmente caso precise abandoná-lo por um tempo e voltar mais tarde. +O mantenedor do projeto Git também tende a colocar esses branches em namespaces -- como `sc/ruby_client`, onde `sc` é a abreviação da pessoa que contribuiu com o trabalho. +Como você deve se lembrar, você pode criar o branch com base no seu 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 mudar para ele 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 você recebeu a este branch de tópico e determinar se deseja mesclá-lo (merge) em seus branches de longo prazo. [[_patches_from_email]] -==== Applying Patches from Email +==== Aplicando Patches a partir de E-mail (((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`. +Se você receber um patch por e-mail que precisa integrar ao seu projeto, você precisa aplicar o patch no seu 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`. -===== Applying a Patch with `apply` +===== Aplicando um Patch com `apply` (((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: +Se você recebeu o patch de alguém que o gerou com `git diff` ou alguma variação do comando `diff` do Unix (o que não é recomendado; veja a próxima seção), você pode aplicá-lo com o comando `git apply`. +Supondo que você tenha salvo 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 executar um comando `patch -p1` para aplicar o patch, embora seja mais paranoico e aceite menos correspondências difusas (fuzzy matches) do que o patch. +Ele também lida com adições, exclusões e renomeações de arquivos se estiverem descritos no formato `git diff`, o que o `patch` não faz. +Finalmente, o `git apply` é um modelo de "`aplique tudo ou aborte tudo`" (apply all or abort all) onde tudo é aplicado ou nada é, enquanto o `patch` pode aplicar os arquivos de patch parcialmente, deixando o seu diretório de trabalho num estado estranho. +O `git apply` é, no geral, muito mais conservador do que o `patch`. +Ele não criará um commit para você -- após executá-lo, você deve preparar (stage) e fazer o commit das alterações introduzidas 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 `git apply` para ver se um patch se aplica de forma limpa antes de tentar aplicá-lo de fato -- você pode rodar `git apply --check` com o patch: [source,console] ---- @@ -62,20 +62,20 @@ 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, então o patch deve se aplicar de forma limpa. +Esse comando também sai com um status diferente de zero se a verificação falhar, então você pode usá-lo em scripts se quiser. [[_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. +Se o contribuidor for um usuário do Git e foi bom o suficiente para usar o comando `format-patch` para gerar o patch dele, então o seu trabalho é mais fácil porque o patch contém as informações do autor e uma mensagem de commit para você. +Se você puder, encoraje os seus contribuidores a usar o `format-patch` em vez do `diff` para gerar patches para você. +Você só deveria ter que usar o `git apply` para patches legados e coisas desse 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 é chamado de `am` porque é usado para "aplicar uma série de patches de uma caixa de correio"). +Tecnicamente, o `git am` foi construído para ler um arquivo mbox, que é um formato simples de texto puro (plain-text) para armazenar uma ou mais mensagens de e-mail em um único arquivo de texto. +Fica parecido com isso: [source,console] ---- @@ -87,11 +87,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; ele também representa um formato de e-mail mbox válido. +Se alguém lhe enviou o patch de forma adequada por e-mail usando `git send-email`, e você fez o download dele no formato mbox, você pode apontar o `git am` para esse arquivo mbox, e ele começará a aplicar todos os patches que encontrar. +Se você executa um cliente de e-mail que pode salvar vários e-mails no formato mbox, pode salvar uma série inteira de patches num arquivo e então usar o `git am` para aplicá-los um de cada vez. -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 fez upload de um arquivo de patch gerado via `git format-patch` em um sistema de tickets ou algo semelhante, você pode salvar o arquivo localmente e depois passar esse arquivo salvo no seu disco para o `git am` aplicá-lo: [source,console] ---- @@ -99,9 +99,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ê pode ver que ele foi aplicado de forma limpa e automaticamente criou 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 esse patch foi aplicado a partir do exemplo de mbox acima, o commit gerado se pareceria com isso: [source,console] ---- @@ -117,12 +117,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 `Commit` indica a pessoa que aplicou o patch e a hora em que foi aplicado. +A informação `Author` (Autor) é o indivíduo que originalmente criou o patch e quando ele foi originalmente 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 de forma limpa. +Talvez o seu branch principal tenha divergido muito do branch a partir do qual o patch foi construído, ou o patch depende 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,8 +136,8 @@ 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 quaisquer arquivos com os quais tenha problemas, muito parecido com uma operação de merge ou rebase em conflito. +Você resolve esse problema da mesma maneira -- edite o arquivo para resolver o conflito, prepare (stage) o novo arquivo, e então execute `git am --resolved` para continuar com o próximo patch: [source,console] ---- @@ -147,9 +147,9 @@ $ 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 um pouco mais inteligente, você pode passar uma opção `-3` para ele, o que faz com que o Git tente um merge de três vias (three-way merge). +Essa opção não está ativada por padrão porque ela não funciona se o commit no qual o patch diz que foi baseado não estiver no seu repositório. +Se você tiver esse commit -- se o patch for baseado em um commit público -- então a opção `-3` é geralmente muito mais inteligente para aplicar um patch conflitante: [source,console] ---- @@ -162,10 +162,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 teria sido considerado como um conflito. +Como a opção `-3` foi usada, o patch foi aplicado de forma limpa. -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 a partir de um mbox, você também pode executar o comando `am` no modo interativo, que para em cada patch que encontra e pergunta se você deseja aplicá-lo: [source,console] ---- @@ -177,17 +177,17 @@ 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 é bom se você tiver vários patches salvos, porque você pode visualizar o patch primeiro se não se lembrar do que se trata, ou não aplicar o patch 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 tiverem sido confirmados (committed) no seu branch, você pode escolher se e como integrá-los em um branch de longa duração. [[_checking_out_remotes]] -==== Checking Out Remote Branches +==== Fazendo Checkout de Branches Remotos (((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. +Se a sua contribuição veio de um usuário do Git que configurou seu próprio repositório, fez o push de várias alterações para ele e depois lhe enviou a URL do repositório e o nome do branch remoto onde as alterações estão, você pode adicioná-lo como remoto e fazer os 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 Jessica lhe enviar um e-mail dizendo que ela tem um ótimo novo recurso no branch `ruby-client` de seu repositório, você pode testá-lo adicionando o remoto e fazendo checkout desse branch localmente: [source,console] ---- @@ -196,18 +196,18 @@ $ git fetch jessica $ git checkout -b rubyclient jessica/ruby-client ---- -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. +Se ela lhe enviar um e-mail novamente mais tarde com outro branch contendo outro ótimo recurso, você poderia fazer um `fetch` e `checkout` diretamente porque já tem a configuração do remoto. -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 com uma pessoa de forma consistente. +Se alguém tiver apenas um único patch para contribuir de vez em quando, então aceitá-lo por e-mail pode consumir menos tempo do que exigir que todos executem seus próprios servidores e ter que adicionar e remover remotos continuamente para obter alguns patches. +Também é improvável que você queira ter centenas de remotos, cada um para alguém que contribui com apenas um ou dois patches. +No entanto, scripts e serviços hospedados podem facilitar isso -- depende muito de como você desenvolve e como os seus contribuidores 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 de merge legítimos, você sabe em que ponto da sua história o trabalho deles se baseia; 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 estiver trabalhando com uma pessoa consistentemente, mas ainda assim quiser fazer um pull dela dessa maneira, pode fornecer a URL do repositório remoto ao comando `git pull`. +Isso faz um pull único e não salva a URL como uma referência de remoto: [source,console] ---- @@ -218,17 +218,17 @@ Merge made by the 'recursive' strategy. ---- [[_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 pode usá-los para revisar exatamente o que você introduzirá se fizer o merge disto 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: +Muitas vezes é útil obter uma revisão de 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 o seu contribuidor lhe enviar dois patches e você criar um branch chamado `contrib` e aplicou esses patches lá, você pode executar isto: [source,console] ---- @@ -246,27 +246,27 @@ Date: Mon Oct 22 19:38:36 2008 -0700 Update gemspec to hopefully work better ---- -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 introduz, lembre-se de que você pode passar a opção `-p` para o `git log` e ele anexará o diff introduzido a 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ê fosse mesclar esse branch de tópico com outro branch, você pode ter que usar um truque estranho para obter os resultados corretos. +Você pode pensar em executar 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. +Este comando fornece 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, então você obterá resultados aparentemente estranhos. +Isso acontece porque o Git compara diretamente os snapshots do último commit do branch de tópico em que você está e o snapshot do último commit no branch `master`. +Por exemplo, se você adicionou uma linha num arquivo no branch `master`, uma comparação direta dos snapshots fará 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 as duas histórias tiverem divergido, o diff fará parecer que você está adicionando todas as coisas novas no seu branch de tópico e removendo tudo o que é exclusivo do 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ê introduzirá se mesclar esse branch com o `master`. +Você faz isso fazendo com que o Git compare o último commit no 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 seu diff sobre ele: [source,console] ---- @@ -275,116 +275,116 @@ $ git merge-base contrib master $ git diff 36c7db ---- -or, more concisely: +ou, de forma 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 é particularmente conveniente, então o Git fornece outra abreviação (shorthand) para fazer a mesma coisa: a sintaxe de três pontos (triple-dot syntax). +No contexto do comando `git diff`, você pode colocar três pontos após outro branch para fazer um `diff` entre o último commit do branch em que você está e o seu ancestral comum com o 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. +Esse comando mostra apenas o trabalho que o seu atual branch de tópico introduziu desde o seu ancestral comum com o `master`. +Essa é uma sintaxe muito útil para se 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 a um branch de linha principal (mainline branch), a questão é como fazê-lo. +Além disso, qual fluxo de trabalho geral você deseja usar para manter o seu projeto? +Você tem várias opções, então abordaremos 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 mesclar todo esse trabalho diretamente no seu branch `master`. +Neste cenário, você tem um branch `master` que contém código basicamente estável. +Quando você tem trabalho num branch de tópico que você acha que concluiu, ou trabalho com o qual outra pessoa contribuiu e você verificou, você o mescla no seu branch master, exclui o branch de tópico recém-mesclado 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 mesclamos `ruby_client` seguido de `php_client`, o seu histórico acabará ficando parecido com <>. [[merwf_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ópicos +image::images/merging-workflows-1.png[Histórico com vários branches de tópicos] [[merwf_b]] -.After a topic branch merge -image::images/merging-workflows-2.png[After a topic branch merge] +.Após um merge de branch de tópico +image::images/merging-workflows-2.png[Após 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 possivelmente ser problemático se você estiver lidando com projetos maiores ou mais estáveis, onde você quer ser muito 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 de duas fases. +Neste cenário, você tem dois branches de longa duração, `master` e `develop`, em que você determina que o `master` é atualizado apenas quando uma versão (release) muito estável é criada, e todo o novo código é integrado ao branch `develop`. +Você faz regularmente o push de ambos os branches para o repositório público. +Toda vez que você tem um novo branch de tópico para mesclar (<>), você o mescla em `develop` (<>); em seguida, quando você cria uma tag de um lançamento, você faz um fast-forward do `master` para onde quer que o agora estável branch `develop` esteja (<>). [[merwf_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] [[merwf_d]] -.After a topic branch merge -image::images/merging-workflows-4.png[After a topic branch merge] +.Após um merge de branch de tópico +image::images/merging-workflows-4.png[Após um merge de branch de tópico] [[merwf_e]] -.After a project release -image::images/merging-workflows-5.png[After a project release] +.Após um lançamento (release) do projeto +image::images/merging-workflows-5.png[Após um lançamento (release) 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. +Desta forma, quando as pessoas clonarem o repositório do seu projeto, elas podem fazer o checkout do `master` para construir a versão estável mais recente e manter-se atualizadas com facilidade, ou podem fazer o checkout do `develop`, que é o conteúdo mais inovador (cutting-edge). +Você também pode estender esse conceito tendo um branch `integrate` onde todo o trabalho é mesclado. +Então, quando a base de código nesse branch estiver estável e passar nos testes, você o mescla em um branch `develop`; e quando ele provar estar estável por um tempo, você faz um fast-forward no seu branch `master`. -===== Large-Merging Workflows +===== Fluxos de Trabalho de Mesclagem em Grande Escala (((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` (antigamente 'pu' -- proposed updates, ou atualizações propostas) para trabalhos novos, e `maint` para backports de manutenção. +Quando um novo trabalho é introduzido por contribuidores, ele é coletado em branches de tópicos no repositório do mantenedor de uma maneira semelhante à que descrevemos (veja <>). +Neste ponto, os tópicos são avaliados para determinar se eles são seguros e estão prontos para consumo ou se precisam de mais trabalho. +Se forem seguros, eles são mesclados em `next`, e esse branch recebe um push para que todos possam testar os tópicos integrados juntos. [[merwf_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ópicos contribuídos paralelamente +image::images/large-merges-1.png[Gerenciando uma série complexa de branches de tópicos contribuídos paralelamente] -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 mesclados em `seen`. +Quando for determinado que eles estão totalmente estáveis, os tópicos são mesclados novamente em `master`. +Os branches `next` e `seen` são então reconstruídos a partir de `master`. +Isso significa que o `master` quase sempre se move para frente, o `next` sofre rebase ocasionalmente e o `seen` sofre rebase ainda com mais frequência: -.Merging contributed topic branches into long-term integration branches -image::images/large-merges-2.png[Merging contributed topic branches into long-term integration branches] +.Mesclando branches de tópicos contribuídos em branches de integração de longo prazo +image::images/large-merges-2.png[Mesclando branches de tópicos contribuídos 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 é mesclado no `master`, ele é removido do repositório. +O projeto Git também tem um branch `maint` originado a partir do fork do último lançamento, a fim de fornecer patches de backport caso um lançamento de manutenção seja necessário. +Assim, quando você clona o repositório Git, você tem quatro branches nos quais pode fazer checkout para avaliar o projeto em diferentes estágios de desenvolvimento, dependendo do quão inovador você deseja ser ou de como deseja contribuir; e o mantenedor tem um fluxo de trabalho estruturado para ajudá-lo a examinar (vet) novas contribuições. +O fluxo de trabalho do projeto Git é especializado. +Para entender claramente isso, você poderia conferir o https://github.com/git/git/blob/master/Documentation/howto/maintain-git.txt[Guia do Mantenedor do Git^]. [[_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. +Outros mantenedores preferem fazer rebase ou cherry-pick do trabalho contribuído no topo do seu branch `master`, em vez de fazer o merge dele, para manter um histórico majoritariamente linear. +Quando você tem trabalho em um branch de tópico e determina que deseja integrá-lo, você se move para esse branch e executa o comando rebase para reconstruir as alterações no topo do seu branch `master` (ou `develop`, e assim por diante) atual. +Se isso funcionar bem, você pode fazer um fast-forward no seu branch `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: +A outra maneira de mover o trabalho introduzido de um branch para outro é fazer o cherry-pick dele. +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 branch em que você está no momento. +Isso é útil se você tem vários commits num branch de tópico e quer integrar apenas um deles, ou se tem apenas um commit num branch de tópico e prefere fazer o cherry-pick em vez de executar o rebase. +Por exemplo, suponha que você tenha um projeto parecido com este: -.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 +image::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 (pull) o commit `e43a6` para o seu branch `master`, você pode executar: [source,console] ---- @@ -394,44 +394,44 @@ Finished one cherry-pick. 3 files changed, 17 insertions(+), 3 deletions(-) ---- -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 alteração introduzida em `e43a6`, mas você obtém um novo valor SHA-1 de commit, porque a data de aplicação é diferente. +Agora o seu histórico se parece com isso: -.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 fazer o cherry-pick de um commit num branch de tópico +image::images/rebasing-2.png[Histórico após fazer o cherry-pick de um commit num branch 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 o seu branch de tópico e descartar os commits que você não quis 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. +Se você está fazendo muitos merges e rebases, ou está mantendo um branch de tópico de longa vida, 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`" (reutilizar resolução registrada) -- é uma forma de atalhar a resolução manual de conflitos. +Quando o rerere está ativado, o Git mantém um conjunto de pré e pós-imagens de merges bem-sucedidos e, se perceber que há um conflito exatamente igual a um que você já corrigiu, ele 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: +Esse recurso vem em duas partes: uma configuração e um comando. +A configuração é `rerere.enabled`, e é útil o suficiente para ser colocada em 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á registrada 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 precisar, 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`). +Existem também subcomandos para ver o que será registrado, para apagar resoluções específicas do cache e para limpar todo o cache. +Cobriremos o rerere em mais detalhes em <>. [[_tagging_releases]] -==== Tagging Your Releases +==== Adicionando Tags aos Seus Lançamentos (((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ê tiver decidido cortar um lançamento (release), provavelmente desejará atribuir uma tag para poder recriar esse lançamento em qualquer momento no futuro. +Você pode criar uma nova tag conforme discutido em <>. +Se você decidir assinar a tag como mantenedor, a marcação com tag pode se parecer com isso: [source,console] ---- @@ -441,9 +441,9 @@ user: "Scott Chacon " 1024-bit DSA key, ID F721C45A, created 2009-02-09 ---- -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ê realmente assinar as suas tags, pode ter o problema de distribuir a chave pública PGP usada para assinar as suas tags. +O mantenedor do projeto Git resolveu esse problema incluindo a sua chave pública como um blob no repositório e então adicionando uma tag que aponta diretamente para esse conteúdo. +Para fazer isso, você pode descobrir qual chave deseja executando `gpg --list-keys`: [source,console] ---- @@ -455,7 +455,7 @@ uid Scott Chacon sub 2048g/45D02282 2009-02-09 [expires: 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: +Em seguida, você pode importar diretamente a chave para o banco de dados do Git, exportando-a e passando o resultado via pipe pelo `git hash-object`, que grava um novo blob com esse conteúdo no Git e retorna o SHA-1 do blob para você: [source,console] ---- @@ -463,30 +463,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 de sua chave no Git, pode criar uma tag que aponte diretamente para ele, especificando o novo valor SHA-1 que o comando `hash-object` lhe deu: [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ê rodar `git push --tags`, a tag `maintainer-pgp-pub` será compartilhada com todos. +Se alguém quiser verificar uma tag, eles podem importar diretamente a sua chave PGP, retirando 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, rodar `git show ` permitirá que você dê ao usuário final instruções mais específicas sobre a verificação de tags. [[_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): +Como o Git não possui números monotonicamente crescentes como 'v123' ou o equivalente para acompanhar cada commit, se você deseja ter um nome legível por humanos para acompanhar um commit, você pode rodar o `git describe` nesse commit. +Em resposta, o Git gera uma string que consiste no nome da tag mais recente anterior a esse commit, seguida pelo número de commits desde essa tag e, finalmente, por um valor SHA-1 parcial do commit que está sendo descrito (prefixado com a letra "g" que significa Git): [source,console] ---- @@ -494,21 +494,21 @@ $ 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 com algo compreensível para as pessoas. +Na verdade, se você compilar o Git a partir do código-fonte clonado do repositório Git, o `git --version` lhe dará algo que se parece com isto. +Se você estiver descrevendo um commit que marcou diretamente com uma tag, ele lhe dará simplesmente 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 também as tags leves (lightweight tags, não anotadas), adicione a opção `--tags` ao comando. +Você também pode usar essa string como o alvo de um comando `git checkout` ou `git show`, embora ele dependa do valor SHA-1 abreviado no final, portanto pode não ser válido para sempre. +Por exemplo, o kernel do Linux pulou recentemente de 8 para 10 caracteres para garantir a exclusividade do objeto SHA-1, portanto, nomes de saída mais antigos do `git describe` foram invalidados. [[_preparing_release]] -==== Preparing a Release +==== Preparando um Lançamento (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`: +Agora você quer lançar (release) um build. +Uma das coisas que você vai querer fazer é criar um arquivo compactado (archive) do snapshot mais recente do seu código para aquelas pobres almas que não usam o Git. +O comando para fazer isso é `git archive`: [source,console] ---- @@ -517,23 +517,23 @@ $ 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 tarball, obterá o snapshot mais recente do seu projeto dentro de um diretório `project`. +Você também pode criar um arquivo zip da mesma maneira, mas passando a opção `--format=zip` para o `git archive`: [source,console] ---- $ 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 belo tarball e um arquivo zip do lançamento do seu projeto que você pode fazer upload para o seu site ou enviar por e-mail para as pessoas. [[_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`: +É hora de enviar um e-mail para a sua lista de discussão de pessoas que querem saber o que está acontecendo no seu projeto. +Uma maneira legal de obter rapidamente uma espécie de changelog do que foi adicionado ao seu projeto desde o seu último lançamento ou e-mail é usar o comando `git shortlog`. +Ele resume todos os commits no intervalo que você fornece; por exemplo, o seguinte lhe dá um resumo de todos os commits desde o seu último lançamento, se o seu último lançamento se chamasse `v1.0.1`: [source,console] ---- @@ -553,4 +553,4 @@ 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ê obtém um resumo limpo de todos os commits desde a `v1.0.1`, agrupados por autor, que você pode enviar por e-mail para a sua lista. diff --git a/ch05-distributed-git.asc b/ch05-distributed-git.asc index 588a2174..a3322198 100644 --- a/ch05-distributed-git.asc +++ b/ch05-distributed-git.asc @@ -1,11 +1,11 @@ [[ch05-distributed-git]] -== Distributed Git +== Git Distribuído (((distributed git))) -Now that you have a remote Git repository set up as a focal point for all the developers to share their code, and you're familiar with basic Git commands in a local workflow, you'll look at how to utilize some of the distributed workflows that Git affords you. +Agora que você tem um repositório Git remoto configurado como um ponto focal para todos os desenvolvedores compartilharem os seus códigos, e está familiarizado com os comandos básicos do Git em um fluxo de trabalho local, verá como utilizar alguns dos fluxos de trabalho distribuídos que o Git oferece. -In this chapter, you'll see how to work with Git in a distributed environment as a contributor and an integrator. -That is, you'll learn how to contribute code successfully to a project and make it as easy on you and the project maintainer as possible, and also how to maintain a project successfully with a number of developers contributing. +Neste capítulo, você verá como trabalhar com o Git em um ambiente distribuído como contribuidor (contributor) e integrador (integrator). +Ou seja, você aprenderá como contribuir com código para um projeto com sucesso e torná-lo o mais fácil possível para você e para o mantenedor do projeto, e também como manter um projeto com sucesso com vários desenvolvedores contribuindo. include::book/05-distributed-git/sections/distributed-workflows.asc[] @@ -13,8 +13,8 @@ include::book/05-distributed-git/sections/contributing.asc[] include::book/05-distributed-git/sections/maintaining.asc[] -=== Summary +=== Resumo -You should feel fairly comfortable contributing to a project in Git as well as maintaining your own project or integrating other users' contributions. -Congratulations on being an effective Git developer! -In the next chapter, you'll learn about how to use the largest and most popular Git hosting service, GitHub. +Você deve se sentir bastante confortável contribuindo para um projeto no Git, bem como mantendo o seu próprio projeto ou integrando contribuições de outros usuários. +Parabéns por ser um desenvolvedor Git eficaz! +No próximo capítulo, você aprenderá sobre como usar o maior e mais popular serviço de hospedagem Git, o GitHub. From 501966e586d0933f79a7c9754d8c734e0ecae0e7 Mon Sep 17 00:00:00 2001 From: "Sergio Cabral (AI Agent)" Date: Thu, 20 Aug 2026 13:51:58 -0300 Subject: [PATCH 08/16] =?UTF-8?q?Traduz:=20Cap=C3=ADtulo=206=20=E2=80=94?= =?UTF-8?q?=20GitHub?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../sections/1-setting-up-account.asc | 112 ++-- book/06-github/sections/2-contributing.asc | 498 +++++++++--------- book/06-github/sections/3-maintaining.asc | 376 ++++++------- .../sections/4-managing-organization.asc | 88 ++-- book/06-github/sections/5-scripting.asc | 204 +++---- ch06-github.asc | 26 +- 6 files changed, 652 insertions(+), 652 deletions(-) diff --git a/book/06-github/sections/1-setting-up-account.asc b/book/06-github/sections/1-setting-up-account.asc index 2ab023ec..73527f5b 100644 --- a/book/06-github/sections/1-setting-up-account.asc +++ b/book/06-github/sections/1-setting-up-account.asc @@ -1,97 +1,97 @@ -=== Account Setup and Configuration +=== Configuração e Ajustes de Conta (((GitHub, user accounts))) -The first thing you need to do is set up a free user account. -Simply visit https://github.com[^], choose a user name that isn't already taken, provide an email address and a password, and click the big green "`Sign up for GitHub`" button. +A primeira coisa que você precisa fazer é configurar uma conta de usuário gratuita. +Basta visitar https://github.com[^], escolher um nome de usuário que ainda não tenha sido usado, fornecer um endereço de e-mail e uma senha, e clicar no botão verde grande "`Sign up for GitHub`". -.The GitHub sign-up form -image::images/signup.png[The GitHub sign-up form] +.O formulário de inscrição do GitHub +image::images/signup.png[O formulário de inscrição do GitHub] -The next thing you'll see is the pricing page for upgraded plans, but it's safe to ignore this for now. -GitHub will send you an email to verify the address you provided. -Go ahead and do this; it's pretty important (as we'll see later). +A próxima coisa que você verá é a página de preços para planos atualizados, mas é seguro ignorá-la por enquanto. +O GitHub lhe enviará um e-mail para verificar o endereço que você forneceu. +Vá em frente e faça isso; é muito importante (como veremos mais adiante). [NOTE] ==== -GitHub provides almost all of its functionality with free accounts, except some advanced features. +O GitHub fornece quase toda a sua funcionalidade em contas gratuitas, exceto alguns recursos avançados. -GitHub's paid plans include advanced tools and features as well as increased limits for free services, but we won't be covering those in this book. -To get more information about available plans and their comparison, visit https://github.com/pricing[^]. +Os planos pagos do GitHub incluem ferramentas e recursos avançados, bem como limites maiores para serviços gratuitos, mas não os abordaremos neste livro. +Para obter mais informações sobre os planos disponíveis e sua comparação, visite https://github.com/pricing[^]. ==== -Clicking the Octocat logo at the top-left of the screen will take you to your dashboard page. -You're now ready to use GitHub. +Clicar no logotipo Octocat no canto superior esquerdo da tela levará você para a página do seu painel. +Agora você está pronto para usar o GitHub. -==== SSH Access +==== Acesso SSH (((SSH keys, with GitHub))) -As of right now, you're fully able to connect with Git repositories using the `https://` protocol, authenticating with the username and password you just set up. -However, to simply clone public projects, you don't even need to sign up - the account we just created comes into play when we fork projects and push to our forks a bit later. +A partir de agora, você está totalmente apto a se conectar com repositórios Git usando o protocolo `https://`, autenticando-se com o nome de usuário e senha que você acabou de configurar. +No entanto, para simplesmente clonar projetos públicos, você nem precisa se inscrever - a conta que acabamos de criar entra em jogo quando fazemos fork de projetos e fazemos push para nossos forks um pouco mais tarde. -If you'd like to use SSH remotes, you'll need to configure a public key. -If you don't already have one, see <>. -Open up your account settings using the link at the top-right of the window: +Se você quiser usar remotos SSH, precisará configurar uma chave pública. +Se você ainda não tiver uma, veja <>. +Abra as configurações da sua conta usando o link no canto superior direito da janela: -.The "`Account settings`" link -image::images/account-settings.png[The “Account settings” link] +.O link "`Account settings`" +image::images/account-settings.png[O link "Account settings"] -Then select the "`SSH keys`" section along the left-hand side. +Em seguida, selecione a seção "`SSH keys`" ao longo do lado esquerdo. -.The "`SSH keys`" link -image::images/ssh-keys.png[The “SSH keys” link] +.O link "`SSH keys`" +image::images/ssh-keys.png[O link "SSH keys"] -From there, click the "`Add an SSH key`" button, give your key a name, paste the contents of your `~/.ssh/id_rsa.pub` (or whatever you named it) public-key file into the text area, and click "`Add key`". +A partir daí, clique no botão "`Add an SSH key`", dê um nome à sua chave, cole o conteúdo do seu arquivo de chave pública `~/.ssh/id_rsa.pub` (ou qualquer que seja o nome dele) na área de texto e clique em "`Add key`". [NOTE] ==== -Be sure to name your SSH key something you can remember. -You can name each of your keys (e.g. "My Laptop" or "Work Account") so that if you need to revoke a key later, you can easily tell which one you're looking for. +Certifique-se de nomear sua chave SSH com algo que você possa lembrar. +Você pode nomear cada uma de suas chaves (ex: "Meu Laptop" ou "Conta de Trabalho") para que, se precisar revogar uma chave mais tarde, possa saber facilmente qual está procurando. ==== [[_personal_avatar]] -==== Your Avatar +==== O Seu Avatar -Next, if you wish, you can replace the avatar that is generated for you with an image of your choosing. -First go to the "`Profile`" tab (above the SSH Keys tab) and click "`Upload new picture`". +Em seguida, se desejar, você pode substituir o avatar gerado para você por uma imagem de sua escolha. +Primeiro vá para a aba "`Profile`" (perfil, acima da aba SSH Keys) e clique em "`Upload new picture`" (carregar nova imagem). -.The "`Profile`" link -image::images/your-profile.png[The “Profile” link] +.O link "`Profile`" +image::images/your-profile.png[O link "Profile"] -We'll choose a copy of the Git logo that is on our hard drive and then we get a chance to crop it. +Nós escolheremos uma cópia do logotipo do Git que está no nosso disco rígido e então teremos a chance de recortá-lo. -.Crop your uploaded avatar -image::images/avatar-crop.png[Crop your uploaded avatar] +.Recorte o seu avatar carregado +image::images/avatar-crop.png[Recorte o seu avatar carregado] -Now anywhere you interact on the site, people will see your avatar next to your username. +Agora, em qualquer lugar que você interagir no site, as pessoas verão o seu avatar ao lado do seu nome de usuário. -If you happen to have uploaded an avatar to the popular Gravatar service (often used for WordPress accounts), that avatar will be used by default and you don't need to do this step. +Se por acaso você tiver carregado um avatar no popular serviço Gravatar (frequentemente usado para contas WordPress), esse avatar será usado por padrão e você não precisa fazer esta etapa. -==== Your Email Addresses +==== Os Seus Endereços de E-mail -The way that GitHub maps your Git commits to your user is by email address. -If you use multiple email addresses in your commits and you want GitHub to link them up properly, you need to add all the email addresses you have used to the Emails section of the admin section. +A maneira como o GitHub mapeia os seus commits do Git para o seu usuário é pelo endereço de e-mail. +Se você usa vários endereços de e-mail nos seus commits e quer que o GitHub os vincule adequadamente, precisa adicionar todos os endereços de e-mail que você usou na seção Emails da seção de administração. [[_add_email_addresses]] -.Add all your email addresses -image::images/email-settings.png[Add all your email addresses] +.Adicione todos os seus endereços de e-mail +image::images/email-settings.png[Adicione todos os seus endereços de e-mail] -In <<_add_email_addresses>> we can see some of the different states that are possible. -The top address is verified and set as the primary address, meaning that is where you'll get any notifications and receipts. -The second address is verified and so can be set as the primary if you wish to switch them. -The final address is unverified, meaning that you can't make it your primary address. -If GitHub sees any of these in commit messages in any repository on the site, it will be linked to your user now. +Em <<_add_email_addresses>> podemos ver alguns dos diferentes estados que são possíveis. +O endereço do topo é verificado e definido como o endereço principal, o que significa que é lá que você receberá quaisquer notificações e recibos. +O segundo endereço é verificado e, portanto, pode ser definido como principal se você desejar trocá-los. +O último endereço não é verificado, o que significa que você não pode torná-lo o seu endereço principal. +Se o GitHub vir qualquer um desses nas mensagens de commit em qualquer repositório no site, ele será vinculado ao seu usuário agora. -==== Two Factor Authentication +==== Autenticação de Dois Fatores -Finally, for extra security, you should definitely set up Two-factor Authentication or "`2FA`". -Two-factor Authentication is an authentication mechanism that is becoming more and more popular recently to mitigate the risk of your account being compromised if your password is stolen somehow. -Turning it on will make GitHub ask you for two different methods of authentication, so that if one of them is compromised, an attacker will not be able to access your account. +Finalmente, para segurança extra, você definitivamente deve configurar a Autenticação de Dois Fatores ou "`2FA`" (Two-factor Authentication). +A Autenticação de Dois Fatores é um mecanismo de autenticação que está se tornando cada vez mais popular recentemente para mitigar o risco de a sua conta ser comprometida se a sua senha for roubada de alguma forma. +Ao ativá-la, o GitHub pedirá dois métodos diferentes de autenticação, de modo que, se um deles for comprometido, um invasor não conseguirá acessar a sua conta. -You can find the Two-factor Authentication setup under the Security tab of your Account settings. +Você pode encontrar a configuração de Autenticação de Dois Fatores na aba Security (Segurança) das configurações da sua Conta. -.2FA in the Security Tab -image::images/2fa-1.png[2FA in the Security Tab] +.2FA na aba Security +image::images/2fa-1.png[2FA na aba Security] -If you click on the "`Set up two-factor authentication`" button, it will take you to a configuration page where you can choose to use a phone app to generate your secondary code (a "`time based one-time password`"), or you can have GitHub send you a code via SMS each time you need to log in. +Se você clicar no botão "`Set up two-factor authentication`", ele o levará a uma página de configuração onde você pode escolher usar um aplicativo de telefone para gerar o seu código secundário (uma "`senha de uso único baseada em tempo`" ou time based one-time password), ou pode fazer com que o GitHub lhe envie um código via SMS cada vez que você precisar fazer login. -After you choose which method you prefer and follow the instructions for setting up 2FA, your account will then be a little more secure and you will have to provide a code in addition to your password whenever you log into GitHub. +Depois de escolher o método de sua preferência e seguir as instruções para configurar o 2FA, a sua conta ficará um pouco mais segura e você terá que fornecer um código além da sua senha sempre que fizer login no GitHub. diff --git a/book/06-github/sections/2-contributing.asc b/book/06-github/sections/2-contributing.asc index 1dffbd9a..90898c53 100644 --- a/book/06-github/sections/2-contributing.asc +++ b/book/06-github/sections/2-contributing.asc @@ -1,74 +1,74 @@ -=== Contributing to a Project +=== Contribuindo para um Projeto -Now that our account is set up, let's walk through some details that could be useful in helping you contribute to an existing project. +Agora que a nossa conta está configurada, vamos examinar alguns detalhes que podem ser úteis para ajudá-lo a contribuir com um projeto existente. -==== Forking Projects +==== Fazendo Fork de Projetos (((forking))) -If you want to contribute to an existing project to which you don't have push access, you can "`fork`" the project. -When you "`fork`" a project, GitHub will make a copy of the project that is entirely yours; it lives in your namespace, and you can push to it. +Se você quiser contribuir com um projeto existente ao qual não tem acesso de push, você pode fazer um "`fork`" do projeto. +Quando você faz um "`fork`" de um projeto, o GitHub faz uma cópia do projeto que é inteiramente sua; ela vive no seu namespace e você pode fazer push para ela. [NOTE] ==== -Historically, the term "`fork`" has been somewhat negative in context, meaning that someone took an open source project in a different direction, sometimes creating a competing project and splitting the contributors. -In GitHub, a "`fork`" is simply the same project in your own namespace, allowing you to make changes to a project publicly as a way to contribute in a more open manner. +Historicamente, o termo "`fork`" tem sido um tanto negativo em seu contexto, significando que alguém levou um projeto de código aberto para uma direção diferente, às vezes criando um projeto concorrente e dividindo os contribuidores. +No GitHub, um "`fork`" é simplesmente o mesmo projeto no seu próprio namespace, permitindo que você faça alterações em um projeto publicamente como uma forma de contribuir de maneira mais aberta. ==== -This way, projects don't have to worry about adding users as collaborators to give them push access. -People can fork a project, push to it, and contribute their changes back to the original repository by creating what's called a Pull Request, which we'll cover next. -This opens up a discussion thread with code review, and the owner and the contributor can then communicate about the change until the owner is happy with it, at which point the owner can merge it in. +Dessa forma, os projetos não precisam se preocupar em adicionar usuários como colaboradores para lhes dar acesso de push. +As pessoas podem fazer o fork de um projeto, fazer push nele e contribuir com as suas alterações de volta ao repositório original criando o que é chamado de Pull Request, que abordaremos a seguir. +Isso abre um tópico de discussão com revisão de código, e o proprietário e o contribuidor podem então se comunicar sobre a alteração até que o proprietário esteja satisfeito com ela, momento em que o proprietário pode mesclá-la. -To fork a project, visit the project page and click the "`Fork`" button at the top-right of the page. +Para fazer o fork de um projeto, visite a página do projeto e clique no botão "`Fork`" no canto superior direito da página. -.The "`Fork`" button -image::images/forkbutton.png[The “Fork” button] +.O botão "`Fork`" +image::images/forkbutton.png[O botão "Fork"] -After a few seconds, you'll be taken to your new project page, with your own writeable copy of the code. +Depois de alguns segundos, você será levado para a página do seu novo projeto, com a sua própria cópia editável do código. [[ch06-github_flow]] -==== The GitHub Flow +==== O Fluxo do GitHub (GitHub Flow) (((GitHub, Flow))) -GitHub is designed around a particular collaboration workflow, centered on Pull Requests. -This flow works whether you're collaborating with a tightly-knit team in a single shared repository, or a globally-distributed company or network of strangers contributing to a project through dozens of forks. -It is centered on the <> workflow covered in <>. +O GitHub é projetado em torno de um fluxo de trabalho de colaboração particular, centrado em Pull Requests. +Esse fluxo funciona quer você esteja colaborando com uma equipe unida em um único repositório compartilhado, ou com uma empresa distribuída globalmente ou uma rede de estranhos contribuindo para um projeto por meio de dezenas de forks. +Ele é centrado no fluxo de trabalho de <> abordado em <>. -Here's how it generally works: +Eis como isso geralmente funciona: -1. Fork the project. -2. Create a topic branch from `master`. -3. Make some commits to improve the project. -4. Push this branch to your GitHub project. -5. Open a Pull Request on GitHub. -6. Discuss, and optionally continue committing. -7. The project owner merges or closes the Pull Request. -8. Sync the updated `master` back to your fork. +1. Faça um fork do projeto. +2. Crie um branch de tópico a partir do `master`. +3. Faça alguns commits para melhorar o projeto. +4. Faça um push deste branch para o seu projeto no GitHub. +5. Abra um Pull Request no GitHub. +6. Discuta e, opcionalmente, continue a fazer commits. +7. O proprietário do projeto mescla (merge) ou fecha (close) o Pull Request. +8. Sincronize o `master` atualizado de volta para o seu fork. -This is basically the Integration Manager workflow covered in <>, but instead of using email to communicate and review changes, teams use GitHub's web based tools. +Este é basicamente o fluxo de trabalho de Gerente de Integração (Integration Manager) abordado em <>, mas em vez de usar e-mail para comunicar e revisar as alterações, as equipes usam as ferramentas baseadas na web do GitHub. -Let's walk through an example of proposing a change to an open source project hosted on GitHub using this flow. +Vamos analisar um exemplo de proposição de uma alteração a um projeto de código aberto hospedado no GitHub usando este fluxo. [TIP] ==== -You can use the official *GitHub CLI* tool instead of the GitHub web interface for most things. -The tool can be used on Windows, macOS, and Linux systems. -Go to the https://cli.github.com/[GitHub CLI homepage^] for installation instructions and the manual. +Você pode usar a ferramenta oficial *GitHub CLI* em vez da interface web do GitHub para a maioria das coisas. +A ferramenta pode ser usada em sistemas Windows, macOS e Linux. +Vá para a https://cli.github.com/[página inicial do GitHub CLI^] para instruções de instalação e o manual. ==== -===== Creating a Pull Request +===== Criando um Pull Request -Tony is looking for code to run on his Arduino programmable microcontroller and has found a great program file on GitHub at https://github.com/schacon/blink[^]. +Tony está procurando um código para rodar no seu microcontrolador programável Arduino e encontrou um ótimo arquivo de programa no GitHub em https://github.com/schacon/blink[^]. -.The project we want to contribute to -image::images/blink-01-start.png[The project we want to contribute to] +.O projeto com o qual queremos contribuir +image::images/blink-01-start.png[O projeto com o qual queremos contribuir] -The only problem is that the blinking rate is too fast. -We think it's much nicer to wait 3 seconds instead of 1 in between each state change. -So let's improve the program and submit it back to the project as a proposed change. +O único problema é que a taxa de piscar está muito rápida. +Achamos que é muito mais agradável esperar 3 segundos em vez de 1 entre cada mudança de estado. +Então, vamos melhorar o programa e enviá-lo de volta ao projeto como uma alteração proposta. -First, we click the 'Fork' button as mentioned earlier to get our own copy of the project. -Our user name here is "`tonychacon`" so our copy of this project is at `https://github.com/tonychacon/blink` and that's where we can edit it. -We will clone it locally, create a topic branch, make the code change and finally push that change back up to GitHub. +Primeiro, clicamos no botão 'Fork' (Fazer Fork) como mencionado anteriormente para obtermos a nossa própria cópia do projeto. +O nosso nome de usuário aqui é "`tonychacon`", então a nossa cópia deste projeto está em `https://github.com/tonychacon/blink` e é lá que podemos editá-lo. +Vamos cloná-lo localmente, criar um branch de tópico, fazer a alteração no código e finalmente fazer o push dessa alteração de volta para o GitHub. [source,console] ---- @@ -113,135 +113,135 @@ To https://github.com/tonychacon/blink * [new branch] slow-blink -> slow-blink ---- -<1> Clone our fork of the project locally. -<2> Create a descriptive topic branch. -<3> Make our change to the code. -<4> Check that the change is good. -<5> Commit our change to the topic branch. -<6> Push our new topic branch back up to our GitHub fork. +<1> Clone o nosso fork do projeto localmente. +<2> Crie um branch de tópico descritivo. +<3> Faça a nossa alteração no código. +<4> Verifique se a alteração está boa. +<5> Faça o commit da nossa alteração para o branch de tópico. +<6> Faça o push do nosso novo branch de tópico de volta para o nosso fork no GitHub. -Now if we go back to our fork on GitHub, we can see that GitHub noticed that we pushed a new topic branch up and presents us with a big green button to check out our changes and open a Pull Request to the original project. +Agora, se voltarmos para o nosso fork no GitHub, podemos ver que o GitHub notou que fizemos o push de um novo branch de tópico e nos apresenta um grande botão verde para verificar as nossas alterações e abrir um Pull Request para o projeto original. -You can alternatively go to the "`Branches`" page at `\https://github.com///branches` to locate your branch and open a new Pull Request from there. +Alternativamente, você pode ir para a página "`Branches`" em `\https://github.com///branches` para localizar o seu branch e abrir um novo Pull Request a partir de lá. -.Pull Request button -image::images/blink-02-pr.png[Pull Request button] +.Botão de Pull Request +image::images/blink-02-pr.png[Botão de Pull Request] (((GitHub, pull requests))) -If we click that green button, we'll see a screen that asks us to give our Pull Request a title and description. -It is almost always worthwhile to put some effort into this, since a good description helps the owner of the original project determine what you were trying to do, whether your proposed changes are correct, and whether accepting the changes would improve the original project. +Se clicarmos naquele botão verde, veremos uma tela que nos pede para dar um título e uma descrição ao nosso Pull Request. +Quase sempre vale a pena colocar algum esforço nisso, já que uma boa descrição ajuda o proprietário do projeto original a determinar o que você estava tentando fazer, se as alterações propostas estão corretas e se a aceitação das alterações melhoraria o projeto original. -We also see a list of the commits in our topic branch that are "`ahead`" of the `master` branch (in this case, just the one) and a unified diff of all the changes that will be made should this branch get merged by the project owner. +Também vemos uma lista dos commits em nosso branch de tópico que estão "`à frente`" (ahead) do branch `master` (neste caso, apenas um) e um diff unificado de todas as alterações que serão feitas caso este branch seja mesclado pelo proprietário do projeto. -.Pull Request creation page -image::images/blink-03-pull-request-open.png[Pull Request creation page] +.Página de criação de Pull Request +image::images/blink-03-pull-request-open.png[Página de criação de Pull Request] -When you hit the 'Create pull request' button on this screen, the owner of the project you forked will get a notification that someone is suggesting a change and will link to a page that has all of this information on it. +Quando você clica no botão 'Create pull request' nesta tela, o proprietário do projeto do qual você fez fork receberá uma notificação de que alguém está sugerindo uma alteração e fornecerá um link para uma página que contém todas essas informações. [NOTE] ==== -Though Pull Requests are used commonly for public projects like this when the contributor has a complete change ready to be made, it's also often used in internal projects _at the beginning_ of the development cycle. -Since you can keep pushing to the topic branch even *after* the Pull Request is opened, it's often opened early and used as a way to iterate on work as a team within a context, rather than opened at the very end of the process. +Embora Pull Requests sejam comumente usados para projetos públicos como este quando o contribuidor tem uma alteração completa pronta para ser feita, eles também são frequentemente usados em projetos internos _no início_ do ciclo de desenvolvimento. +Como você pode continuar fazendo push para o branch de tópico mesmo *após* a abertura do Pull Request, ele costuma ser aberto no início e usado como uma forma de iterar no trabalho em equipe dentro de um contexto, em vez de ser aberto apenas no final do processo. ==== -===== Iterating on a Pull Request +===== Iterando em um Pull Request -At this point, the project owner can look at the suggested change and merge it, reject it or comment on it. -Let's say that he likes the idea, but would prefer a slightly longer time for the light to be off than on. +Neste ponto, o proprietário do projeto pode examinar a alteração sugerida e mesclá-la, rejeitá-la ou comentá-la. +Digamos que ele goste da ideia, mas preferisse um tempo um pouco maior para a luz ficar apagada do que acesa. -Where this conversation may take place over email in the workflows presented in <>, on GitHub this happens online. -The project owner can review the unified diff and leave a comment by clicking on any of the lines. +Onde essa conversa poderia ocorrer por e-mail nos fluxos de trabalho apresentados em <>, no GitHub ela acontece online. +O proprietário do projeto pode revisar o diff unificado e deixar um comentário clicando em qualquer uma das linhas. -.Comment on a specific line of code in a Pull Request -image::images/blink-04-pr-comment.png[Comment on a specific line of code in a Pull Request] +.Comentário em uma linha de código específica em um Pull Request +image::images/blink-04-pr-comment.png[Comentário em uma linha de código específica em um Pull Request] -Once the maintainer makes this comment, the person who opened the Pull Request (and indeed, anyone else watching the repository) will get a notification. -We'll go over customizing this later, but if he had email notifications turned on, Tony would get an email like this: +Assim que o mantenedor faz esse comentário, a pessoa que abriu o Pull Request (e, na verdade, qualquer outra pessoa que esteja observando o repositório) receberá uma notificação. +Abordaremos a personalização disso mais tarde, mas se tivesse as notificações por e-mail ativadas, Tony receberia um e-mail como este: [[_email_notification]] -.Comments sent as email notifications -image::images/blink-04-email.png[Comments sent as email notifications] +.Comentários enviados como notificações por e-mail +image::images/blink-04-email.png[Comentários enviados como notificações por e-mail] -Anyone can also leave general comments on the Pull Request. -In <<_pr_discussion>> we can see an example of the project owner both commenting on a line of code and then leaving a general comment in the discussion section. -You can see that the code comments are brought into the conversation as well. +Qualquer pessoa também pode deixar comentários gerais sobre o Pull Request. +Em <<_pr_discussion>> podemos ver um exemplo do proprietário do projeto tanto comentando em uma linha de código quanto deixando um comentário geral na seção de discussão. +Você pode ver que os comentários de código também são trazidos para a conversa. [[_pr_discussion]] -.Pull Request discussion page -image::images/blink-05-general-comment.png[Pull Request discussion page] +.Página de discussão de Pull Request +image::images/blink-05-general-comment.png[Página de discussão de Pull Request] -Now the contributor can see what they need to do in order to get their change accepted. -Luckily this is very straightforward. -Where over email you may have to re-roll your series and resubmit it to the mailing list, with GitHub you simply commit to the topic branch again and push, which will automatically update the Pull Request. -In <<_pr_final>> you can also see that the old code comment has been collapsed in the updated Pull Request, since it was made on a line that has since been changed. +Agora o contribuidor pode ver o que precisa fazer para que a sua alteração seja aceita. +Felizmente, isso é muito simples. +Enquanto por e-mail você pode ter que reescrever (re-roll) a sua série e reenviá-la para a lista de discussão, com o GitHub você simplesmente faz um commit no branch de tópico novamente e faz o push, o que atualizará automaticamente o Pull Request. +Em <<_pr_final>>, você também pode ver que o comentário do código antigo foi ocultado no Pull Request atualizado, uma vez que foi feito em uma linha que já foi alterada. -Adding commits to an existing Pull Request doesn't trigger a notification, so once Tony has pushed his corrections he decides to leave a comment to inform the project owner that he made the requested change. +Adicionar commits a um Pull Request existente não aciona uma notificação, então, assim que Tony envia as suas correções, ele decide deixar um comentário para informar ao proprietário do projeto que fez a alteração solicitada. [[_pr_final]] -.Pull Request final -image::images/blink-06-final.png[Pull Request final] +.Final do Pull Request +image::images/blink-06-final.png[Final do Pull Request] -An interesting thing to notice is that if you click on the "`Files Changed`" tab on this Pull Request, you'll get the "`unified`" diff -- that is, the total aggregate difference that would be introduced to your main branch if this topic branch was merged in. -In `git diff` terms, it basically automatically shows you `git diff master...` for the branch this Pull Request is based on. -See <> for more about this type of diff. +Uma coisa interessante de se notar é que se você clicar na aba "`Files Changed`" (Arquivos Alterados) neste Pull Request, você obterá o diff "`unificado`" -- isto é, a diferença total agregada que seria introduzida no seu branch principal se este branch de tópico fosse mesclado. +Em termos de `git diff`, ele basicamente mostra automaticamente `git diff master...` para o branch no qual este Pull Request se baseia. +Veja <> para saber mais sobre esse tipo de diff. -The other thing you'll notice is that GitHub checks to see if the Pull Request merges cleanly and provides a button to do the merge for you on the server. -This button only shows up if you have write access to the repository and a trivial merge is possible. -If you click it GitHub will perform a "`non-fast-forward`" merge, meaning that even if the merge *could* be a fast-forward, it will still create a merge commit. +A outra coisa que você notará é que o GitHub verifica se o Pull Request se mescla de forma limpa e fornece um botão para fazer o merge para você no servidor. +Este botão só aparece se você tiver acesso de gravação (write access) ao repositório e um merge trivial for possível. +Se você clicar nele, o GitHub realizará um merge "`non-fast-forward`", o que significa que mesmo que o merge *pudesse* ser um fast-forward, ele ainda criará um commit de merge. -If you would prefer, you can simply pull the branch down and merge it locally. -If you merge this branch into the `master` branch and push it to GitHub, the Pull Request will automatically be closed. +Se preferir, você pode simplesmente fazer o pull do branch e mesclá-lo localmente. +Se você mesclar este branch no branch `master` e fizer o push para o GitHub, o Pull Request será fechado automaticamente. -This is the basic workflow that most GitHub projects use. -Topic branches are created, Pull Requests are opened on them, a discussion ensues, possibly more work is done on the branch and eventually the request is either closed or merged. +Este é o fluxo de trabalho básico que a maioria dos projetos do GitHub usa. +Branches de tópico são criados, Pull Requests são abertos neles, uma discussão se segue, possivelmente mais trabalho é feito no branch e, eventualmente, a solicitação é fechada ou mesclada. [NOTE] -.Not Only Forks +.Não Apenas Forks ==== -It's important to note that you can also open a Pull Request between two branches in the same repository. -If you're working on a feature with someone and you both have write access to the project, you can push a topic branch to the repository and open a Pull Request on it to the `master` branch of that same project to initiate the code review and discussion process. -No forking necessary. +É importante notar que você também pode abrir um Pull Request entre dois branches no mesmo repositório. +Se você estiver trabalhando em um recurso com alguém e ambos tiverem acesso de gravação ao projeto, você pode fazer o push de um branch de tópico para o repositório e abrir um Pull Request dele para o branch `master` desse mesmo projeto para iniciar o processo de revisão de código e discussão. +Nenhum fork é necessário. ==== -==== Advanced Pull Requests +==== Pull Requests Avançados -Now that we've covered the basics of contributing to a project on GitHub, let's cover a few interesting tips and tricks about Pull Requests so you can be more effective in using them. +Agora que cobrimos os fundamentos de contribuição para um projeto no GitHub, vamos abordar algumas dicas e truques interessantes sobre Pull Requests para que você possa ser mais eficaz ao usá-los. -===== Pull Requests as Patches +===== Pull Requests como Patches -It's important to understand that many projects don't really think of Pull Requests as queues of perfect patches that should apply cleanly in order, as most mailing list-based projects think of patch series contributions. -Most GitHub projects think about Pull Request branches as iterative conversations around a proposed change, culminating in a unified diff that is applied by merging. +É importante entender que muitos projetos não pensam realmente nos Pull Requests como filas de patches perfeitos que devem ser aplicados de forma limpa em ordem, como a maioria dos projetos baseados em lista de discussão pensa das contribuições de séries de patches. +A maioria dos projetos no GitHub pensa nos branches de Pull Request como conversas iterativas em torno de uma alteração proposta, culminando em um diff unificado que é aplicado por meio de merge. -This is an important distinction, because generally the change is suggested before the code is thought to be perfect, which is far more rare with mailing list based patch series contributions. -This enables an earlier conversation with the maintainers so that arriving at the proper solution is more of a community effort. -When code is proposed with a Pull Request and the maintainers or community suggest a change, the patch series is generally not re-rolled, but instead the difference is pushed as a new commit to the branch, moving the conversation forward with the context of the previous work intact. +Esta é uma distinção importante, porque geralmente a alteração é sugerida antes que o código seja considerado perfeito, o que é muito mais raro com contribuições de séries de patches baseadas em listas de discussão. +Isso permite uma conversa mais cedo com os mantenedores para que chegar à solução adequada seja mais um esforço da comunidade. +Quando um código é proposto com um Pull Request e os mantenedores ou a comunidade sugerem uma alteração, a série de patches geralmente não é reescrita, mas sim a diferença é enviada como um novo commit para o branch, avançando a conversa com o contexto do trabalho anterior intacto. -For instance, if you go back and look again at <<_pr_final>>, you'll notice that the contributor did not rebase his commit and send another Pull Request. -Instead they added new commits and pushed them to the existing branch. -This way if you go back and look at this Pull Request in the future, you can easily find all of the context of why decisions were made. -Pushing the "`Merge`" button on the site purposefully creates a merge commit that references the Pull Request so that it's easy to go back and research the original conversation if necessary. +Por exemplo, se você voltar e olhar novamente para <<_pr_final>>, notará que o contribuidor não fez um rebase do seu commit nem enviou outro Pull Request. +Em vez disso, eles adicionaram novos commits e fizeram push para o branch existente. +Dessa forma, se você voltar e analisar este Pull Request no futuro, poderá facilmente encontrar todo o contexto do porquê as decisões foram tomadas. +Clicar no botão "`Merge`" no site cria intencionalmente um commit de merge que faz referência ao Pull Request, para que seja fácil voltar e pesquisar a conversa original, se necessário. -===== Keeping up with Upstream +===== Acompanhando o Upstream -If your Pull Request becomes out of date or otherwise doesn't merge cleanly, you will want to fix it so the maintainer can easily merge it. -GitHub will test this for you and let you know at the bottom of every Pull Request if the merge is trivial or not. +Se o seu Pull Request ficar desatualizado ou não puder ser mesclado de forma limpa, você vai querer consertá-lo para que o mantenedor possa mesclá-lo facilmente. +O GitHub testará isso para você e informará na parte inferior de cada Pull Request se o merge é trivial ou não. [[_pr_fail]] -.Pull Request does not merge cleanly -image::images/pr-01-fail.png[Pull Request does not merge cleanly] +.Pull Request não se mescla de forma limpa +image::images/pr-01-fail.png[Pull Request não se mescla de forma limpa] -If you see something like <<_pr_fail>>, you'll want to fix your branch so that it turns green and the maintainer doesn't have to do extra work. +Se você vir algo como <<_pr_fail>>, você vai querer consertar o seu branch para que ele fique verde e o mantenedor não tenha que fazer trabalho extra. -You have two main options in order to do this. -You can either rebase your branch on top of whatever the target branch is (normally the `master` branch of the repository you forked), or you can merge the target branch into your branch. +Você tem duas opções principais para fazer isso. +Você pode fazer um rebase do seu branch em cima de qualquer que seja o branch de destino (normalmente o branch `master` do repositório do qual você fez fork), ou pode mesclar (merge) o branch de destino no seu branch. -Most developers on GitHub will choose to do the latter, for the same reasons we just went over in the previous section. -What matters is the history and the final merge, so rebasing isn't getting you much other than a slightly cleaner history and in return is *far* more difficult and error prone. +A maioria dos desenvolvedores no GitHub escolherá fazer o último, pelas mesmas razões que acabamos de ver na seção anterior. +O que importa é o histórico e o merge final, então fazer rebase não está lhe dando muito além de um histórico ligeiramente mais limpo e, em troca, é *muito* mais difícil e propenso a erros. -If you want to merge in the target branch to make your Pull Request mergeable, you would add the original repository as a new remote, fetch from it, merge the main branch of that repository into your topic branch, fix any issues and finally push it back up to the same branch you opened the Pull Request on. +Se você quiser mesclar o branch de destino para tornar o seu Pull Request passível de merge, você adicionaria o repositório original como um novo remoto, faria um fetch dele, mesclaria o branch principal daquele repositório no seu branch de tópico, consertaria quaisquer problemas e finalmente faria o push de volta para o mesmo branch em que você abriu o Pull Request. -For example, let's say that in the "`tonychacon`" example we were using before, the original author made a change that would create a conflict in the Pull Request. -Let's go through those steps. +Por exemplo, digamos que no exemplo do "`tonychacon`" que estávamos usando antes, o autor original tenha feito uma alteração que criaria um conflito no Pull Request. +Vamos percorrer essas etapas. [source,console] ---- @@ -276,87 +276,87 @@ To https://github.com/tonychacon/blink ef4725c..3c8d735 slower-blink -> slow-blink ---- -<1> Add the original repository as a remote named `upstream`. -<2> Fetch the newest work from that remote. -<3> Merge the main branch of that repository into your topic branch. -<4> Fix the conflict that occurred. -<5> Push back up to the same topic branch. +<1> Adicione o repositório original como um remoto chamado `upstream`. +<2> Faça um fetch do trabalho mais recente daquele remoto. +<3> Mescle o branch principal daquele repositório no seu branch de tópico. +<4> Conserte o conflito que ocorreu. +<5> Faça o push de volta para o mesmo branch de tópico. -Once you do that, the Pull Request will be automatically updated and re-checked to see if it merges cleanly. +Assim que você fizer isso, o Pull Request será automaticamente atualizado e verificado novamente para ver se ele se mescla de forma limpa. [[_pr_merge_fix]] -.Pull Request now merges cleanly -image::images/pr-02-merge-fix.png[Pull Request now merges cleanly] +.O Pull Request agora se mescla de forma limpa +image::images/pr-02-merge-fix.png[O Pull Request agora se mescla de forma limpa] -One of the great things about Git is that you can do that continuously. -If you have a very long-running project, you can easily merge from the target branch over and over again and only have to deal with conflicts that have arisen since the last time that you merged, making the process very manageable. +Uma das grandes coisas sobre o Git é que você pode fazer isso continuamente. +Se você tiver um projeto muito longo, poderá facilmente fazer merge do branch de destino repetidas vezes e só terá que lidar com os conflitos que surgiram desde a última vez que você fez merge, tornando o processo muito gerenciável. -If you absolutely wish to rebase the branch to clean it up, you can certainly do so, but it is highly encouraged to not force push over the branch that the Pull Request is already opened on. -If other people have pulled it down and done more work on it, you run into all of the issues outlined in <>. -Instead, push the rebased branch to a new branch on GitHub and open a brand new Pull Request referencing the old one, then close the original. +Se você absolutamente deseja fazer rebase do branch para limpá-lo, certamente pode fazê-lo, mas é altamente recomendável não fazer um push forçado (force push) sobre o branch em que o Pull Request já está aberto. +Se outras pessoas tiverem feito o pull dele e feito mais trabalho nele, você encontrará todos os problemas descritos em <>. +Em vez disso, faça o push do branch que sofreu rebase para um novo branch no GitHub e abra um Pull Request totalmente novo fazendo referência ao antigo, depois feche o original. -===== References +===== Referências -Your next question may be "`How do I reference the old Pull Request?`". -It turns out there are many, many ways to reference other things almost anywhere you can write in GitHub. +A sua próxima pergunta pode ser "`Como faço referência ao Pull Request antigo?`". +Acontece que existem muitas, muitas maneiras de referenciar outras coisas em quase qualquer lugar onde você pode escrever no GitHub. -Let's start with how to cross-reference another Pull Request or an Issue. -All Pull Requests and Issues are assigned numbers and they are unique within the project. -For example, you can't have Pull Request +#3+ _and_ Issue +#3+. -If you want to reference any Pull Request or Issue from any other one, you can simply put `+#+` in any comment or description. -You can also be more specific if the Issue or Pull request lives somewhere else; write `username#` if you're referring to an Issue or Pull Request in a fork of the repository you're in, or `username/repo#` to reference something in another repository. +Vamos começar com como fazer referência cruzada a outro Pull Request ou a uma Issue. +Todos os Pull Requests e Issues recebem números e eles são únicos dentro do projeto. +Por exemplo, você não pode ter o Pull Request +#3+ _e_ a Issue +#3+. +Se você quiser referenciar qualquer Pull Request ou Issue a partir de qualquer outro, você pode simplesmente colocar `+#+` em qualquer comentário ou descrição. +Você também pode ser mais específico se a Issue ou Pull Request estiver em outro lugar; escreva `username#` se estiver se referindo a uma Issue ou Pull Request em um fork do repositório em que você está, ou `username/repo#` para referenciar algo em outro repositório. -Let's look at an example. -Say we rebased the branch in the previous example, created a new pull request for it, and now we want to reference the old pull request from the new one. -We also want to reference an issue in the fork of the repository and an issue in a completely different project. -We can fill out the description just like <<_pr_references>>. +Vamos ver um exemplo. +Digamos que fizemos um rebase do branch no exemplo anterior, criamos um novo pull request para ele e agora queremos referenciar o pull request antigo a partir do novo. +Nós também queremos referenciar uma issue no fork do repositório e uma issue em um projeto completamente diferente. +Podemos preencher a descrição exatamente como em <<_pr_references>>. [[_pr_references]] -.Cross references in a Pull Request -image::images/mentions-01-syntax.png[Cross references in a Pull Request] +.Referências cruzadas em um Pull Request +image::images/mentions-01-syntax.png[Referências cruzadas em um Pull Request] -When we submit this pull request, we'll see all of that rendered like <<_pr_references_render>>. +Quando submetermos este pull request, veremos tudo isso renderizado como em <<_pr_references_render>>. [[_pr_references_render]] -.Cross references rendered in a Pull Request -image::images/mentions-02-render.png[Cross references rendered in a Pull Request] +.Referências cruzadas renderizadas em um Pull Request +image::images/mentions-02-render.png[Referências cruzadas renderizadas em um Pull Request] -Notice that the full GitHub URL we put in there was shortened to just the information needed. +Observe que a URL completa do GitHub que colocamos lá foi encurtada apenas para as informações necessárias. -Now if Tony goes back and closes out the original Pull Request, we can see that by mentioning it in the new one, GitHub has automatically created a trackback event in the Pull Request timeline. -This means that anyone who visits this Pull Request and sees that it is closed can easily link back to the one that superseded it. -The link will look something like <<_pr_closed>>. +Agora, se Tony voltar e fechar o Pull Request original, podemos ver que, ao mencioná-lo no novo, o GitHub criou automaticamente um evento de trackback (rastreamento) na linha do tempo do Pull Request. +Isso significa que qualquer um que visite este Pull Request e veja que ele está fechado pode facilmente encontrar um link para aquele que o substituiu. +O link se parecerá com <<_pr_closed>>. [[_pr_closed]] -.Link back to the new Pull Request in the closed Pull Request timeline -image::images/mentions-03-closed.png[Link back to the new Pull Request in the closed Pull Request timeline] +.Link de volta para o novo Pull Request na linha do tempo do Pull Request fechado +image::images/mentions-03-closed.png[Link de volta para o novo Pull Request na linha do tempo do Pull Request fechado] -In addition to issue numbers, you can also reference a specific commit by SHA-1. -You have to specify a full 40 character SHA-1, but if GitHub sees that in a comment, it will link directly to the commit. -Again, you can reference commits in forks or other repositories in the same way you did with issues. +Além dos números de issue, você também pode referenciar um commit específico pelo seu SHA-1. +Você tem que especificar um SHA-1 completo de 40 caracteres, mas se o GitHub vir isso em um comentário, ele criará um link direto para o commit. +Novamente, você pode referenciar commits em forks ou outros repositórios da mesma forma que fez com issues. -==== GitHub Flavored Markdown +==== Markdown do GitHub (GitHub Flavored Markdown) -Linking to other Issues is just the beginning of interesting things you can do with almost any text box on GitHub. -In Issue and Pull Request descriptions, comments, code comments and more, you can use what is called "`GitHub Flavored Markdown`". -Markdown is like writing in plain text but which is rendered richly. +Vincular a outras Issues é apenas o começo de coisas interessantes que você pode fazer com quase qualquer caixa de texto no GitHub. +Em descrições de Issue e Pull Request, comentários, comentários de código e muito mais, você pode usar o que é chamado de "`GitHub Flavored Markdown`". +Markdown é como escrever em texto simples, mas que é renderizado com riqueza de detalhes. -See <<_example_markdown>> for an example of how comments or text can be written and then rendered using Markdown. +Veja <<_example_markdown>> para um exemplo de como os comentários ou textos podem ser escritos e depois renderizados usando Markdown. [[_example_markdown]] -.An example of GitHub Flavored Markdown as written and as rendered -image::images/markdown-01-example.png[An example of GitHub Flavored Markdown as written and as rendered] +.Um exemplo de GitHub Flavored Markdown como escrito e como renderizado +image::images/markdown-01-example.png[Um exemplo de GitHub Flavored Markdown como escrito e como renderizado] -The GitHub flavor of Markdown adds more things you can do beyond the basic Markdown syntax. -These can all be really useful when creating useful Pull Request or Issue comments or descriptions. +A variação de Markdown do GitHub adiciona mais coisas que você pode fazer além da sintaxe Markdown básica. +Tudo isso pode ser realmente útil ao criar comentários ou descrições úteis de Pull Request ou Issue. -===== Task Lists +===== Listas de Tarefas (Task Lists) -The first really useful GitHub specific Markdown feature, especially for use in Pull Requests, is the Task List. -A task list is a list of checkboxes of things you want to get done. -Putting them into an Issue or Pull Request normally indicates things that you want to get done before you consider the item complete. +A primeira funcionalidade Markdown realmente útil específica do GitHub, especialmente para uso em Pull Requests, é a Lista de Tarefas (Task List). +Uma lista de tarefas é uma lista de caixas de seleção de coisas que você deseja que sejam feitas. +Colocá-las em uma Issue ou Pull Request normalmente indica coisas que você deseja que sejam feitas antes de considerar o item completo. -You can create a task list like this: +Você pode criar uma lista de tarefas como esta: [source,text] ---- @@ -365,33 +365,33 @@ You can create a task list like this: - [ ] Document the code ---- -If we include this in the description of our Pull Request or Issue, we'll see it rendered like <<_eg_task_lists>>. +Se incluirmos isso na descrição do nosso Pull Request ou Issue, o veremos renderizado como em <<_eg_task_lists>>. [[_eg_task_lists]] -.Task lists rendered in a Markdown comment -image::images/markdown-02-tasks.png[Task lists rendered in a Markdown comment] +.Listas de tarefas renderizadas em um comentário Markdown +image::images/markdown-02-tasks.png[Listas de tarefas renderizadas em um comentário Markdown] -This is often used in Pull Requests to indicate what all you would like to get done on the branch before the Pull Request will be ready to merge. -The really cool part is that you can simply click the checkboxes to update the comment -- you don't have to edit the Markdown directly to check tasks off. +Isso é frequentemente usado em Pull Requests para indicar tudo o que você gostaria de ver feito no branch antes que o Pull Request esteja pronto para o merge. +A parte realmente legal é que você pode simplesmente clicar nas caixas de seleção para atualizar o comentário -- você não precisa editar o Markdown diretamente para marcar as tarefas como concluídas. -What's more, GitHub will look for task lists in your Issues and Pull Requests and show them as metadata on the pages that list them out. -For example, if you have a Pull Request with tasks and you look at the overview page of all Pull Requests, you can see how far done it is. -This helps people break down Pull Requests into subtasks and helps other people track the progress of the branch. -You can see an example of this in <<_task_list_progress>>. +Além do mais, o GitHub procurará por listas de tarefas em suas Issues e Pull Requests e as mostrará como metadados nas páginas que os listam. +Por exemplo, se você tem um Pull Request com tarefas e olha na página de visão geral de todos os Pull Requests, pode ver o quanto ele está concluído. +Isso ajuda as pessoas a dividirem Pull Requests em subtarefas e ajuda outras pessoas a acompanhar o progresso do branch. +Você pode ver um exemplo disso em <<_task_list_progress>>. [[_task_list_progress]] -.Task list summary in the Pull Request list -image::images/markdown-03-task-summary.png[Task list summary in the Pull Request list] +.Resumo da lista de tarefas na lista de Pull Request +image::images/markdown-03-task-summary.png[Resumo da lista de tarefas na lista de Pull Request] -These are incredibly useful when you open a Pull Request early and use it to track your progress through the implementation of the feature. +Elas são incrivelmente úteis quando você abre um Pull Request logo no início e o usa para rastrear o seu progresso através da implementação do recurso. -===== Code Snippets +===== Trechos de Código (Code Snippets) -You can also add code snippets to comments. -This is especially useful if you want to present something that you _could_ try to do before actually implementing it as a commit on your branch. -This is also often used to add example code of what is not working or what this Pull Request could implement. +Você também pode adicionar trechos de código (code snippets) aos comentários. +Isso é especialmente útil se você quiser apresentar algo que você _poderia_ tentar fazer antes de realmente implementá-lo como um commit no seu branch. +Isso também é usado com frequência para adicionar código de exemplo do que não está funcionando ou o que este Pull Request poderia implementar. -To add a snippet of code you have to "`fence`" it in backticks. +Para adicionar um trecho de código você tem que "`cercá-lo`" (fence) com crases. [source,text] ---- @@ -403,20 +403,20 @@ for(int i=0 ; i < 5 ; i++) ``` ---- -If you add a language name like we did there with 'java', GitHub will also try to syntax highlight the snippet. -In the case of the above example, it would end up rendering like <<_md_code>>. +Se você adicionar um nome de linguagem como fizemos ali com 'java', o GitHub também tentará destacar a sintaxe do trecho. +No caso do exemplo acima, ele acabaria renderizando como em <<_md_code>>. [[_md_code]] -.Rendered fenced code example -image::images/markdown-04-fenced-code.png[Rendered fenced code example] +.Exemplo de código cercado renderizado +image::images/markdown-04-fenced-code.png[Exemplo de código cercado renderizado] -===== Quoting +===== Citando (Quoting) -If you're responding to a small part of a long comment, you can selectively quote out of the other comment by preceding the lines with the `>` character. -In fact, this is so common and so useful that there is a keyboard shortcut for it. -If you highlight text in a comment that you want to directly reply to and hit the `r` key, it will quote that text in the comment box for you. +Se você estiver respondendo a uma pequena parte de um comentário longo, você pode citar seletivamente do outro comentário precedendo as linhas com o caractere `>`. +De fato, isso é tão comum e tão útil que existe um atalho de teclado para isso. +Se você destacar texto em um comentário ao qual deseja responder diretamente e pressionar a tecla `r`, ele citará esse texto na caixa de comentário para você. -The quotes look something like this: +As citações se parecem mais ou menos assim: [source,text] ---- @@ -426,25 +426,25 @@ The quotes look something like this: How big are these slings and in particular, these arrows? ---- -Once rendered, the comment will look like <<_md_quote>>. +Uma vez renderizado, o comentário se parecerá com <<_md_quote>>. [[_md_quote]] -.Rendered quoting example -image::images/markdown-05-quote.png[Rendered quoting example] +.Exemplo de citação renderizado +image::images/markdown-05-quote.png[Exemplo de citação renderizado] ===== Emoji -Finally, you can also use emoji in your comments. -This is actually used quite extensively in comments you see on many GitHub Issues and Pull Requests. -There is even an emoji helper in GitHub. -If you are typing a comment and you start with a `:` character, an autocompleter will help you find what you're looking for. +Finalmente, você também pode usar emoji em seus comentários. +Isso é, na verdade, usado extensivamente em comentários que você vê em muitas Issues e Pull Requests no GitHub. +Há até mesmo um assistente de emoji no GitHub. +Se você estiver digitando um comentário e começar com um caractere `:`, um recurso de autocompletar ajudará a encontrar o que você está procurando. [[_md_emoji_auto]] -.Emoji autocompleter in action -image::images/markdown-06-emoji-complete.png[Emoji autocompleter in action] +.Recurso de autocompletar emoji em ação +image::images/markdown-06-emoji-complete.png[Recurso de autocompletar emoji em ação] -Emojis take the form of `::` anywhere in the comment. -For instance, you could write something like this: +Os emojis assumem a forma de `::` em qualquer lugar no comentário. +Por exemplo, você poderia escrever algo assim: [source,text] ---- @@ -457,50 +457,50 @@ I :eyes: that :bug: and I :cold_sweat:. :clap::tada::panda_face: ---- -When rendered, it would look something like <<_md_emoji>>. +Quando renderizado, ficaria parecido com <<_md_emoji>>. [[_md_emoji]] -.Heavy emoji commenting -image::images/markdown-07-emoji.png[Heavy emoji commenting] +.Comentários repletos de emoji +image::images/markdown-07-emoji.png[Comentários repletos de emoji] -Not that this is incredibly useful, but it does add an element of fun and emotion to a medium that is otherwise hard to convey emotion in. +Não que isso seja incrivelmente útil, mas adiciona um elemento de diversão e emoção a um meio no qual, de outra forma, é difícil transmitir emoção. [NOTE] ==== -There are actually quite a number of web services that make use of emoji characters these days. -A great cheat sheet to reference to find emoji that expresses what you want to say can be found at: +Na verdade, há um bom número de serviços da web que fazem uso de caracteres emoji hoje em dia. +Um ótimo guia de referência (cheat sheet) para encontrar o emoji que expressa o que você quer dizer pode ser encontrado em: https://www.webfx.com/tools/emoji-cheat-sheet/[^] ==== -===== Images +===== Imagens -This isn't technically GitHub Flavored Markdown, but it is incredibly useful. -In addition to adding Markdown image links to comments, which can be difficult to find and embed URLs for, GitHub allows you to drag and drop images into text areas to embed them. +Isso não é tecnicamente GitHub Flavored Markdown, mas é incrivelmente útil. +Além de adicionar links de imagens Markdown aos comentários, que podem ser difíceis de encontrar e incorporar URLs, o GitHub permite que você arraste e solte imagens em áreas de texto para incorporá-las. [[_md_drag]] -.Drag and drop images to upload them and auto-embed them -image::images/markdown-08-drag-drop.png[Drag and drop images to upload them and auto-embed them] +.Arraste e solte imagens para carregá-las e incorporá-las automaticamente +image::images/markdown-08-drag-drop.png[Arraste e solte imagens para carregá-las e incorporá-las automaticamente] -If you look at <<_md_drag>>, you can see a small "`Parsed as Markdown`" hint above the text area. -Clicking on that will give you a full cheat sheet of everything you can do with Markdown on GitHub. +Se você olhar para <<_md_drag>>, poderá ver uma pequena dica "`Parsed as Markdown`" (Analisado como Markdown) acima da área de texto. +Clicar nela lhe dará um guia de referência completo de tudo o que você pode fazer com Markdown no GitHub. [[_fetch_and_push_on_different_repositories]] -==== Keep your GitHub public repository up-to-date +==== Mantenha o seu repositório público do GitHub atualizado -Once you've forked a GitHub repository, your repository (your "fork") exists independently from the original. -In particular, when the original repository has new commits, GitHub informs you by a message like: +Depois que você faz o fork de um repositório no GitHub, o seu repositório (o seu "fork") existe independentemente do original. +Em particular, quando o repositório original tiver novos commits, o GitHub o informará com uma mensagem como: [source,text] ---- This branch is 5 commits behind progit:master. ---- -But your GitHub repository will never be automatically updated by GitHub; this is something that you must do yourself. -Fortunately, this is very easy to do. +Mas o seu repositório no GitHub nunca será atualizado automaticamente pelo GitHub; isso é algo que você mesmo deve fazer. +Felizmente, isso é muito fácil de fazer. -One possibility to do this requires no configuration. -For example, if you forked from `https://github.com/progit/progit2.git`, you can keep your `master` branch up-to-date like this: +Uma possibilidade para fazer isso não requer configuração. +Por exemplo, se você fez fork de `https://github.com/progit/progit2.git`, você pode manter o seu branch `master` atualizado desta forma: [source,console] ---- @@ -509,12 +509,12 @@ $ git pull https://github.com/progit/progit2.git <2> $ git push origin master <3> ---- -<1> If you were on another branch, return to `master`. -<2> Fetch changes from `https://github.com/progit/progit2.git` and merge them into `master`. -<3> Push your `master` branch to `origin`. +<1> Se você estava em outro branch, retorne ao `master`. +<2> Faça um fetch das alterações de `https://github.com/progit/progit2.git` e as mescle no `master`. +<3> Faça o push do seu branch `master` para a `origin`. -This works, but it is a little tedious having to spell out the fetch URL every time. -You can automate this work with a bit of configuration: +Isso funciona, mas é um pouco entediante ter que soletrar a URL do fetch todas as vezes. +Você pode automatizar esse trabalho com um pouco de configuração: [source,console] ---- @@ -524,13 +524,13 @@ $ git branch --set-upstream-to=progit/master master <3> $ git config --local remote.pushDefault origin <4> ---- -<1> Add the source repository and give it a name. - Here, I have chosen to call it `progit`. -<2> Get a reference on progit's branches, in particular `master`. -<3> Set your `master` branch to fetch from the `progit` remote. -<4> Define the default push repository to `origin`. +<1> Adicione o repositório de origem e dê um nome a ele. + Aqui, escolhi chamá-lo de `progit`. +<2> Obtenha uma referência aos branches do progit, em particular ao `master`. +<3> Configure o seu branch `master` para fazer fetch do remoto `progit`. +<4> Defina o repositório padrão de push para `origin`. -Once this is done, the workflow becomes much simpler: +Uma vez feito isso, o fluxo de trabalho se torna muito mais simples: [source,console] ---- @@ -539,10 +539,10 @@ $ git pull <2> $ git push <3> ---- -<1> If you were on another branch, return to `master`. -<2> Fetch changes from `progit` and merge changes into `master`. -<3> Push your `master` branch to `origin`. +<1> Se você estava em outro branch, retorne ao `master`. +<2> Faça um fetch das alterações do `progit` e mescle as alterações no `master`. +<3> Faça o push do seu branch `master` para a `origin`. -This approach can be useful, but it's not without downsides. -Git will happily do this work for you silently, but it won't warn you if you make a commit to `master`, pull from `progit`, then push to `origin` -- all of those operations are valid with this setup. -So you'll have to take care never to commit directly to `master`, since that branch effectively belongs to the upstream repository. +Essa abordagem pode ser útil, mas não deixa de ter desvantagens. +O Git ficará feliz em fazer esse trabalho para você silenciosamente, mas não o avisará se você fizer um commit no `master`, fizer um pull de `progit` e depois fizer um push para `origin` -- todas essas operações são válidas com esta configuração. +Então, você terá que tomar cuidado para nunca comitar diretamente no `master`, já que esse branch pertence efetivamente ao repositório upstream. diff --git a/book/06-github/sections/3-maintaining.asc b/book/06-github/sections/3-maintaining.asc index 2505e86a..bfad1586 100644 --- a/book/06-github/sections/3-maintaining.asc +++ b/book/06-github/sections/3-maintaining.asc @@ -1,134 +1,134 @@ [[_maintaining_gh_project]] -=== Maintaining a Project +=== Mantendo um Projeto -Now that we're comfortable contributing to a project, let's look at the other side: creating, maintaining and administering your own project. +Agora que nos sentimos confortáveis contribuindo com um projeto, vamos olhar para o outro lado: criar, manter e administrar o seu próprio projeto. -==== Creating a New Repository +==== Criando um Novo Repositório -Let's create a new repository to share our project code with. -Start by clicking the "`New repository`" button on the right-hand side of the dashboard, or from the `+` button in the top toolbar next to your username as seen in <<_new_repo_dropdown>>. +Vamos criar um novo repositório para compartilhar o código do nosso projeto. +Comece clicando no botão "`New repository`" (Novo repositório) no lado direito do painel, ou a partir do botão `+` na barra de ferramentas superior ao lado do seu nome de usuário, como visto em <<_new_repo_dropdown>>. -.The "`Your repositories`" area -image::images/newrepo.png[The “Your repositories” area] +.A área "`Your repositories`" +image::images/newrepo.png[A área "Your repositories"] [[_new_repo_dropdown]] -.The "`New repository`" dropdown -image::images/new-repo.png[The “New repository” dropdown] +.O menu suspenso "`New repository`" +image::images/new-repo.png[O menu suspenso "New repository"] -This takes you to the "`new repository`" form: +Isso leva você ao formulário "`new repository`" (novo repositório): -.The "`new repository`" form -image::images/newrepoform.png[The “new repository” form] +.O formulário "`new repository`" +image::images/newrepoform.png[O formulário "new repository"] -All you really have to do here is provide a project name; the rest of the fields are completely optional. -For now, just click the "`Create Repository`" button, and boom -- you have a new repository on GitHub, named `/`. +Tudo o que você realmente precisa fazer aqui é fornecer o nome de um projeto; o restante dos campos é totalmente opcional. +Por enquanto, basta clicar no botão "`Create Repository`" (Criar Repositório), e bum -- você tem um novo repositório no GitHub, chamado `/`. -Since you have no code there yet, GitHub will show you instructions for how to create a brand-new Git repository, or connect an existing Git project. -We won't belabor this here; if you need a refresher, check out <>. +Como você ainda não tem nenhum código lá, o GitHub lhe mostrará instruções de como criar um repositório Git totalmente novo ou conectar um projeto Git existente. +Não vamos nos estender sobre isso aqui; se você precisar de uma atualização, verifique <>. -Now that your project is hosted on GitHub, you can give the URL to anyone you want to share your project with. -Every project on GitHub is accessible over HTTPS as `\https://github.com//`, and over SSH as `\git@github.com:/`. -Git can fetch from and push to both of these URLs, but they are access-controlled based on the credentials of the user connecting to them. +Agora que o seu projeto está hospedado no GitHub, você pode fornecer a URL a qualquer pessoa com quem queira compartilhar o seu projeto. +Todo projeto no GitHub é acessível via HTTPS em `\https://github.com//`, e via SSH em `\git@github.com:/`. +O Git pode fazer fetch de e push para ambas as URLs, mas elas têm controle de acesso com base nas credenciais do usuário que se conecta a elas. [NOTE] ==== -It is often preferable to share the HTTPS based URL for a public project, since the user does not have to have a GitHub account to access it for cloning. -Users will have to have an account and an uploaded SSH key to access your project if you give them the SSH URL. -The HTTPS one is also exactly the same URL they would paste into a browser to view the project there. +Muitas vezes é preferível compartilhar a URL baseada em HTTPS para um projeto público, já que o usuário não precisa ter uma conta no GitHub para acessá-lo para clonagem. +Os usuários terão que ter uma conta e uma chave SSH carregada para acessar o seu projeto se você lhes der a URL SSH. +A versão em HTTPS também é exatamente a mesma URL que eles colariam em um navegador para ver o projeto lá. ==== -==== Adding Collaborators +==== Adicionando Colaboradores -If you're working with other people who you want to give commit access to, you need to add them as "`collaborators`". -If Ben, Jeff, and Louise all sign up for accounts on GitHub, and you want to give them push access to your repository, you can add them to your project. -Doing so will give them "`push`" access, which means they have both read and write access to the project and Git repository. +Se você estiver trabalhando com outras pessoas a quem deseja dar acesso de commit, você precisará adicioná-las como "`collaborators`" (colaboradores). +Se Ben, Jeff e Louise se inscreverem para contas no GitHub, e você quiser dar a eles acesso de push ao seu repositório, você pode adicioná-los ao seu projeto. +Ao fazer isso, você dará a eles acesso de "`push`", o que significa que eles terão acesso tanto de leitura quanto de gravação ao projeto e ao repositório Git. -Click the "`Settings`" link at the bottom of the right-hand sidebar. +Clique no link "`Settings`" (Configurações) na parte inferior da barra lateral direita. -.The repository settings link -image::images/reposettingslink.png[The repository settings link] +.O link de configurações do repositório +image::images/reposettingslink.png[O link de configurações do repositório] -Then select "`Collaborators`" from the menu on the left-hand side. -Then, just type a username into the box, and click "`Add collaborator.`" -You can repeat this as many times as you like to grant access to everyone you like. -If you need to revoke access, just click the "`X`" on the right-hand side of their row. +Em seguida, selecione "`Collaborators`" (Colaboradores) no menu do lado esquerdo. +Em seguida, basta digitar um nome de usuário na caixa e clicar em "`Add collaborator`" (Adicionar colaborador). +Você pode repetir isso quantas vezes quiser para conceder acesso a todos que desejar. +Se precisar revogar o acesso, basta clicar no "`X`" no lado direito da linha deles. -.The repository collaborators box -image::images/collaborators.png[The repository collaborators box] +.A caixa de colaboradores do repositório +image::images/collaborators.png[A caixa de colaboradores do repositório] -==== Managing Pull Requests +==== Gerenciando Pull Requests -Now that you have a project with some code in it and maybe even a few collaborators who also have push access, let's go over what to do when you get a Pull Request yourself. +Agora que você tem um projeto com algum código nele e talvez até mesmo alguns colaboradores que também têm acesso de push, vamos ver o que fazer quando você mesmo receber um Pull Request. -Pull Requests can either come from a branch in a fork of your repository or they can come from another branch in the same repository. -The only difference is that the ones in a fork are often from people where you can't push to their branch and they can't push to yours, whereas with internal Pull Requests generally both parties can access the branch. +Os Pull Requests podem vir de um branch em um fork do seu repositório ou podem vir de outro branch no mesmo repositório. +A única diferença é que os que estão em um fork costumam ser de pessoas onde você não pode fazer push para o branch delas e elas não podem fazer push para o seu, enquanto em Pull Requests internos, geralmente, ambas as partes podem acessar o branch. -For these examples, let's assume you are "`tonychacon`" and you've created a new Arduino code project named "`fade`". +Para estes exemplos, vamos assumir que você seja "`tonychacon`" e tenha criado um novo projeto de código Arduino chamado "`fade`". [[_email_notifications]] -===== Email Notifications +===== Notificações por E-mail -Someone comes along and makes a change to your code and sends you a Pull Request. -You should get an email notifying you about the new Pull Request and it should look something like <<_email_pr>>. +Alguém chega, faz uma alteração no seu código e lhe envia um Pull Request. +Você deve receber um e-mail notificando-o sobre o novo Pull Request e ele deve se parecer com <<_email_pr>>. [[_email_pr]] -.Email notification of a new Pull Request -image::images/maint-01-email.png[Email notification of a new Pull Request] +.Notificação por e-mail de um novo Pull Request +image::images/maint-01-email.png[Notificação por e-mail de um novo Pull Request] -There are a few things to notice about this email. -It will give you a small diffstat -- a list of files that have changed in the Pull Request and by how much. -It gives you a link to the Pull Request on GitHub. -It also gives you a few URLs that you can use from the command line. +Existem algumas coisas a serem notadas sobre este e-mail. +Ele lhe dará um pequeno diffstat -- uma lista de arquivos que foram alterados no Pull Request e em que quantidade. +Ele lhe dá um link para o Pull Request no GitHub. +Ele também lhe dá algumas URLs que você pode usar a partir da linha de comando. -If you notice the line that says `git pull patch-1`, this is a simple way to merge in a remote branch without having to add a remote. -We went over this quickly in <>. -If you wish, you can create and switch to a topic branch and then run this command to merge in the Pull Request changes. +Se você notar a linha que diz `git pull patch-1`, esta é uma forma simples de mesclar (merge) um branch remoto sem ter que adicionar um remoto. +Nós analisamos isso rapidamente em <>. +Se desejar, você pode criar e mudar para um branch de tópico e, em seguida, executar este comando para mesclar as alterações do Pull Request. -The other interesting URLs are the `.diff` and `.patch` URLs, which as you may guess, provide unified diff and patch versions of the Pull Request. -You could technically merge in the Pull Request work with something like this: +As outras URLs interessantes são as URLs `.diff` e `.patch`, que, como você pode adivinhar, fornecem versões diff unificadas e patch do Pull Request. +Você poderia tecnicamente mesclar o trabalho do Pull Request com algo como isto: [source,console] ---- $ curl https://github.com/tonychacon/fade/pull/1.patch | git am ---- -===== Collaborating on the Pull Request +===== Colaborando no Pull Request -As we covered in <>, you can now have a conversation with the person who opened the Pull Request. -You can comment on specific lines of code, comment on whole commits or comment on the entire Pull Request itself, using GitHub Flavored Markdown everywhere. +Como abordamos em <>, agora você pode ter uma conversa com a pessoa que abriu o Pull Request. +Você pode comentar em linhas de código específicas, comentar em commits inteiros ou comentar no Pull Request inteiro em si, usando o GitHub Flavored Markdown em toda parte. -Every time someone else comments on the Pull Request you will continue to get email notifications so you know there is activity happening. -They will each have a link to the Pull Request where the activity is happening and you can also directly respond to the email to comment on the Pull Request thread. +Toda vez que alguém comenta no Pull Request, você continuará a receber notificações por e-mail, para saber que há atividade acontecendo. +Cada um deles terá um link para o Pull Request onde a atividade está acontecendo e você também pode responder diretamente ao e-mail para comentar na thread do Pull Request. -.Responses to emails are included in the thread -image::images/maint-03-email-resp.png[Responses to emails are included in the thread] +.Respostas a e-mails são incluídas na thread +image::images/maint-03-email-resp.png[Respostas a e-mails são incluídas na thread] -Once the code is in a place you like and want to merge it in, you can either pull the code down and merge it locally, either with the `git pull ` syntax we saw earlier, or by adding the fork as a remote and fetching and merging. +Uma vez que o código esteja de uma forma que você goste e queira mesclá-lo, você pode fazer o pull do código e mesclá-lo localmente, seja com a sintaxe `git pull ` que vimos anteriormente, ou adicionando o fork como um remoto e fazendo fetch e merge. -If the merge is trivial, you can also just hit the "`Merge`" button on the GitHub site. -This will do a "`non-fast-forward`" merge, creating a merge commit even if a fast-forward merge was possible. -This means that no matter what, every time you hit the merge button, a merge commit is created. -As you can see in <<_merge_button>>, GitHub gives you all of this information if you click the hint link. +Se o merge for trivial, você também pode simplesmente clicar no botão "`Merge`" no site do GitHub. +Isso fará um merge "`non-fast-forward`", criando um commit de merge mesmo que um merge fast-forward fosse possível. +Isso significa que, aconteça o que acontecer, toda vez que você clica no botão de merge, um commit de merge é criado. +Como você pode ver em <<_merge_button>>, o GitHub lhe dá todas essas informações se você clicar no link de dica. [[_merge_button]] -.Merge button and instructions for merging a Pull Request manually -image::images/maint-02-merge.png[Merge button and instructions for merging a Pull Request manually] +.Botão Merge e instruções para fazer o merge de um Pull Request manualmente +image::images/maint-02-merge.png[Botão Merge e instruções para fazer o merge de um Pull Request manualmente] -If you decide you don't want to merge it, you can also just close the Pull Request and the person who opened it will be notified. +Se você decidir que não quer mesclá-lo, você também pode simplesmente fechar o Pull Request e a pessoa que o abriu será notificada. [[_pr_refs]] -===== Pull Request Refs +===== Refs de Pull Request -If you're dealing with a *lot* of Pull Requests and don't want to add a bunch of remotes or do one time pulls every time, there is a neat trick that GitHub allows you to do. -This is a bit of an advanced trick and we'll go over the details of this a bit more in <>, but it can be pretty useful. +Se você estiver lidando com um *monte* de Pull Requests e não quiser adicionar um monte de remotos ou fazer pulls pontuais toda vez, há um truque bacana que o GitHub permite que você faça. +Este é um truque um pouco avançado e vamos analisar os detalhes disso um pouco mais em <>, mas ele pode ser bastante útil. -GitHub actually advertises the Pull Request branches for a repository as sort of pseudo-branches on the server. -By default you don't get them when you clone, but they are there in an obscured way and you can access them pretty easily. +Na verdade, o GitHub anuncia (advertises) os branches de Pull Request de um repositório como uma espécie de pseudo-branches no servidor. +Por padrão, você não os obtém quando clona, mas eles estão lá de forma obscura e você pode acessá-los com bastante facilidade. -To demonstrate this, we're going to use a low-level command (often referred to as a "`plumbing`" command, which we'll read about more in <>) called `ls-remote`. -This command is generally not used in day-to-day Git operations but it's useful to show us what references are present on the server. +Para demonstrar isso, usaremos um comando de baixo nível (frequentemente referido como um comando de "`plumbing`" ou encanamento, sobre o qual leremos mais em <>) chamado `ls-remote`. +Esse comando geralmente não é usado em operações do dia a dia no Git, mas é útil para nos mostrar quais referências estão presentes no servidor. -If we run this command against the "`blink`" repository we were using earlier, we will get a list of all the branches and tags and other references in the repository. +Se executarmos esse comando no repositório "`blink`" que estávamos usando antes, obteremos uma lista de todos os branches, tags e outras referências no repositório. [source,console] ---- @@ -143,16 +143,16 @@ a5a7751a33b7e86c5e9bb07b26001bb17d775d1a refs/pull/4/head 31a45fc257e8433c8d8804e3e848cf61c9d3166c refs/pull/4/merge ---- -Of course, if you're in your repository and you run `git ls-remote origin` or whatever remote you want to check, it will show you something similar to this. +É claro, se você estiver em seu repositório e executar `git ls-remote origin` ou qualquer remoto que deseje verificar, ele mostrará algo semelhante a isso. -If the repository is on GitHub and you have any Pull Requests that have been opened, you'll get these references that are prefixed with `refs/pull/`. -These are basically branches, but since they're not under `refs/heads/` you don't get them normally when you clone or fetch from the server -- the process of fetching ignores them normally. +Se o repositório estiver no GitHub e você tiver Pull Requests abertos, você obterá essas referências prefixadas com `refs/pull/`. +Estas são basicamente branches, mas como elas não estão sob `refs/heads/`, você normalmente não as obtém ao clonar ou fazer fetch do servidor -- o processo de fetch normalmente as ignora. -There are two references per Pull Request - the one that ends in `/head` points to exactly the same commit as the last commit in the Pull Request branch. -So if someone opens a Pull Request in our repository and their branch is named `bug-fix` and it points to commit `a5a775`, then in *our* repository we will not have a `bug-fix` branch (since that's in their fork), but we _will_ have `pull//head` that points to `a5a775`. -This means that we can pretty easily pull down every Pull Request branch in one go without having to add a bunch of remotes. +Existem duas referências por Pull Request - a que termina em `/head` aponta exatamente para o mesmo commit que o último commit no branch do Pull Request. +Então, se alguém abrir um Pull Request no nosso repositório e seu branch for nomeado `bug-fix` apontando para o commit `a5a775`, em *nosso* repositório não teremos um branch `bug-fix` (já que está no fork deles), mas _teremos_ `pull//head` apontando para `a5a775`. +Isso significa que podemos muito facilmente baixar todo branch de Pull Request de uma só vez sem ter que adicionar um monte de remotos. -Now, you could do something like fetching the reference directly. +Agora, você poderia fazer algo como o fetch da referência diretamente. [source,console] ---- @@ -161,14 +161,14 @@ From https://github.com/libgit2/libgit2 * branch refs/pull/958/head -> FETCH_HEAD ---- -This tells Git, "`Connect to the `origin` remote, and download the ref named `refs/pull/958/head`.`" -Git happily obeys, and downloads everything you need to construct that ref, and puts a pointer to the commit you want under `.git/FETCH_HEAD`. -You can follow that up with `git merge FETCH_HEAD` into a branch you want to test it in, but that merge commit message looks a bit weird. -Also, if you're reviewing a *lot* of pull requests, this gets tedious. +Isto diz ao Git: "`Conecte-se ao remoto `origin` e baixe o ref chamado `refs/pull/958/head`.`" +O Git obedece de bom grado e baixa tudo o que você precisa para construir esse ref, e coloca um ponteiro para o commit que você deseja sob `.git/FETCH_HEAD`. +Você pode seguir isso com `git merge FETCH_HEAD` no branch onde deseja testar a alteração, mas a mensagem do commit de merge parecerá um pouco estranha. +Além disso, se você estiver revisando um *monte* de pull requests, isso se torna entediante. -There's also a way to fetch _all_ of the pull requests, and keep them up to date whenever you connect to the remote. -Open up `.git/config` in your favorite editor, and look for the `origin` remote. -It should look a bit like this: +Há também uma forma de fazer fetch de _todos_ os pull requests e mantê-los atualizados sempre que você se conectar ao remoto. +Abra o `.git/config` em seu editor favorito e procure pelo remoto `origin`. +Deve se parecer um pouco com isto: [source,ini] ---- @@ -177,10 +177,10 @@ It should look a bit like this: fetch = +refs/heads/*:refs/remotes/origin/* ---- -That line that begins with `fetch =` is a "`refspec.`" -It's a way of mapping names on the remote with names in your local `.git` directory. -This particular one tells Git, "the things on the remote that are under `refs/heads` should go in my local repository under `refs/remotes/origin`." -You can modify this section to add another refspec: +A linha que começa com `fetch =` é um "`refspec`". +É uma forma de mapear nomes no remoto com nomes no seu diretório `.git` local. +Esse em particular diz ao Git: "as coisas no remoto que estão sob `refs/heads` devem ir para o meu repositório local sob `refs/remotes/origin`." +Você pode modificar esta seção para adicionar outro refspec: [source,ini] ---- @@ -190,8 +190,8 @@ You can modify this section to add another refspec: fetch = +refs/pull/*/head:refs/remotes/origin/pr/* ---- -That last line tells Git, "`All the refs that look like `refs/pull/123/head` should be stored locally like `refs/remotes/origin/pr/123`.`" -Now, if you save that file, and do a `git fetch`: +Essa última linha diz ao Git: "`Todos os refs que se parecem com `refs/pull/123/head` devem ser armazenados localmente como `refs/remotes/origin/pr/123`.`" +Agora, se você salvar esse arquivo e fizer um `git fetch`: [source,console] ---- @@ -203,8 +203,8 @@ $ git fetch # … ---- -Now all of the remote pull requests are represented locally with refs that act much like tracking branches; they're read-only, and they update when you do a fetch. -This makes it super easy to try the code from a pull request locally: +Agora, todos os pull requests remotos são representados localmente com refs que atuam de forma muito parecida com as branches de rastreamento (tracking branches); eles são somente leitura e são atualizados quando você faz um fetch. +Isso torna super fácil testar o código de um pull request localmente: [source,console] ---- @@ -214,85 +214,85 @@ Branch pr/2 set up to track remote branch pr/2 from origin. Switched to a new branch 'pr/2' ---- -The eagle-eyed among you would note the `head` on the end of the remote portion of the refspec. -There's also a `refs/pull/#/merge` ref on the GitHub side, which represents the commit that would result if you push the "`merge`" button on the site. -This can allow you to test the merge before even hitting the button. +Os mais observadores entre vocês devem ter notado o `head` no final da porção remota do refspec. +Há também um ref `refs/pull/#/merge` no lado do GitHub, que representa o commit que resultaria se você clicasse no botão "`merge`" no site. +Isso pode permitir que você teste o merge antes mesmo de apertar o botão. -===== Pull Requests on Pull Requests +===== Pull Requests de Pull Requests -Not only can you open Pull Requests that target the main or `master` branch, you can actually open a Pull Request targeting any branch in the network. -In fact, you can even target another Pull Request. +Você não apenas pode abrir Pull Requests que visam o branch principal ou `master`, como na verdade pode abrir um Pull Request visando qualquer branch na rede. +De fato, você pode até mesmo visar outro Pull Request. -If you see a Pull Request that is moving in the right direction and you have an idea for a change that depends on it or you're not sure is a good idea, or you just don't have push access to the target branch, you can open a Pull Request directly to it. +Se você vir um Pull Request que está indo na direção certa e tiver uma ideia para uma alteração que dependa dele ou sobre a qual não tenha certeza se é uma boa ideia, ou simplesmente não tiver acesso de push ao branch de destino, você pode abrir um Pull Request diretamente para ele. -When you go to open a Pull Request, there is a box at the top of the page that specifies which branch you're requesting to pull to and which you're requesting to pull from. -If you hit the "`Edit`" button at the right of that box you can change not only the branches but also which fork. +Quando você vai abrir um Pull Request, há uma caixa na parte superior da página que especifica de qual branch você está solicitando fazer o pull e para qual branch você está solicitando fazer o pull. +Se você clicar no botão "`Edit`" (Editar) à direita dessa caixa, poderá alterar não apenas os branches, mas também de qual fork. [[_pr_targets]] -.Manually change the Pull Request target fork and branch -image::images/maint-04-target.png[Manually change the Pull Request target fork and branch] +.Altere manualmente o fork e o branch de destino do Pull Request +image::images/maint-04-target.png[Altere manualmente o fork e o branch de destino do Pull Request] -Here you can fairly easily specify to merge your new branch into another Pull Request or another fork of the project. +Aqui, você pode facilmente especificar o merge do seu novo branch em outro Pull Request ou outro fork do projeto. -==== Mentions and Notifications +==== Menções e Notificações -GitHub also has a pretty nice notifications system built in that can come in handy when you have questions or need feedback from specific individuals or teams. +O GitHub também possui um sistema de notificações embutido muito bom que pode ser útil quando você tem dúvidas ou precisa de feedback de indivíduos ou equipes específicas. -In any comment you can start typing a `@` character and it will begin to autocomplete with the names and usernames of people who are collaborators or contributors in the project. +Em qualquer comentário, você pode começar a digitar um caractere `@` e ele começará a preencher automaticamente (autocomplete) com os nomes e nomes de usuário de pessoas que são colaboradoras ou contribuidoras do projeto. -.Start typing @ to mention someone -image::images/maint-05-mentions.png[Start typing @ to mention someone] +.Comece a digitar @ para mencionar alguém +image::images/maint-05-mentions.png[Comece a digitar @ para mencionar alguém] -You can also mention a user who is not in that dropdown, but often the autocompleter can make it faster. +Você também pode mencionar um usuário que não está nesse menu suspenso, mas muitas vezes o recurso de autocompletar pode torná-lo mais rápido. -Once you post a comment with a user mention, that user will be notified. -This means that this can be a really effective way of pulling people into conversations rather than making them poll. -Very often in Pull Requests on GitHub people will pull in other people on their teams or in their company to review an Issue or Pull Request. +Assim que você publicar um comentário com uma menção a um usuário, esse usuário será notificado. +Isso significa que essa pode ser uma forma realmente eficaz de puxar as pessoas para conversas em vez de fazê-las pesquisar (poll). +Com muita frequência, em Pull Requests no GitHub, as pessoas puxam outras pessoas de suas equipes ou de suas empresas para revisar uma Issue ou Pull Request. -If someone gets mentioned on a Pull Request or Issue, they will be "`subscribed`" to it and will continue getting notifications any time some activity occurs on it. -You will also be subscribed to something if you opened it, if you're watching the repository or if you comment on something. -If you no longer wish to receive notifications, there is an "`Unsubscribe`" button on the page you can click to stop receiving updates on it. +Se alguém for mencionado em um Pull Request ou Issue, ele será "`inscrito`" (subscribed) nele e continuará recebendo notificações sempre que alguma atividade ocorrer. +Você também será inscrito em algo se o abriu, se estiver observando (watching) o repositório ou se comentar sobre algo. +Se você não deseja mais receber notificações, há um botão "`Unsubscribe`" (Cancelar Inscrição) na página que você pode clicar para parar de receber atualizações sobre ele. -.Unsubscribe from an Issue or Pull Request -image::images/maint-06-unsubscribe.png[Unsubscribe from an Issue or Pull Request] +.Cancele a inscrição de uma Issue ou Pull Request +image::images/maint-06-unsubscribe.png[Cancele a inscrição de uma Issue ou Pull Request] -===== The Notifications Page +===== A Página de Notificações -When we mention "`notifications`" here with respect to GitHub, we mean a specific way that GitHub tries to get in touch with you when events happen and there are a few different ways you can configure them. -If you go to the "`Notification center`" tab from the settings page, you can see some of the options you have. +Quando mencionamos "`notificações`" aqui em relação ao GitHub, queremos dizer uma maneira específica que o GitHub tenta entrar em contato com você quando ocorrem eventos e há algumas maneiras diferentes de configurá-las. +Se você for para a guia "`Notification center`" (Centro de notificações) na página de configurações, poderá ver algumas das opções que você tem. -.Notification center options -image::images/maint-07-notifications.png[Notification center options] +.Opções do centro de notificações +image::images/maint-07-notifications.png[Opções do centro de notificações] -The two choices are to get notifications over "`Email`" and over "`Web`" and you can choose either, neither or both for when you actively participate in things and for activity on repositories you are watching. +As duas opções são receber notificações por "`Email`" e pela "`Web`" e você pode escolher uma, nenhuma ou ambas para quando participar ativamente de coisas e para atividades em repositórios que você está observando. -====== Web Notifications +====== Notificações na Web -Web notifications only exist on GitHub and you can only check them on GitHub. -If you have this option selected in your preferences and a notification is triggered for you, you will see a small blue dot over your notifications icon at the top of your screen as seen in <<_not_center>>. +Notificações na Web só existem no GitHub e você só pode verificá-las no GitHub. +Se você tiver essa opção selecionada em suas preferências e uma notificação for acionada para você, você verá um pequeno ponto azul sobre o ícone de notificações na parte superior da tela, como visto em <<_not_center>>. [[_not_center]] -.Notification center -image::images/maint-08-notifications-page.png[Notification center] +.Centro de notificações +image::images/maint-08-notifications-page.png[Centro de notificações] -If you click on that, you will see a list of all the items you have been notified about, grouped by project. -You can filter to the notifications of a specific project by clicking on its name in the left hand sidebar. -You can also acknowledge the notification by clicking the checkmark icon next to any notification, or acknowledge _all_ of the notifications in a project by clicking the checkmark at the top of the group. -There is also a mute button next to each checkmark that you can click to not receive any further notifications on that item. +Se você clicar nele, verá uma lista de todos os itens sobre os quais foi notificado, agrupados por projeto. +Você pode filtrar as notificações de um projeto específico clicando em seu nome na barra lateral esquerda. +Você também pode confirmar a leitura (acknowledge) da notificação clicando no ícone de marca de seleção ao lado de qualquer notificação, ou confirmar a leitura de _todas_ as notificações em um projeto clicando na marca de seleção na parte superior do grupo. +Há também um botão de silenciar (mute) ao lado de cada marca de seleção que você pode clicar para não receber mais notificações sobre aquele item. -All of these tools are very useful for handling large numbers of notifications. -Many GitHub power users will simply turn off email notifications entirely and manage all of their notifications through this screen. +Todas essas ferramentas são muito úteis para lidar com um grande número de notificações. +Muitos usuários avançados (power users) do GitHub simplesmente desligarão totalmente as notificações por e-mail e gerenciarão todas as suas notificações através desta tela. -====== Email Notifications +====== Notificações por E-mail -Email notifications are the other way you can handle notifications through GitHub. -If you have this turned on you will get emails for each notification. -We saw examples of this in <<_email_notification>> and <<_email_pr>>. -The emails will also be threaded properly, which is nice if you're using a threading email client. +Notificações por e-mail são a outra forma de lidar com notificações pelo GitHub. +Se você tiver isso ativado, receberá e-mails para cada notificação. +Vimos exemplos disso em <<_email_notification>> e <<_email_pr>>. +Os e-mails também serão agrupados em threads corretamente, o que é bom se você estiver usando um cliente de e-mail com suporte a threads. -There is also a fair amount of metadata embedded in the headers of the emails that GitHub sends you, which can be really helpful for setting up custom filters and rules. +Há também uma boa quantidade de metadados incorporados aos cabeçalhos dos e-mails que o GitHub lhe envia, o que pode ser muito útil para configurar filtros e regras personalizadas. -For instance, if we look at the actual email headers sent to Tony in the email shown in <<_email_pr>>, we will see the following among the information sent: +Por exemplo, se olharmos os cabeçalhos de e-mail reais enviados para Tony no e-mail mostrado em <<_email_pr>>, veremos as seguintes informações entre as enviadas: [source,mbox] ---- @@ -307,71 +307,71 @@ List-Unsubscribe: ,... X-GitHub-Recipient-Address: tchacon@example.com ---- -There are a couple of interesting things here. -If you want to highlight or re-route emails to this particular project or even Pull Request, the information in `Message-ID` gives you all the data in `///` format. -If this was an issue, for example, the `` field would have been "`issues`" rather than "`pull`". +Há algumas coisas interessantes aqui. +Se você quiser destacar ou redirecionar e-mails para este projeto ou mesmo Pull Request em particular, as informações em `Message-ID` lhe dão todos os dados no formato `///`. +Se isso fosse uma issue, por exemplo, o campo `` teria sido "`issues`" em vez de "`pull`". -The `List-Post` and `List-Unsubscribe` fields mean that if you have a mail client that understands those, you can easily post to the list or "`Unsubscribe`" from the thread. -That would be essentially the same as clicking the "`mute`" button on the web version of the notification or "`Unsubscribe`" on the Issue or Pull Request page itself. +Os campos `List-Post` e `List-Unsubscribe` significam que, se você tiver um cliente de e-mail que os compreenda, você pode postar facilmente na lista ou cancelar a inscrição ("`Unsubscribe`") na thread. +Isso seria essencialmente o mesmo que clicar no botão de silenciar ("`mute`") na versão web da notificação ou em "`Unsubscribe`" na própria página da Issue ou Pull Request. -It's also worth noting that if you have both email and web notifications enabled and you read the email version of the notification, the web version will be marked as read as well if you have images allowed in your mail client. +Também vale a pena notar que se você tiver ambas as notificações por e-mail e pela web ativadas e ler a versão por e-mail da notificação, a versão web também será marcada como lida se você tiver imagens permitidas em seu cliente de e-mail. -==== Special Files +==== Arquivos Especiais -There are a couple of special files that GitHub will notice if they are present in your repository. +Existem alguns arquivos especiais que o GitHub notará se estiverem presentes em seu repositório. ==== README -The first is the `README` file, which can be of nearly any format that GitHub recognizes as prose. -For example, it could be `README`, `README.md`, `README.asciidoc`, etc. -If GitHub sees a `README` file in your source, it will render it on the landing page of the project. +O primeiro é o arquivo `README`, que pode ser de quase qualquer formato que o GitHub reconheça como prosa. +Por exemplo, pode ser `README`, `README.md`, `README.asciidoc`, etc. +Se o GitHub vir um arquivo `README` no seu código-fonte, ele o renderizará na página de destino (landing page) do projeto. -Many teams use this file to hold all the relevant project information for someone who might be new to the repository or project. -This generally includes things like: +Muitas equipes usam este arquivo para armazenar todas as informações relevantes do projeto para alguém que possa ser novo no repositório ou projeto. +Geralmente, isso inclui coisas como: -* What the project is for -* How to configure and install it -* An example of how to use it or get it running -* The license that the project is offered under -* How to contribute to it +* Para que serve o projeto +* Como configurá-lo e instalá-lo +* Um exemplo de como usá-lo ou colocá-lo para rodar +* A licença sob a qual o projeto é oferecido +* Como contribuir com ele -Since GitHub will render this file, you can embed images or links in it for added ease of understanding. +Uma vez que o GitHub renderizará este arquivo, você pode incorporar imagens ou links nele para maior facilidade de compreensão. ==== CONTRIBUTING -The other special file that GitHub recognizes is the `CONTRIBUTING` file. -If you have a file named `CONTRIBUTING` with any file extension, GitHub will show <<_contrib_file>> when anyone starts opening a Pull Request. +O outro arquivo especial que o GitHub reconhece é o arquivo `CONTRIBUTING`. +Se você tiver um arquivo chamado `CONTRIBUTING` com qualquer extensão de arquivo, o GitHub mostrará <<_contrib_file>> quando alguém começar a abrir um Pull Request. [[_contrib_file]] -.Opening a Pull Request when a CONTRIBUTING file exists -image::images/maint-09-contrib.png[Opening a Pull Request when a CONTRIBUTING file exists] +.Abrindo um Pull Request quando existe um arquivo CONTRIBUTING +image::images/maint-09-contrib.png[Abrindo um Pull Request quando existe um arquivo CONTRIBUTING] -The idea here is that you can specify specific things you want or don't want in a Pull Request sent to your project. -This way people may actually read the guidelines before opening the Pull Request. +A ideia aqui é que você pode especificar coisas específicas que você quer ou não quer em um Pull Request enviado para o seu projeto. +Dessa forma, as pessoas podem de fato ler as diretrizes antes de abrirem o Pull Request. -==== Project Administration +==== Administração de Projeto -Generally there are not a lot of administrative things you can do with a single project, but there are a couple of items that might be of interest. +Geralmente não há muitas coisas administrativas que você possa fazer com um único projeto, mas há alguns itens que podem ser de interesse. -===== Changing the Default Branch +===== Mudando o Branch Padrão -If you are using a branch other than "`master`" as your default branch that you want people to open Pull Requests on or see by default, you can change that in your repository's settings page under the "`Options`" tab. +Se você estiver usando um branch diferente de "`master`" como seu branch padrão, no qual você quer que as pessoas abram Pull Requests ou vejam por padrão, você pode alterar isso na página de configurações do seu repositório, na guia "`Options`" (Opções). [[_default_branch]] -.Change the default branch for a project -image::images/maint-10-default-branch.png[Change the default branch for a project] +.Mude o branch padrão de um projeto +image::images/maint-10-default-branch.png[Mude o branch padrão de um projeto] -Simply change the default branch in the dropdown and that will be the default for all major operations from then on, including which branch is checked out by default when someone clones the repository. +Basta alterar o branch padrão no menu suspenso e ele será o padrão para todas as principais operações a partir de então, incluindo qual branch é feito o checkout por padrão quando alguém clona o repositório. -===== Transferring a Project +===== Transferindo um Projeto -If you would like to transfer a project to another user or an organization in GitHub, there is a "`Transfer ownership`" option at the bottom of the same "`Options`" tab of your repository settings page that allows you to do this. +Se você quiser transferir um projeto para outro usuário ou para uma organização no GitHub, há uma opção "`Transfer ownership`" (Transferir propriedade) na parte inferior da mesma guia "`Options`" (Opções) da página de configurações do seu repositório que permite fazer isso. [[_transfer_project]] -.Transfer a project to another GitHub user or Organization -image::images/maint-11-transfer.png[Transfer a project to another GitHub user or Organization] +.Transfira um projeto para outro usuário ou Organização do GitHub +image::images/maint-11-transfer.png[Transfira um projeto para outro usuário ou Organização do GitHub] -This is helpful if you are abandoning a project and someone wants to take it over, or if your project is getting bigger and want to move it into an organization. +Isso é útil se você estiver abandonando um projeto e alguém quiser assumi-lo, ou se o seu projeto estiver crescendo e você quiser movê-lo para uma organização. -Not only does this move the repository along with all its watchers and stars to another place, it also sets up a redirect from your URL to the new place. -It will also redirect clones and fetches from Git, not just web requests. +Isso não apenas move o repositório, juntamente com todos os seus observadores (watchers) e estrelas (stars), para outro lugar, mas também configura um redirecionamento da sua URL para o novo lugar. +Ele também redirecionará clones e fetches do Git, não apenas solicitações da web. diff --git a/book/06-github/sections/4-managing-organization.asc b/book/06-github/sections/4-managing-organization.asc index cdb2447a..63319575 100644 --- a/book/06-github/sections/4-managing-organization.asc +++ b/book/06-github/sections/4-managing-organization.asc @@ -1,72 +1,72 @@ [[ch06-github_orgs]] -=== Managing an organization +=== Gerenciando uma Organização (((GitHub, organizations))) -In addition to single-user accounts, GitHub has what are called Organizations. -Like personal accounts, Organizational accounts have a namespace where all their projects exist, but many other things are different. -These accounts represent a group of people with shared ownership of projects, and there are many tools to manage subgroups of those people. -Normally these accounts are used for Open Source groups (such as "`perl`" or "`rails`") or companies (such as "`google`" or "`twitter`"). +Além das contas de usuário único, o GitHub tem o que são chamadas de Organizações (Organizations). +Como as contas pessoais, as contas de Organizações têm um namespace onde todos os seus projetos existem, mas muitas outras coisas são diferentes. +Essas contas representam um grupo de pessoas com propriedade compartilhada de projetos e existem muitas ferramentas para gerenciar subgrupos dessas pessoas. +Normalmente, essas contas são usadas por grupos Open Source (como "`perl`" ou "`rails`") ou empresas (como "`google`" ou "`twitter`"). -==== Organization Basics +==== O Básico de uma Organização -An organization is pretty easy to create; just click on the "`+`" icon at the top-right of any GitHub page, and select "`New organization`" from the menu. +Uma organização é muito fácil de criar; basta clicar no ícone "`+`" no canto superior direito de qualquer página do GitHub e selecionar "`New organization`" (Nova organização) no menu. -.The "`New organization`" menu item -image::images/neworg.png[The “New organization” menu item] +.O item de menu "`New organization`" +image::images/neworg.png[O item de menu "New organization"] -First you'll need to name your organization and provide an email address for a main point of contact for the group. -Then you can invite other users to be co-owners of the account if you want to. +Primeiro você precisará nomear a sua organização e fornecer um endereço de e-mail para um ponto de contato principal para o grupo. +Em seguida, você pode convidar outros usuários para serem coproprietários da conta, se desejar. -Follow these steps and you'll soon be the owner of a brand-new organization. -Like personal accounts, organizations are free if everything you plan to store there will be open source. +Siga essas etapas e você logo será o proprietário de uma organização novinha em folha. +Como as contas pessoais, as organizações são gratuitas se tudo o que você planeja armazenar lá for de código aberto. -As an owner in an organization, when you fork a repository, you'll have the choice of forking it to your organization's namespace. -When you create new repositories you can create them either under your personal account or under any of the organizations that you are an owner in. -You also automatically "`watch`" any new repository created under these organizations. +Como proprietário de uma organização, ao fazer fork de um repositório, você terá a opção de fazer o fork dele para o namespace da sua organização. +Ao criar novos repositórios, você pode criá-los em sua conta pessoal ou em qualquer uma das organizações das quais é proprietário. +Você também observa ("`watch`") automaticamente qualquer novo repositório criado sob essas organizações. -Just like in <<_personal_avatar>>, you can upload an avatar for your organization to personalize it a bit. -Also just like personal accounts, you have a landing page for the organization that lists all of your repositories and can be viewed by other people. +Assim como em <<_personal_avatar>>, você pode fazer o upload de um avatar para a sua organização para personalizá-la um pouco. +Também como as contas pessoais, você tem uma página de destino (landing page) para a organização que lista todos os seus repositórios e pode ser visualizada por outras pessoas. -Now let's cover some of the things that are a bit different with an organizational account. +Agora vamos cobrir algumas das coisas que são um pouco diferentes com uma conta organizacional. -==== Teams +==== Equipes (Teams) -Organizations are associated with individual people by way of teams, which are simply a grouping of individual user accounts and repositories within the organization and what kind of access those people have in those repositories. +Organizações são associadas a pessoas individuais por meio de equipes, que são simplesmente um agrupamento de contas de usuários individuais e repositórios dentro da organização, e o tipo de acesso que essas pessoas têm nesses repositórios. -For example, say your company has three repositories: `frontend`, `backend`, and `deployscripts`. -You'd want your HTML/CSS/JavaScript developers to have access to `frontend` and maybe `backend`, and your Operations people to have access to `backend` and `deployscripts`. -Teams make this easy, without having to manage the collaborators for every individual repository. +Por exemplo, digamos que a sua empresa tenha três repositórios: `frontend`, `backend` e `deployscripts`. +Você gostaria que os seus desenvolvedores de HTML/CSS/JavaScript tivessem acesso ao `frontend` e talvez ao `backend`, e que o seu pessoal de Operações tivesse acesso ao `backend` e `deployscripts`. +As equipes tornam isso fácil, sem ter que gerenciar os colaboradores de cada repositório individual. -The Organization page shows you a simple dashboard of all the repositories, users and teams that are under this organization. +A página da Organização mostra um painel simples de todos os repositórios, usuários e equipes que estão sob essa organização. [[_org_page]] -.The Organization page -image::images/orgs-01-page.png[The Organization page] +.A página da Organização +image::images/orgs-01-page.png[A página da Organização] -To manage your Teams, you can click on the Teams sidebar on the right hand side of the page in <<_org_page>>. -This will bring you to a page you can use to add members to the team, add repositories to the team or manage the settings and access control levels for the team. -Each team can have read only, read/write or administrative access to the repositories. -You can change that level by clicking the "`Settings`" button in <<_team_page>>. +Para gerenciar as suas Equipes (Teams), você pode clicar na barra lateral Equipes (Teams) no lado direito da página em <<_org_page>>. +Isso levará você a uma página que você pode usar para adicionar membros à equipe, adicionar repositórios à equipe ou gerenciar as configurações e níveis de controle de acesso para a equipe. +Cada equipe pode ter acesso somente de leitura, leitura/gravação ou administrativo aos repositórios. +Você pode alterar esse nível clicando no botão "`Settings`" (Configurações) em <<_team_page>>. [[_team_page]] -.The Team page -image::images/orgs-02-teams.png[The Team page] +.A página da Equipe +image::images/orgs-02-teams.png[A página da Equipe] -When you invite someone to a team, they will get an email letting them know they've been invited. +Quando você convidar alguém para uma equipe, ele receberá um e-mail avisando que foi convidado. -Additionally, team `@mentions` (such as `@acmecorp/frontend`) work much the same as they do with individual users, except that *all* members of the team are then subscribed to the thread. -This is useful if you want the attention from someone on a team, but you don't know exactly who to ask. +Além disso, as menções à equipe, `@mentions` (como `@acmecorp/frontend`), funcionam da mesma forma que com usuários individuais, exceto que *todos* os membros da equipe são então inscritos na thread. +Isso é útil se você quiser a atenção de alguém de uma equipe, mas não sabe exatamente para quem perguntar. -A user can belong to any number of teams, so don't limit yourself to only access-control teams. -Special-interest teams like `ux`, `css`, or `refactoring` are useful for certain kinds of questions, and others like `legal` and `colorblind` for an entirely different kind. +Um usuário pode pertencer a qualquer número de equipes, então não se limite apenas a equipes de controle de acesso. +Equipes de interesse especial como `ux`, `css` ou `refactoring` (refatoração) são úteis para certos tipos de perguntas, e outras como `legal` (jurídico) e `colorblind` (daltônico) para um tipo totalmente diferente. -==== Audit Log +==== Log de Auditoria (Audit Log) -Organizations also give owners access to all the information about what went on under the organization. -You can go to the 'Audit Log' tab and see what events have happened at an organization level, who did them and where in the world they were done. +As organizações também dão aos proprietários acesso a todas as informações sobre o que aconteceu sob a organização. +Você pode ir até a aba 'Audit Log' (Log de Auditoria) e ver quais eventos aconteceram em um nível de organização, quem os fez e em que lugar do mundo eles foram feitos. [[_the_audit_log]] -.The Audit log -image::images/orgs-03-audit.png[The Audit log] +.O Log de Auditoria +image::images/orgs-03-audit.png[O Log de Auditoria] -You can also filter down to specific types of events, specific places or specific people. +Você também pode filtrar por tipos específicos de eventos, locais específicos ou pessoas específicas. diff --git a/book/06-github/sections/5-scripting.asc b/book/06-github/sections/5-scripting.asc index c755afa1..e3fe816e 100644 --- a/book/06-github/sections/5-scripting.asc +++ b/book/06-github/sections/5-scripting.asc @@ -1,63 +1,63 @@ -=== Scripting GitHub +=== Criando Scripts para o GitHub -So now we've covered all of the major features and workflows of GitHub, but any large group or project will have customizations they may want to make or external services they may want to integrate. +Então, agora cobrimos todos os principais recursos e fluxos de trabalho do GitHub, mas qualquer grande grupo ou projeto terá personalizações que podem querer fazer ou serviços externos que podem querer integrar. -Luckily for us, GitHub is really quite hackable in many ways. -In this section we'll cover how to use the GitHub hooks system and its API to make GitHub work how we want it to. +Para nossa sorte, o GitHub é realmente bastante hackeável de muitas maneiras. +Nesta seção cobriremos como usar o sistema de hooks do GitHub e a sua API para fazer o GitHub funcionar como nós queremos. -==== Services and Hooks +==== Serviços e Hooks -The Hooks and Services section of GitHub repository administration is the easiest way to have GitHub interact with external systems. +A seção Hooks and Services da administração de repositório do GitHub é a maneira mais fácil de fazer o GitHub interagir com sistemas externos. -===== Services +===== Serviços -First we'll take a look at Services. -Both the Hooks and Services integrations can be found in the Settings section of your repository, where we previously looked at adding Collaborators and changing the default branch of your project. -Under the "`Webhooks and Services`" tab you will see something like <<_services_hooks>>. +Primeiro daremos uma olhada em Serviços. +Ambas as integrações de Hooks e Serviços podem ser encontradas na seção Settings do seu repositório, onde vimos anteriormente como adicionar Colaboradores e alterar o branch padrão do seu projeto. +Na aba "`Webhooks and Services`" (Webhooks e Serviços), você verá algo parecido com <<_services_hooks>>. [[_services_hooks]] -.Services and Hooks configuration section -image::images/scripting-01-services.png[Services and Hooks configuration section] +.Seção de configuração de Serviços e Hooks +image::images/scripting-01-services.png[Seção de configuração de Serviços e Hooks] -There are dozens of services you can choose from, most of them integrations into other commercial and open source systems. -Most of them are for Continuous Integration services, bug and issue trackers, chat room systems and documentation systems. -We'll walk through setting up a very simple one, the Email hook. -If you choose "`email`" from the "`Add Service`" dropdown, you'll get a configuration screen like <<_service_config>>. +Existem dezenas de serviços para escolher, a maioria integrações com outros sistemas comerciais e de código aberto. +A maioria deles é para serviços de Integração Contínua, rastreadores de bugs e issues, sistemas de sala de bate-papo e sistemas de documentação. +Passaremos pela configuração de um bem simples, o hook de E-mail. +Se você escolher "`email`" no menu suspenso "`Add Service`" (Adicionar Serviço), você obterá uma tela de configuração como <<_service_config>>. [[_service_config]] -.Email service configuration -image::images/scripting-02-email-service.png[Email service configuration] +.Configuração de serviço de e-mail +image::images/scripting-02-email-service.png[Configuração de serviço de e-mail] -In this case, if we hit the "`Add service`" button, the email address we specified will get an email every time someone pushes to the repository. -Services can listen for lots of different types of events, but most only listen for push events and then do something with that data. +Neste caso, se clicarmos no botão "`Add service`" (Adicionar serviço), o endereço de e-mail que especificamos receberá um e-mail toda vez que alguém fizer um push para o repositório. +Os serviços podem escutar muitos tipos diferentes de eventos, mas a maioria apenas escuta eventos de push e, em seguida, faz algo com esses dados. -If there is a system you are using that you would like to integrate with GitHub, you should check here to see if there is an existing service integration available. -For example, if you're using Jenkins to run tests on your codebase, you can enable the Jenkins builtin service integration to kick off a test run every time someone pushes to your repository. +Se houver um sistema que você esteja usando e que gostaria de integrar com o GitHub, você deve verificar aqui para ver se há uma integração de serviço existente disponível. +Por exemplo, se você estiver usando o Jenkins para executar testes em sua base de código, poderá habilitar a integração do serviço embutido do Jenkins para iniciar uma execução de teste toda vez que alguém fizer push no seu repositório. ===== Hooks -If you need something more specific or you want to integrate with a service or site that is not included in this list, you can instead use the more generic hooks system. -GitHub repository hooks are pretty simple. -You specify a URL and GitHub will post an HTTP payload to that URL on any event you want. +Se você precisar de algo mais específico ou quiser se integrar a um serviço ou site que não está incluído nesta lista, você pode usar o sistema de hooks mais genérico. +Os hooks de repositório do GitHub são bem simples. +Você especifica uma URL e o GitHub fará o post de um payload HTTP para essa URL em qualquer evento que você desejar. -Generally the way this works is you can setup a small web service to listen for a GitHub hook payload and then do something with the data when it is received. +Geralmente, a maneira como isso funciona é que você pode configurar um pequeno serviço web para escutar um payload do hook do GitHub e então fazer algo com os dados quando eles forem recebidos. -To enable a hook, you click the "`Add webhook`" button in <<_services_hooks>>. -This will bring you to a page that looks like <<_web_hook>>. +Para ativar um hook, você clica no botão "`Add webhook`" em <<_services_hooks>>. +Isso o levará a uma página semelhante a <<_web_hook>>. [[_web_hook]] -.Web hook configuration -image::images/scripting-03-webhook.png[Web hook configuration] +.Configuração de Web hook +image::images/scripting-03-webhook.png[Configuração de Web hook] -The configuration for a web hook is pretty simple. -In most cases you simply enter a URL and a secret key and hit "`Add webhook`". -There are a few options for which events you want GitHub to send you a payload for -- the default is to only get a payload for the `push` event, when someone pushes new code to any branch of your repository. +A configuração para um web hook é bastante simples. +Na maioria dos casos, você simplesmente insere uma URL e uma chave secreta e aperta "`Add webhook`". +Existem algumas opções para quais eventos você deseja que o GitHub envie um payload -- o padrão é receber um payload apenas para o evento `push`, quando alguém envia (push) novo código para qualquer branch do seu repositório. -Let's see a small example of a web service you may set up to handle a web hook. -We'll use the Ruby web framework Sinatra since it's fairly concise and you should be able to easily see what we're doing. +Vejamos um pequeno exemplo de um serviço web que você pode configurar para lidar com um web hook. +Nós usaremos o framework web Ruby Sinatra, já que ele é bastante conciso e você deve ser capaz de ver facilmente o que estamos fazendo. -Let's say we want to get an email if a specific person pushes to a specific branch of our project modifying a specific file. -We could fairly easily do that with code like this: +Digamos que queremos receber um e-mail se uma pessoa específica fizer push em um branch específico do nosso projeto, modificando um arquivo específico. +Nós poderíamos muito facilmente fazer isso com um código como este: [source,ruby] ---- @@ -93,37 +93,37 @@ post '/payload' do end ---- -Here we're taking the JSON payload that GitHub delivers us and looking up who pushed it, what branch they pushed to and what files were touched in all the commits that were pushed. -Then we check that against our criteria and send an email if it matches. +Aqui estamos pegando o payload JSON que o GitHub nos entrega e procurando quem fez o push, em qual branch fizeram o push e quais arquivos foram tocados em todos os commits que sofreram push. +Em seguida, verificamos isso contra os nossos critérios e enviamos um e-mail caso corresponda. -In order to develop and test something like this, you have a nice developer console in the same screen where you set the hook up. -You can see the last few deliveries that GitHub has tried to make for that webhook. -For each hook you can dig down into when it was delivered, if it was successful and the body and headers for both the request and the response. -This makes it incredibly easy to test and debug your hooks. +Para desenvolver e testar algo assim, você tem um console de desenvolvedor legal na mesma tela onde você configura o hook. +Você pode ver as últimas entregas que o GitHub tentou fazer para aquele webhook. +Para cada hook, você pode analisar quando ele foi entregue, se foi bem-sucedido e o corpo e os cabeçalhos tanto para a requisição quanto para a resposta. +Isso torna incrivelmente fácil testar e depurar seus hooks. [[_web_hook_debug]] -.Web hook debugging information -image::images/scripting-04-webhook-debug.png[Web hook debugging information] +.Informações de depuração do Web hook +image::images/scripting-04-webhook-debug.png[Informações de depuração do Web hook] -The other great feature of this is that you can redeliver any of the payloads to test your service easily. +O outro grande recurso disso é que você pode reenviar qualquer um dos payloads para testar o seu serviço facilmente. -For more information on how to write webhooks and all the different event types you can listen for, go to the GitHub Developer documentation at https://docs.github.com/en/webhooks-and-events/webhooks/about-webhooks[^]. +Para mais informações sobre como escrever webhooks e todos os diferentes tipos de eventos que você pode escutar, vá para a documentação do GitHub Developer em https://docs.github.com/en/webhooks-and-events/webhooks/about-webhooks[^]. -==== The GitHub API +==== A API do GitHub (((GitHub, API))) -Services and hooks give you a way to receive push notifications about events that happen on your repositories, but what if you need more information about these events? -What if you need to automate something like adding collaborators or labeling issues? +Serviços e hooks oferecem uma forma de receber notificações push sobre eventos que acontecem nos seus repositórios, mas e se você precisar de mais informações sobre esses eventos? +E se você precisar automatizar algo como adicionar colaboradores ou rotular issues? -This is where the GitHub API comes in handy. -GitHub has tons of API endpoints for doing nearly anything you can do on the website in an automated fashion. -In this section we'll learn how to authenticate and connect to the API, how to comment on an issue and how to change the status of a Pull Request through the API. +É aqui que a API do GitHub é útil. +O GitHub tem muitos endpoints de API para fazer de forma automatizada quase tudo que você pode fazer no site. +Nesta seção, aprenderemos como autenticar e se conectar à API, como comentar em uma issue e como alterar o status de um Pull Request através da API. -==== Basic Usage +==== Uso Básico -The most basic thing you can do is a simple GET request on an endpoint that doesn't require authentication. -This could be a user or read-only information on an open source project. -For example, if we want to know more about a user named "`schacon`", we can run something like this: +A coisa mais básica que você pode fazer é uma simples requisição GET num endpoint que não requer autenticação. +Isto pode ser um usuário ou uma informação somente leitura num projeto de código aberto. +Por exemplo, se quisermos saber mais sobre um usuário chamado "`schacon`", podemos rodar algo como isto: [source,javascript] ---- @@ -141,8 +141,8 @@ $ curl https://api.github.com/users/schacon } ---- -There are tons of endpoints like this to get information about organizations, projects, issues, commits -- just about anything you can publicly see on GitHub. -You can even use the API to render arbitrary Markdown or find a `.gitignore` template. +Há toneladas de endpoints como esse para obter informações sobre organizações, projetos, issues, commits -- basicamente qualquer coisa que você possa ver publicamente no GitHub. +Você pode até mesmo usar a API para renderizar Markdown arbitrário ou encontrar um template `.gitignore`. [source,javascript] ---- @@ -165,32 +165,32 @@ hs_err_pid* } ---- -==== Commenting on an Issue +==== Comentando em uma Issue -However, if you want to do an action on the website such as comment on an Issue or Pull Request or if you want to view or interact with private content, you'll need to authenticate. +No entanto, se você quiser fazer uma ação no site como comentar em uma Issue ou Pull Request ou se você quiser visualizar ou interagir com conteúdo privado, você precisará se autenticar. -There are several ways to authenticate. -You can use basic authentication with just your username and password, but generally it's a better idea to use a personal access token. -You can generate this from the "`Applications`" tab of your settings page. +Existem várias maneiras de se autenticar. +Você pode usar autenticação básica com apenas seu nome de usuário e senha, mas geralmente é uma ideia melhor usar um token de acesso pessoal. +Você pode gerar isso a partir da aba "`Applications`" (Aplicações) da sua página de configurações. [[_access_token]] -.Generate your access token from the "`Applications`" tab of your settings page -image::images/scripting-05-access-token.png[Generate your access token from the “Applications” tab of your settings page] +.Gere seu token de acesso a partir da aba "`Applications`" da sua página de configurações +image::images/scripting-05-access-token.png[Gere seu token de acesso a partir da aba "Applications" da sua página de configurações] -It will ask you which scopes you want for this token and a description. -Make sure to use a good description so you feel comfortable removing the token when your script or application is no longer used. +Ele perguntará quais escopos você deseja para esse token e uma descrição. +Certifique-se de usar uma boa descrição para se sentir confortável ao remover o token quando o seu script ou aplicação não for mais usado. -GitHub will only show you the token once, so be sure to copy it. -You can now use this to authenticate in your script instead of using a username and password. -This is nice because you can limit the scope of what you want to do and the token is revocable. +O GitHub mostrará o token apenas uma vez, então certifique-se de copiá-lo. +Você pode agora usar isso para se autenticar no seu script em vez de usar um nome de usuário e senha. +Isso é legal porque você pode limitar o escopo do que deseja fazer e o token é revogável. -This also has the added advantage of increasing your rate limit. -Without authenticating, you will be limited to 60 requests per hour. -If you authenticate you can make up to 5,000 requests per hour. +Isso também tem a vantagem adicional de aumentar o seu limite de requisições (rate limit). +Sem autenticação, você será limitado a 60 requisições por hora. +Se você se autenticar, pode fazer até 5.000 requisições por hora. -So let's use it to make a comment on one of our issues. -Let's say we want to leave a comment on a specific issue, Issue #6. -To do so we have to do an HTTP POST request to `repos///issues//comments` with the token we just generated as an Authorization header. +Então, vamos usá-lo para fazer um comentário em uma de nossas issues. +Digamos que queremos deixar um comentário em uma issue específica, a Issue #6. +Para fazer isso, temos que fazer uma requisição HTTP POST para `repos///issues//comments` com o token que acabamos de gerar como um cabeçalho Authorization. [source,javascript] ---- @@ -214,23 +214,23 @@ $ curl -H "Content-Type: application/json" \ } ---- -Now if you go to that issue, you can see the comment that we just successfully posted as in <<_api_comment>>. +Agora, se você for a essa issue, poderá ver o comentário que acabamos de postar com sucesso, como em <<_api_comment>>. [[_api_comment]] -.A comment posted from the GitHub API -image::images/scripting-06-comment.png[A comment posted from the GitHub API] +.Um comentário postado da API do GitHub +image::images/scripting-06-comment.png[Um comentário postado da API do GitHub] -You can use the API to do just about anything you can do on the website -- creating and setting milestones, assigning people to Issues and Pull Requests, creating and changing labels, accessing commit data, creating new commits and branches, opening, closing or merging Pull Requests, creating and editing teams, commenting on lines of code in a Pull Request, searching the site and on and on. +Você pode usar a API para fazer basicamente qualquer coisa que você pode fazer no site -- criar e configurar marcos (milestones), atribuir pessoas a Issues e Pull Requests, criar e alterar rótulos (labels), acessar dados de commit, criar novos commits e branches, abrir, fechar ou mesclar Pull Requests, criar e editar equipes, comentar em linhas de código em um Pull Request, pesquisar no site e muito mais. -==== Changing the Status of a Pull Request +==== Alterando o Status de um Pull Request -There is one final example we'll look at since it's really useful if you're working with Pull Requests. -Each commit can have one or more statuses associated with it and there is an API to add and query that status. +Há um último exemplo que veremos, já que é realmente útil se você estiver trabalhando com Pull Requests. +Cada commit pode ter um ou mais status associados a ele e há uma API para adicionar e consultar esse status. -Most of the Continuous Integration and testing services make use of this API to react to pushes by testing the code that was pushed, and then report back if that commit has passed all the tests. -You could also use this to check if the commit message is properly formatted, if the submitter followed all your contribution guidelines, if the commit was validly signed -- any number of things. +A maioria dos serviços de Integração Contínua e testes faz uso desta API para reagir a pushes, testando o código que sofreu push, e então relatando de volta se aquele commit passou em todos os testes. +Você também poderia usar isso para verificar se a mensagem de commit está formatada corretamente, se o remetente seguiu todas as suas diretrizes de contribuição, se o commit foi validamente assinado -- qualquer número de coisas. -Let's say you set up a webhook on your repository that hits a small web service that checks for a `Signed-off-by` string in the commit message. +Digamos que você configure um webhook no seu repositório que atinge um pequeno serviço web que verifica uma string `Signed-off-by` na mensagem de commit. [source,ruby] ---- @@ -275,27 +275,27 @@ post '/payload' do end ---- -Hopefully this is fairly simple to follow. -In this web hook handler we look through each commit that was just pushed, we look for the string 'Signed-off-by' in the commit message and finally we POST via HTTP to the `/repos///statuses/` API endpoint with the status. +Espero que isso seja bastante simples de acompanhar. +Neste manipulador de web hook (handler), olhamos cada commit que acabou de sofrer push, procuramos pela string 'Signed-off-by' na mensagem de commit e finalmente fazemos um POST via HTTP para o endpoint da API `/repos///statuses/` com o status. -In this case you can send a state ('success', 'failure', 'error'), a description of what happened, a target URL the user can go to for more information and a "`context`" in case there are multiple statuses for a single commit. -For example, a testing service may provide a status and a validation service like this may also provide a status -- the "`context`" field is how they're differentiated. +Neste caso, você pode enviar um estado ('success', 'failure', 'error'), uma descrição do que aconteceu, uma URL de destino (target URL) onde o usuário pode ir para obter mais informações e um "`context`" (contexto) no caso de haver vários status para um único commit. +Por exemplo, um serviço de teste pode fornecer um status e um serviço de validação como este também pode fornecer um status -- o campo "`context`" é como eles são diferenciados. -If someone opens a new Pull Request on GitHub and this hook is set up, you may see something like <<_commit_status>>. +Se alguém abrir um novo Pull Request no GitHub e este hook estiver configurado, você poderá ver algo como <<_commit_status>>. [[_commit_status]] -.Commit status via the API -image::images/scripting-07-status.png[Commit status via the API] +.Status do commit via API +image::images/scripting-07-status.png[Status do commit via API] -You can now see a little green check mark next to the commit that has a "`Signed-off-by`" string in the message and a red cross through the one where the author forgot to sign off. -You can also see that the Pull Request takes the status of the last commit on the branch and warns you if it is a failure. -This is really useful if you're using this API for test results so you don't accidentally merge something where the last commit is failing tests. +Você pode ver agora uma pequena marca de seleção (check mark) verde ao lado do commit que tem uma string "`Signed-off-by`" na mensagem e uma cruz vermelha naquele em que o autor esqueceu de assinar (sign off). +Você também pode ver que o Pull Request pega o status do último commit no branch e o avisa se for uma falha. +Isso é realmente útil se você estiver usando esta API para resultados de testes, para que não mescle acidentalmente algo em que o último commit esteja falhando nos testes. ==== Octokit -Though we've been doing nearly everything through `curl` and simple HTTP requests in these examples, several open-source libraries exist that make this API available in a more idiomatic way. -At the time of this writing, the supported languages include Go, Objective-C, Ruby, and .NET. -Check out https://github.com/octokit[^] for more information on these, as they handle much of the HTTP for you. +Embora tenhamos feito quase tudo através de `curl` e simples requisições HTTP nestes exemplos, existem várias bibliotecas de código aberto que disponibilizam esta API de uma maneira mais idiomática. +No momento em que este livro foi escrito, as linguagens suportadas incluíam Go, Objective-C, Ruby e .NET. +Confira https://github.com/octokit[^] para obter mais informações sobre eles, pois eles lidam com grande parte do HTTP para você. -Hopefully these tools can help you customize and modify GitHub to work better for your specific workflows. -For complete documentation on the entire API as well as guides for common tasks, check out https://docs.github.com/[^]. +Esperamos que estas ferramentas possam ajudá-lo a personalizar e modificar o GitHub para funcionar melhor com os seus fluxos de trabalho específicos. +Para a documentação completa de toda a API, bem como guias para tarefas comuns, confira https://docs.github.com/[^]. diff --git a/ch06-github.asc b/ch06-github.asc index e2cd29e7..794fb0af 100644 --- a/ch06-github.asc +++ b/ch06-github.asc @@ -2,20 +2,20 @@ == GitHub (((GitHub))) -GitHub is the single largest host for Git repositories, and is the central point of collaboration for millions of developers and projects. -A large percentage of all Git repositories are hosted on GitHub, and many open-source projects use it for Git hosting, issue tracking, code review, and other things. -So while it's not a direct part of the Git open source project, there's a good chance that you'll want or need to interact with GitHub at some point while using Git professionally. +O GitHub é o maior provedor de hospedagem de repositórios Git, e é o ponto central de colaboração para milhões de desenvolvedores e projetos. +Uma grande porcentagem de todos os repositórios Git está hospedada no GitHub, e muitos projetos de código aberto o utilizam para hospedagem Git, rastreamento de problemas (issue tracking), revisão de código e outras coisas. +Portanto, embora não seja uma parte direta do projeto de código aberto Git, há uma boa chance de você querer ou precisar interagir com o GitHub em algum momento enquanto usa o Git profissionalmente. -This chapter is about using GitHub effectively. -We'll cover signing up for and managing an account, creating and using Git repositories, common workflows to contribute to projects and to accept contributions to yours, GitHub's programmatic interface and lots of little tips to make your life easier in general. +Este capítulo é sobre como usar o GitHub de forma eficaz. +Nós abordaremos como se inscrever e gerenciar uma conta, criar e usar repositórios Git, fluxos de trabalho comuns para contribuir com projetos e aceitar contribuições para os seus, a interface programática do GitHub e várias dicas para facilitar a sua vida em geral. -If you are not interested in using GitHub to host your own projects or to collaborate with other projects that are hosted on GitHub, you can safely skip to <>. +Se você não estiver interessado em usar o GitHub para hospedar seus próprios projetos ou colaborar com outros projetos que estão hospedados no GitHub, você pode pular para <> com segurança. [WARNING] -.Interfaces Change +.Alterações de Interface ==== -It's important to note that like many active websites, the UI elements in these screenshots are bound to change over time. -Hopefully the general idea of what we're trying to accomplish here will still be there, but if you want more up to date versions of these screens, the online versions of this book may have newer screenshots. +É importante notar que, como muitos sites ativos, os elementos de interface de usuário (UI) nestas capturas de tela estão sujeitos a alterações ao longo do tempo. +Esperamos que a ideia geral do que estamos tentando realizar aqui ainda esteja lá, mas se você quiser versões mais atualizadas dessas telas, as versões online deste livro podem ter capturas de tela mais novas. ==== include::book/06-github/sections/1-setting-up-account.asc[] @@ -28,8 +28,8 @@ include::book/06-github/sections/4-managing-organization.asc[] include::book/06-github/sections/5-scripting.asc[] -=== Summary +=== Resumo -Now you're a GitHub user. -You know how to create an account, manage an organization, create and push to repositories, contribute to other people's projects and accept contributions from others. -In the next chapter, you'll learn more powerful tools and tips for dealing with complex situations, which will truly make you a Git master. +Agora você é um usuário do GitHub. +Você sabe como criar uma conta, gerenciar uma organização, criar e fazer push para repositórios, contribuir para projetos de outras pessoas e aceitar contribuições de terceiros. +No próximo capítulo, você aprenderá sobre ferramentas e dicas mais poderosas para lidar com situações complexas, o que fará de você verdadeiramente um mestre no Git. From 71a9c3d19d21d5d4fbea1daa1d00d059a273a487 Mon Sep 17 00:00:00 2001 From: "Sergio Cabral (AI Agent)" Date: Thu, 20 Aug 2026 13:51:59 -0300 Subject: [PATCH 09/16] =?UTF-8?q?Traduz:=20Cap=C3=ADtulo=207=20=E2=80=94?= =?UTF-8?q?=20Ferramentas=20do=20Git?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../sections/advanced-merging.asc | 354 +++++++-------- book/07-git-tools/sections/bundling.asc | 86 ++-- book/07-git-tools/sections/credentials.asc | 182 ++++---- book/07-git-tools/sections/debugging.asc | 92 ++-- .../sections/interactive-staging.asc | 72 +-- book/07-git-tools/sections/replace.asc | 98 ++-- book/07-git-tools/sections/rerere.asc | 86 ++-- book/07-git-tools/sections/reset.asc | 380 ++++++++-------- .../sections/revision-selection.asc | 216 ++++----- .../sections/rewriting-history.asc | 240 +++++----- book/07-git-tools/sections/searching.asc | 62 +-- book/07-git-tools/sections/signing.asc | 66 +-- .../sections/stashing-cleaning.asc | 134 +++--- book/07-git-tools/sections/submodules.asc | 426 +++++++++--------- book/07-git-tools/sections/subtree-merges.asc | 60 +-- ch07-git-tools.asc | 18 +- 16 files changed, 1286 insertions(+), 1286 deletions(-) diff --git a/book/07-git-tools/sections/advanced-merging.asc b/book/07-git-tools/sections/advanced-merging.asc index 7ace27bc..0479ddbe 100644 --- a/book/07-git-tools/sections/advanced-merging.asc +++ b/book/07-git-tools/sections/advanced-merging.asc @@ -1,28 +1,28 @@ [[_advanced_merging]] -=== Advanced Merging +=== Merging Avançado -Merging in Git is typically fairly easy. -Since Git makes it easy to merge another branch multiple times, it means that you can have a very long lived branch but you can keep it up to date as you go, solving small conflicts often, rather than be surprised by one enormous conflict at the end of the series. +Fazer merge no Git é tipicamente bem fácil. +Já que o Git facilita o merge de outra branch várias vezes, isso significa que você pode ter uma branch de vida muito longa, mas você pode mantê-la atualizada conforme avança, resolvendo pequenos conflitos frequentemente, em vez de ser surpreendido por um conflito enorme no final da série. -However, sometimes tricky conflicts do occur. -Unlike some other version control systems, Git does not try to be overly clever about merge conflict resolution. -Git's philosophy is to be smart about determining when a merge resolution is unambiguous, but if there is a conflict, it does not try to be clever about automatically resolving it. -Therefore, if you wait too long to merge two branches that diverge quickly, you can run into some issues. +No entanto, às vezes ocorrem conflitos complicados. +Ao contrário de alguns outros sistemas de controle de versão, o Git não tenta ser excessivamente esperto sobre a resolução de conflitos de merge. +A filosofia do Git é ser inteligente para determinar quando a resolução de um merge é inequívoca, mas se houver um conflito, ele não tenta ser esperto para resolvê-lo automaticamente. +Portanto, se você esperar muito tempo para fazer merge de duas branches que divergem rapidamente, você pode ter alguns problemas. -In this section, we'll go over what some of those issues might be and what tools Git gives you to help handle these more tricky situations. -We'll also cover some of the different, non-standard types of merges you can do, as well as see how to back out of merges that you've done. +Nesta seção, abordaremos quais podem ser alguns desses problemas e quais ferramentas o Git fornece para ajudar a lidar com essas situações mais complicadas. +Também abordaremos alguns dos diferentes tipos não padronizados de merges que você pode fazer, bem como veremos como desfazer merges que você já fez. -==== Merge Conflicts +==== Conflitos de Merge -While we covered some basics on resolving merge conflicts in <>, for more complex conflicts, Git provides a few tools to help you figure out what's going on and how to better deal with the conflict. +Embora tenhamos coberto alguns conceitos básicos sobre como resolver conflitos de merge em <>, para conflitos mais complexos, o Git fornece algumas ferramentas para ajudá-lo a descobrir o que está acontecendo e como lidar melhor com o conflito. -First of all, if at all possible, try to make sure your working directory is clean before doing a merge that may have conflicts. -If you have work in progress, either commit it to a temporary branch or stash it. -This makes it so that you can undo *anything* you try here. -If you have unsaved changes in your working directory when you try a merge, some of these tips may help you preserve that work. +Em primeiro lugar, se possível, tente certificar-se de que o seu diretório de trabalho está limpo antes de fazer um merge que possa ter conflitos. +Se você tiver trabalho em andamento, ou comite-o em uma branch temporária ou faça o stash dele. +Isso faz com que você possa desfazer *qualquer coisa* que tentar aqui. +Se você tiver alterações não salvas no seu diretório de trabalho ao tentar um merge, algumas dessas dicas podem ajudá-lo a preservar esse trabalho. -Let's walk through a very simple example. -We have a super simple Ruby file that prints 'hello world'. +Vamos analisar um exemplo muito simples. +Temos um arquivo Ruby super simples que imprime 'hello world'. [source,ruby] ---- @@ -35,8 +35,8 @@ end hello() ---- -In our repository, we create a new branch named `whitespace` and proceed to change all the Unix line endings to DOS line endings, essentially changing every line of the file, but just with whitespace. -Then we change the line "`hello world`" to "`hello mundo`". +No nosso repositório, nós criamos uma nova branch chamada `whitespace` e procedemos à alteração de todos os finais de linha do Unix para os finais de linha do DOS, alterando essencialmente todas as linhas do arquivo, mas apenas com espaços em branco (whitespace). +Então nós alteramos a linha "`hello world`" para "`hello mundo`". [source,console] ---- @@ -70,7 +70,7 @@ $ git commit -am 'Use Spanish instead of English' 1 file changed, 1 insertion(+), 1 deletion(-) ---- -Now we switch back to our `master` branch and add some documentation for the function. +Agora nós mudamos de volta para a nossa branch `master` e adicionamos alguma documentação para a função. [source,console] ---- @@ -96,7 +96,7 @@ $ git commit -am 'Add comment documenting the function' 1 file changed, 1 insertion(+) ---- -Now we try to merge in our `whitespace` branch and we'll get conflicts because of the whitespace changes. +Agora tentamos fazer o merge da nossa branch `whitespace` e teremos conflitos por causa das alterações de espaço em branco. [source,console] ---- @@ -107,11 +107,11 @@ Automatic merge failed; fix conflicts and then commit the result. ---- [[_abort_merge]] -===== Aborting a Merge +===== Abortando um Merge -We now have a few options. -First, let's cover how to get out of this situation. -If you perhaps weren't expecting conflicts and don't want to quite deal with the situation yet, you can simply back out of the merge with `git merge --abort`. +Nós agora temos algumas opções. +Primeiro, vamos cobrir como sair desta situação. +Se talvez você não estivesse esperando conflitos e não quer lidar bem com a situação ainda, você pode simplesmente cancelar o merge com `git merge --abort`. [source,console] ---- @@ -125,21 +125,21 @@ $ git status -sb ## master ---- -The `git merge --abort` option tries to revert back to your state before you ran the merge. -The only cases where it may not be able to do this perfectly would be if you had unstashed, uncommitted changes in your working directory when you ran it, otherwise it should work fine. +A opção `git merge --abort` tenta reverter de volta para o seu estado antes de você rodar o merge. +Os únicos casos onde ele pode não conseguir fazer isso perfeitamente seria se você tivesse alterações não comitadas e não stashadas no seu diretório de trabalho quando você o rodou, caso contrário, deve funcionar bem. -If for some reason you just want to start over, you can also run `git reset --hard HEAD`, and your repository will be back to the last committed state. -Remember that any uncommitted work will be lost, so make sure you don't want any of your changes. +Se por alguma razão você só quer começar de novo, você também pode rodar `git reset --hard HEAD`, e seu repositório voltará para o último estado comitado. +Lembre-se que qualquer trabalho não comitado será perdido, então certifique-se de que você não quer nenhuma das suas alterações. -===== Ignoring Whitespace +===== Ignorando Espaços em Branco (Whitespace) -In this specific case, the conflicts are whitespace related. -We know this because the case is simple, but it's also pretty easy to tell in real cases when looking at the conflict because every line is removed on one side and added again on the other. -By default, Git sees all of these lines as being changed, so it can't merge the files. +Neste caso específico, os conflitos estão relacionados a espaços em branco. +Nós sabemos isso porque o caso é simples, mas também é bem fácil dizer em casos reais ao olhar para o conflito porque toda linha é removida de um lado e adicionada de novo no outro. +Por padrão, o Git vê todas estas linhas como tendo sido alteradas, então ele não consegue fazer o merge dos arquivos. -The default merge strategy can take arguments though, and a few of them are about properly ignoring whitespace changes. -If you see that you have a lot of whitespace issues in a merge, you can simply abort it and do it again, this time with `-Xignore-all-space` or `-Xignore-space-change`. -The first option ignores whitespace *completely* when comparing lines, the second treats sequences of one or more whitespace characters as equivalent. +No entanto, a estratégia de merge padrão pode receber argumentos, e alguns deles são sobre ignorar adequadamente alterações de espaços em branco. +Se você ver que tem muitos problemas de espaços em branco em um merge, você pode simplesmente abortá-lo e fazê-lo novamente, desta vez com `-Xignore-all-space` ou `-Xignore-space-change`. +A primeira opção ignora o espaço em branco *completamente* ao comparar linhas, a segunda trata sequências de um ou mais caracteres de espaço em branco como equivalentes. [source,console] ---- @@ -150,28 +150,28 @@ Merge made by the 'recursive' strategy. 1 file changed, 1 insertion(+), 1 deletion(-) ---- -Since in this case, the actual file changes were not conflicting, once we ignore the whitespace changes, everything merges just fine. +Já que neste caso, as alterações reais no arquivo não eram conflitantes, uma vez que ignoramos as alterações de espaços em branco, tudo faz merge perfeitamente. -This is a lifesaver if you have someone on your team who likes to occasionally reformat everything from spaces to tabs or vice-versa. +Isso é um salva-vidas se você tem alguém na sua equipe que gosta de ocasionalmente reformatar tudo de espaços para tabs ou vice-versa. [[_manual_remerge]] -===== Manual File Re-merging +===== Re-merging Manual de Arquivos -Though Git handles whitespace pre-processing pretty well, there are other types of changes that perhaps Git can't handle automatically, but are scriptable fixes. -As an example, let's pretend that Git could not handle the whitespace change and we needed to do it by hand. +Embora o Git lide muito bem com o pré-processamento de espaços em branco, existem outros tipos de alterações que talvez o Git não consiga lidar automaticamente, mas são correções scriptáveis. +Como exemplo, vamos fingir que o Git não conseguiu lidar com a alteração de espaços em branco e nós precisamos fazer isso à mão. -What we really need to do is run the file we're trying to merge in through a `dos2unix` program before trying the actual file merge. -So how would we do that? +O que realmente precisamos fazer é rodar o arquivo que estamos tentando fazer merge através de um programa `dos2unix` antes de tentar o merge real do arquivo. +Então, como faríamos isso? -First, we get into the merge conflict state. -Then we want to get copies of our version of the file, their version (from the branch we're merging in) and the common version (from where both sides branched off). -Then we want to fix up either their side or our side and re-try the merge again for just this single file. +Primeiro, nós entramos no estado de conflito de merge. +Então nós queremos obter cópias da nossa versão do arquivo, a versão deles (da branch que estamos fazendo merge) e a versão comum (de onde ambos os lados ramificaram). +Em seguida, queremos corrigir o lado deles ou o nosso e tentar novamente o merge apenas para este único arquivo. -Getting the three file versions is actually pretty easy. -Git stores all of these versions in the index under "`stages`" which each have numbers associated with them. -Stage 1 is the common ancestor, stage 2 is your version and stage 3 is from the `MERGE_HEAD`, the version you're merging in ("`theirs`"). +Obter as três versões do arquivo é na verdade bem fácil. +O Git armazena todas estas versões no index sob "`estágios`" (stages) que cada um tem números associados a eles. +O Estágio 1 é o ancestral comum, o estágio 2 é a sua versão e o estágio 3 é do `MERGE_HEAD`, a versão que você está fazendo merge ("`theirs`"). -You can extract a copy of each of these versions of the conflicted file with the `git show` command and a special syntax. +Você pode extrair uma cópia de cada uma dessas versões do arquivo conflitante com o comando `git show` e uma sintaxe especial. [source,console] ---- @@ -180,7 +180,7 @@ $ git show :2:hello.rb > hello.ours.rb $ git show :3:hello.rb > hello.theirs.rb ---- -If you want to get a little more hard core, you can also use the `ls-files -u` plumbing command to get the actual SHA-1s of the Git blobs for each of these files. +Se você quiser ser um pouco mais hardcore, você também pode usar o comando de encanamento (plumbing) `ls-files -u` para obter os SHA-1 reais dos blobs do Git para cada um desses arquivos. [source,console] ---- @@ -190,9 +190,9 @@ $ git ls-files -u 100755 e85207e04dfdd5eb0a1e9febbc67fd837c44a1cd 3 hello.rb ---- -The `:1:hello.rb` is just a shorthand for looking up that blob SHA-1. +O `:1:hello.rb` é apenas um atalho (shorthand) para procurar aquele SHA-1 do blob. -Now that we have the content of all three stages in our working directory, we can manually fix up theirs to fix the whitespace issue and re-merge the file with the little-known `git merge-file` command which does just that. +Agora que temos o conteúdo de todos os três estágios em nosso diretório de trabalho, podemos consertar manualmente a versão deles para resolver a questão do espaço em branco e fazer re-merge do arquivo com o pouco conhecido comando `git merge-file` que faz exatamente isso. [source,console] ---- @@ -219,14 +219,14 @@ index 36c06c8,e85207e..0000000 hello() ---- -At this point we have nicely merged the file. -In fact, this actually works better than the `ignore-space-change` option because this actually fixes the whitespace changes before merge instead of simply ignoring them. -In the `ignore-space-change` merge, we actually ended up with a few lines with DOS line endings, making things mixed. +Neste ponto, fizemos o merge do arquivo perfeitamente. +Na verdade, isso funciona melhor do que a opção `ignore-space-change` porque isso realmente conserta as alterações de espaço em branco antes do merge, em vez de simplesmente ignorá-las. +No merge com `ignore-space-change`, nós na verdade terminamos com algumas linhas com finais de linha do DOS, deixando as coisas misturadas. -If you want to get an idea before finalizing this commit about what was actually changed between one side or the other, you can ask `git diff` to compare what is in your working directory that you're about to commit as the result of the merge to any of these stages. -Let's go through them all. +Se você quiser ter uma ideia, antes de finalizar este commit, sobre o que foi realmente alterado entre um lado e outro, você pode pedir ao `git diff` para comparar o que está no seu diretório de trabalho que você está prestes a comitar como resultado do merge para qualquer um desses estágios. +Vamos analisar todos eles. -To compare your result to what you had in your branch before the merge, in other words, to see what the merge introduced, you can run `git diff --ours`: +Para comparar o seu resultado com o que você tinha na sua branch antes do merge, ou seja, para ver o que o merge introduziu, você pode rodar `git diff --ours`: [source,console] ---- @@ -247,10 +247,10 @@ index 36c06c8..44d0a25 100755 hello() ---- -So here we can easily see that what happened in our branch, what we're actually introducing to this file with this merge, is changing that single line. +Então, aqui podemos ver facilmente que o que aconteceu na nossa branch, o que estamos realmente introduzindo neste arquivo com este merge, é a alteração daquela única linha. -If we want to see how the result of the merge differed from what was on their side, you can run `git diff --theirs`. -In this and the following example, we have to use `-b` to strip out the whitespace because we're comparing it to what is in Git, not our cleaned up `hello.theirs.rb` file. +Se quisermos ver como o resultado do merge diferiu do que estava no lado deles, você pode rodar `git diff --theirs`. +Neste e no exemplo seguinte, nós temos que usar `-b` para retirar os espaços em branco porque estamos comparando com o que está no Git, não o nosso arquivo limpo `hello.theirs.rb`. [source,console] ---- @@ -269,7 +269,7 @@ index e85207e..44d0a25 100755 end ---- -Finally, you can see how the file has changed from both sides with `git diff --base`. +Finalmente, você pode ver como o arquivo mudou a partir de ambos os lados com `git diff --base`. [source,console] ---- @@ -291,7 +291,7 @@ index ac51efd..44d0a25 100755 hello() ---- -At this point we can use the `git clean` command to clear out the extra files we created to do the manual merge but no longer need. +Neste ponto, podemos usar o comando `git clean` para limpar os arquivos extras que criamos para fazer o merge manual mas que não precisamos mais. [source,console] ---- @@ -302,12 +302,12 @@ Removing hello.theirs.rb ---- [[_checking_out_conflicts]] -===== Checking Out Conflicts +===== Fazendo Checkout de Conflitos -Perhaps we're not happy with the resolution at this point for some reason, or maybe manually editing one or both sides still didn't work well and we need more context. +Talvez nós não estejamos felizes com a resolução neste ponto por algum motivo, ou talvez editar manualmente um ou ambos os lados ainda não tenha funcionado bem e precisamos de mais contexto. -Let's change up the example a little. -For this example, we have two longer lived branches that each have a few commits in them but create a legitimate content conflict when merged. +Vamos mudar o exemplo um pouco. +Para este exemplo, temos duas branches de vida mais longa que cada uma tem alguns commits nelas mas criam um conflito de conteúdo legítimo quando é feito o merge. [source,console] ---- @@ -322,8 +322,8 @@ $ git log --graph --oneline --decorate --all * b7dcc89 Initial hello world code ---- -We now have three unique commits that live only on the `master` branch and three others that live on the `mundo` branch. -If we try to merge the `mundo` branch in, we get a conflict. +Nós agora temos três commits únicos que vivem apenas na branch `master` e outros três que vivem na branch `mundo`. +Se tentarmos fazer o merge da branch `mundo`, nós teremos um conflito. [source,console] ---- @@ -333,8 +333,8 @@ CONFLICT (content): Merge conflict in hello.rb Automatic merge failed; fix conflicts and then commit the result. ---- -We would like to see what the merge conflict is. -If we open up the file, we'll see something like this: +Gostaríamos de ver qual é o conflito do merge. +Se abrirmos o arquivo, veremos algo assim: [source,ruby] ---- @@ -351,25 +351,25 @@ end hello() ---- -Both sides of the merge added content to this file, but some of the commits modified the file in the same place that caused this conflict. +Ambos os lados do merge adicionaram conteúdo a este arquivo, mas alguns dos commits modificaram o arquivo no mesmo lugar que causou esse conflito. -Let's explore a couple of tools that you now have at your disposal to determine how this conflict came to be. -Perhaps it's not obvious how exactly you should fix this conflict. -You need more context. +Vamos explorar um par de ferramentas que você tem agora à sua disposição para determinar como este conflito ocorreu. +Talvez não seja óbvio como exatamente você deveria consertar este conflito. +Você precisa de mais contexto. -One helpful tool is `git checkout` with the `--conflict` option. -This will re-checkout the file again and replace the merge conflict markers. -This can be useful if you want to reset the markers and try to resolve them again. +Uma ferramenta útil é o `git checkout` com a opção `--conflict`. +Isso fará o re-checkout do arquivo novamente e substituirá os marcadores de conflito do merge. +Isso pode ser útil se você quiser resetar os marcadores e tentar resolvê-los novamente. -You can pass `--conflict` either `diff3` or `merge` (which is the default). -If you pass it `diff3`, Git will use a slightly different version of conflict markers, not only giving you the "`ours`" and "`theirs`" versions, but also the "`base`" version inline to give you more context. +Você pode passar para `--conflict` o valor `diff3` ou `merge` (que é o padrão). +Se você passar `diff3`, o Git usará uma versão ligeiramente diferente de marcadores de conflito, não apenas dando a você as versões "`ours`" e "`theirs`", mas também a versão "`base`" inline para lhe dar mais contexto. [source,console] ---- $ git checkout --conflict=diff3 hello.rb ---- -Once we run that, the file will look like this instead: +Uma vez que rodarmos isso, o arquivo ficará assim em vez disso: [source,ruby] ---- @@ -388,25 +388,25 @@ end hello() ---- -If you like this format, you can set it as the default for future merge conflicts by setting the `merge.conflictstyle` setting to `diff3`. +Se você gostar desse formato, você pode defini-lo como padrão para conflitos de merge futuros, ajustando a configuração `merge.conflictstyle` para `diff3`. [source,console] ---- $ git config --global merge.conflictstyle diff3 ---- -The `git checkout` command can also take `--ours` and `--theirs` options, which can be a really fast way of just choosing either one side or the other without merging things at all. +O comando `git checkout` também pode receber as opções `--ours` e `--theirs`, o que pode ser uma maneira muito rápida de simplesmente escolher um lado ou o outro sem fazer merge de nada. -This can be particularly useful for conflicts of binary files where you can simply choose one side, or where you only want to merge certain files in from another branch -- you can do the merge and then checkout certain files from one side or the other before committing. +Isso pode ser particularmente útil para conflitos de arquivos binários onde você pode simplesmente escolher um lado, ou onde você só quer fazer merge de certos arquivos de outra branch -- você pode fazer o merge e então fazer checkout de certos arquivos de um lado ou do outro antes de comitar. [[_merge_log]] -===== Merge Log +===== Log de Merge (Merge Log) -Another useful tool when resolving merge conflicts is `git log`. -This can help you get context on what may have contributed to the conflicts. -Reviewing a little bit of history to remember why two lines of development were touching the same area of code can be really helpful sometimes. +Outra ferramenta útil ao resolver conflitos de merge é o `git log`. +Isso pode ajudá-lo a obter contexto sobre o que pode ter contribuído para os conflitos. +Revisar um pouco do histórico para lembrar o porquê de duas linhas de desenvolvimento estarem mexendo na mesma área de código pode ser muito útil às vezes. -To get a full list of all of the unique commits that were included in either branch involved in this merge, we can use the "`triple dot`" syntax that we learned in <>. +Para obter uma lista completa de todos os commits únicos que foram incluídos em qualquer uma das branches envolvidas neste merge, nós podemos usar a sintaxe de "`três pontos`" (triple dot) que aprendemos em <>. [source,console] ---- @@ -419,10 +419,10 @@ $ git log --oneline --left-right HEAD...MERGE_HEAD > c3ffff1 Change text to 'hello mundo' ---- -That's a nice list of the six total commits involved, as well as which line of development each commit was on. +Essa é uma boa lista dos seis commits totais envolvidos, bem como em qual linha de desenvolvimento cada commit estava. -We can further simplify this though to give us much more specific context. -If we add the `--merge` option to `git log`, it will only show the commits in either side of the merge that touch a file that's currently conflicted. +No entanto, podemos simplificar ainda mais isso para nos dar um contexto muito mais específico. +Se adicionarmos a opção `--merge` ao `git log`, ele mostrará apenas os commits de ambos os lados do merge que tocam em um arquivo que está atualmente em conflito. [source,console] ---- @@ -431,15 +431,15 @@ $ git log --oneline --left-right --merge > c3ffff1 Change text to 'hello mundo' ---- -If you run that with the `-p` option instead, you get just the diffs to the file that ended up in conflict. -This can be *really* helpful in quickly giving you the context you need to help understand why something conflicts and how to more intelligently resolve it. +Se você rodar isso com a opção `-p` em vez disso, você obtém apenas os diffs do arquivo que acabou em conflito. +Isso pode ser *muito* útil para dar rapidamente a você o contexto necessário para ajudar a entender o porquê algo entrou em conflito e como resolvê-lo de forma mais inteligente. -===== Combined Diff Format +===== Formato Combinado de Diff (Combined Diff Format) -Since Git stages any merge results that are successful, when you run `git diff` while in a conflicted merge state, you only get what is currently still in conflict. -This can be helpful to see what you still have to resolve. +Como o Git faz stage de quaisquer resultados de merge que sejam bem-sucedidos, quando você roda `git diff` enquanto está em um estado de merge em conflito, você só obtém o que atualmente ainda está em conflito. +Isso pode ser útil para ver o que você ainda tem que resolver. -When you run `git diff` directly after a merge conflict, it will give you information in a rather unique diff output format. +Quando você roda `git diff` logo após um conflito de merge, ele lhe dará informações em um formato de saída de diff bastante único. [source,console] ---- @@ -462,13 +462,13 @@ index 0399cd5,59727f0..0000000 hello() ---- -The format is called "`Combined Diff`" and gives you two columns of data next to each line. -The first column shows you if that line is different (added or removed) between the "`ours`" branch and the file in your working directory and the second column does the same between the "`theirs`" branch and your working directory copy. +O formato é chamado "`Combined Diff`" (Diff Combinado) e lhe dá duas colunas de dados ao lado de cada linha. +A primeira coluna mostra se aquela linha é diferente (adicionada ou removida) entre a branch "`ours`" e o arquivo no seu diretório de trabalho e a segunda coluna faz o mesmo entre a branch "`theirs`" e a sua cópia do diretório de trabalho. -So in that example you can see that the `<<<<<<<` and `>>>>>>>` lines are in the working copy but were not in either side of the merge. -This makes sense because the merge tool stuck them in there for our context, but we're expected to remove them. +Então, nesse exemplo você pode ver que as linhas `<<<<<<<` e `>>>>>>>` estão na cópia de trabalho, mas não estavam em nenhum dos lados do merge. +Isso faz sentido porque a ferramenta de merge as colocou lá para nosso contexto, mas espera-se que nós as removamos. -If we resolve the conflict and run `git diff` again, we'll see the same thing, but it's a little more useful. +Se resolvermos o conflito e rodarmos `git diff` novamente, veremos a mesma coisa, mas é um pouco mais útil. [source,console] ---- @@ -490,11 +490,11 @@ index 0399cd5,59727f0..0000000 hello() ---- -This shows us that "`hola world`" was in our side but not in the working copy, that "`hello mundo`" was in their side but not in the working copy and finally that "`hola mundo`" was not in either side but is now in the working copy. -This can be useful to review before committing the resolution. +Isso nos mostra que "`hola world`" estava no nosso lado mas não na cópia de trabalho, que "`hello mundo`" estava no lado deles mas não na cópia de trabalho e finalmente que "`hola mundo`" não estava em nenhum dos lados mas está agora na cópia de trabalho. +Isso pode ser útil para revisar antes de comitar a resolução. -You can also get this from the `git log` for any merge to see how something was resolved after the fact. -Git will output this format if you run `git show` on a merge commit, or if you add a `--cc` option to a `git log -p` (which by default only shows patches for non-merge commits). +Você também pode obter isso a partir do `git log` para qualquer merge para ver como algo foi resolvido depois do fato. +O Git enviará este formato se você rodar `git show` em um commit de merge, ou se você adicionar uma opção `--cc` a um `git log -p` (que por padrão só mostra patches para commits que não são de merge). [source,console] ---- @@ -526,44 +526,44 @@ index 0399cd5,59727f0..e1d0799 ---- [[_undoing_merges]] -==== Undoing Merges +==== Desfazendo Merges -Now that you know how to create a merge commit, you'll probably make some by mistake. -One of the great things about working with Git is that it's okay to make mistakes, because it's possible (and in many cases easy) to fix them. +Agora que você sabe como criar um commit de merge, provavelmente você fará alguns por engano. +Uma das grandes coisas sobre trabalhar com o Git é que não há problema em cometer erros, porque é possível (e em muitos casos fácil) corrigi-los. -Merge commits are no different. -Let's say you started work on a topic branch, accidentally merged it into `master`, and now your commit history looks like this: +Commits de merge não são diferentes. +Digamos que você começou a trabalhar em uma branch de tópico, acidentalmente fez o merge dela na `master`, e agora o seu histórico de commits está assim: -.Accidental merge commit -image::images/undomerge-start.png[Accidental merge commit] +.Commit de merge acidental +image::images/undomerge-start.png[Commit de merge acidental] -There are two ways to approach this problem, depending on what your desired outcome is. +Existem duas maneiras de abordar este problema, dependendo de qual é o seu resultado desejado. -===== Fix the references +===== Consertar as referências -If the unwanted merge commit only exists on your local repository, the easiest and best solution is to move the branches so that they point where you want them to. -In most cases, if you follow the errant `git merge` with `git reset --hard HEAD~`, this will reset the branch pointers so they look like this: +Se o commit de merge indesejado existe apenas no seu repositório local, a solução mais fácil e melhor é mover as branches para que elas apontem para onde você quer que elas apontem. +Na maioria dos casos, se você seguir o `git merge` errôneo com `git reset --hard HEAD~`, isso resetará os ponteiros da branch para que eles fiquem assim: -.History after `git reset --hard HEAD~` -image::images/undomerge-reset.png[History after `git reset --hard HEAD~`] +.Histórico após `git reset --hard HEAD~` +image::images/undomerge-reset.png[Histórico após `git reset --hard HEAD~`] -We covered `reset` back in <>, so it shouldn't be too hard to figure out what's going on here. -Here's a quick refresher: `reset --hard` usually goes through three steps: +Nós cobrimos o `reset` anteriormente em <>, então não deve ser muito difícil descobrir o que está acontecendo aqui. +Aqui está uma rápida recapitulação: `reset --hard` geralmente passa por três passos: -. Move the branch HEAD points to. - In this case, we want to move `master` to where it was before the merge commit (`C6`). -. Make the index look like HEAD. -. Make the working directory look like the index. +. Move a branch para a qual o HEAD aponta. + Neste caso, queremos mover a `master` para onde ela estava antes do commit de merge (`C6`). +. Faz o index ficar igual ao HEAD. +. Faz o diretório de trabalho ficar igual ao index. -The downside of this approach is that it's rewriting history, which can be problematic with a shared repository. -Check out <> for more on what can happen; the short version is that if other people have the commits you're rewriting, you should probably avoid `reset`. -This approach also won't work if any other commits have been created since the merge; moving the refs would effectively lose those changes. +A desvantagem dessa abordagem é que ela está reescrevendo o histórico, o que pode ser problemático com um repositório compartilhado. +Dê uma olhada em <> para mais informações sobre o que pode acontecer; a versão curta é que se outras pessoas têm os commits que você está reescrevendo, você provavelmente deve evitar o `reset`. +Esta abordagem também não funcionará se quaisquer outros commits foram criados desde o merge; mover as referências efetivamente perderia essas alterações. [[_reverse_commit]] -===== Reverse the commit +===== Reverter o commit -If moving the branch pointers around isn't going to work for you, Git gives you the option of making a new commit which undoes all the changes from an existing one. -Git calls this operation a "`revert`", and in this particular scenario, you'd invoke it like this: +Se mover os ponteiros das branches não vai funcionar para você, o Git dá a opção de fazer um novo commit que desfaz todas as alterações de um existente. +O Git chama esta operação de "`revert`" (reverter), e neste cenário em particular, você a invocaria assim: [source,console] ---- @@ -571,17 +571,17 @@ $ git revert -m 1 HEAD [master b1d8379] Revert "Merge branch 'topic'" ---- -The `-m 1` flag indicates which parent is the "`mainline`" and should be kept. -When you invoke a merge into `HEAD` (`git merge topic`), the new commit has two parents: the first one is `HEAD` (`C6`), and the second is the tip of the branch being merged in (`C4`). -In this case, we want to undo all the changes introduced by merging in parent #2 (`C4`), while keeping all the content from parent #1 (`C6`). +A flag `-m 1` indica qual pai é a linha principal ("`mainline`") e deve ser mantido. +Quando você invoca um merge no `HEAD` (`git merge topic`), o novo commit tem dois pais: o primeiro é o `HEAD` (`C6`), e o segundo é a ponta (tip) da branch sendo mesclada (`C4`). +Neste caso, queremos desfazer todas as alterações introduzidas ao mesclar o pai #2 (`C4`), enquanto mantemos todo o conteúdo do pai #1 (`C6`). -The history with the revert commit looks like this: +O histórico com o commit revertido fica assim: -.History after `git revert -m 1` -image::images/undomerge-revert.png[History after `git revert -m 1`] +.Histórico após `git revert -m 1` +image::images/undomerge-revert.png[Histórico após `git revert -m 1`] -The new commit `^M` has exactly the same contents as `C6`, so starting from here it's as if the merge never happened, except that the now-unmerged commits are still in ``HEAD```'s history. -Git will get confused if you try to merge ``topic`` into ``master`` again: +O novo commit `^M` tem exatamente o mesmo conteúdo que `C6`, então começando daqui é como se o merge nunca tivesse acontecido, exceto que os commits agora não mesclados ainda estão no histórico do `HEAD`. +O Git ficará confuso se você tentar fazer o merge de ``topic`` em ``master`` novamente: [source,console] ---- @@ -589,13 +589,13 @@ $ git merge topic Already up-to-date. ---- -There's nothing in `topic` that isn't already reachable from `master`. -What's worse, if you add work to `topic` and merge again, Git will only bring in the changes _since_ the reverted merge: +Não há nada em `topic` que já não seja alcançável a partir de `master`. +O que é pior, se você adicionar trabalho ao `topic` e fizer merge novamente, o Git apenas trará as alterações _desde_ o merge revertido: -.History with a bad merge -image::images/undomerge-revert2.png[History with a bad merge] +.Histórico com um merge ruim +image::images/undomerge-revert2.png[Histórico com um merge ruim] -The best way around this is to un-revert the original merge, since now you want to bring in the changes that were reverted out, *then* create a new merge commit: +A melhor maneira de contornar isso é desfazer o reverso (un-revert) do merge original, já que agora você quer trazer as alterações que foram revertidas, *depois* criar um novo commit de merge: [source,console] ---- @@ -604,31 +604,31 @@ $ git revert ^M $ git merge topic ---- -.History after re-merging a reverted merge -image::images/undomerge-revert3.png[History after re-merging a reverted merge] +.Histórico após re-merging de um merge revertido +image::images/undomerge-revert3.png[Histórico após re-merging de um merge revertido] -In this example, `M` and `^M` cancel out. -`^^M` effectively merges in the changes from `C3` and `C4`, and `C8` merges in the changes from `C7`, so now `topic` is fully merged. +Neste exemplo, `M` e `^M` se cancelam. +`^^M` efetivamente faz o merge das alterações de `C3` e `C4`, e `C8` faz o merge das alterações de `C7`, então agora `topic` está totalmente mesclado. -==== Other Types of Merges +==== Outros Tipos de Merges -So far we've covered the normal merge of two branches, normally handled with what is called the "`recursive`" strategy of merging. -There are other ways to merge branches together however. -Let's cover a few of them quickly. +Até agora cobrimos o merge normal de duas branches, normalmente lidado com o que é chamado de estratégia "`recursive`" (recursiva) de merge. +No entanto, existem outras maneiras de fazer merge de branches. +Vamos cobrir algumas delas rapidamente. -===== Our or Theirs Preference +===== Preferência por Our ou Theirs -First of all, there is another useful thing we can do with the normal "`recursive`" mode of merging. -We've already seen the `ignore-all-space` and `ignore-space-change` options which are passed with a `-X` but we can also tell Git to favor one side or the other when it sees a conflict. +Antes de tudo, há outra coisa útil que podemos fazer com o modo "`recursive`" normal de merge. +Nós já vimos as opções `ignore-all-space` e `ignore-space-change` que são passadas com um `-X`, mas também podemos dizer ao Git para favorecer um lado ou outro quando ele vê um conflito. -By default, when Git sees a conflict between two branches being merged, it will add merge conflict markers into your code and mark the file as conflicted and let you resolve it. -If you would prefer for Git to simply choose a specific side and ignore the other side instead of letting you manually resolve the conflict, you can pass the `merge` command either a `-Xours` or `-Xtheirs`. +Por padrão, quando o Git vê um conflito entre duas branches sofrendo merge, ele adicionará marcadores de conflito de merge ao seu código e marcará o arquivo como em conflito e deixará que você o resolva. +Se você preferir que o Git simplesmente escolha um lado específico e ignore o outro lado em vez de permitir que você resolva manualmente o conflito, você pode passar ao comando `merge` um `-Xours` ou `-Xtheirs`. -If Git sees this, it will not add conflict markers. -Any differences that are mergeable, it will merge. -Any differences that conflict, it will simply choose the side you specify in whole, including binary files. +Se o Git vir isso, ele não adicionará marcadores de conflito. +Quaisquer diferenças que sejam mescláveis (mergeable), ele fará o merge. +Quaisquer diferenças que conflitem, ele simplesmente escolherá o lado que você especificar por inteiro, incluindo arquivos binários. -If we go back to the "`hello world`" example we were using before, we can see that merging in our branch causes conflicts. +Se voltarmos ao exemplo do "`hello world`" que estávamos usando antes, podemos ver que fazer o merge da nossa branch causa conflitos. [source,console] ---- @@ -639,7 +639,7 @@ Resolved 'hello.rb' using previous resolution. Automatic merge failed; fix conflicts and then commit the result. ---- -However if we run it with `-Xours` or `-Xtheirs` it does not. +No entanto, se rodarmos isso com `-Xours` ou `-Xtheirs`, ele não causa. [source,console] ---- @@ -652,17 +652,17 @@ Merge made by the 'recursive' strategy. create mode 100644 test.sh ---- -In that case, instead of getting conflict markers in the file with "`hello mundo`" on one side and "`hola world`" on the other, it will simply pick "`hola world`". -However, all the other non-conflicting changes on that branch are merged successfully in. +Nesse caso, em vez de obter marcadores de conflito no arquivo com "`hello mundo`" de um lado e "`hola world`" do outro, ele simplesmente escolherá "`hola world`". +No entanto, todas as outras alterações não conflitantes naquela branch são mescladas com sucesso. -This option can also be passed to the `git merge-file` command we saw earlier by running something like `git merge-file --ours` for individual file merges. +Esta opção também pode ser passada para o comando `git merge-file` que vimos anteriormente rodando algo como `git merge-file --ours` para merges de arquivos individuais. -If you want to do something like this but not have Git even try to merge changes from the other side in, there is a more draconian option, which is the "`ours`" merge _strategy_. -This is different from the "`ours`" recursive merge _option_. +Se você quer fazer algo parecido mas nem que o Git tente fazer o merge de alterações do outro lado, há uma opção mais draconiana, que é a _estratégia_ de merge "`ours`". +Isso é diferente da _opção_ recursiva de merge "`ours`". -This will basically do a fake merge. -It will record a new merge commit with both branches as parents, but it will not even look at the branch you're merging in. -It will simply record as the result of the merge the exact code in your current branch. +Isso basicamente fará um merge falso. +Ele gravará um novo commit de merge com ambas as branches como pais, mas nem olhará para a branch que você está fazendo merge. +Ele simplesmente gravará como o resultado do merge o código exato da sua branch atual. [source,console] ---- @@ -672,11 +672,11 @@ $ git diff HEAD HEAD~ $ ---- -You can see that there is no difference between the branch we were on and the result of the merge. +Você pode ver que não há diferença entre a branch em que estávamos e o resultado do merge. -This can often be useful to basically trick Git into thinking that a branch is already merged when doing a merge later on. -For example, say you branched off a `release` branch and have done some work on it that you will want to merge back into your `master` branch at some point. -In the meantime some bugfix on `master` needs to be backported into your `release` branch. -You can merge the bugfix branch into the `release` branch and also `merge -s ours` the same branch into your `master` branch (even though the fix is already there) so when you later merge the `release` branch again, there are no conflicts from the bugfix. +Isso muitas vezes pode ser útil para basicamente enganar o Git a pensar que uma branch já foi mesclada ao fazer um merge mais tarde. +Por exemplo, digamos que você ramificou de uma branch `release` e fez algum trabalho nela que você vai querer fazer o merge de volta na sua branch `master` em algum momento. +Enquanto isso, algum bugfix na `master` precisa ser feito backport para a sua branch `release`. +Você pode fazer o merge da branch do bugfix na branch `release` e também `merge -s ours` na mesma branch para a sua branch `master` (embora a correção já esteja lá) de modo que quando mais tarde você fizer o merge da branch `release` de novo, não haja conflitos do bugfix. include::subtree-merges.asc[] diff --git a/book/07-git-tools/sections/bundling.asc b/book/07-git-tools/sections/bundling.asc index 79cb1b8a..6598b895 100644 --- a/book/07-git-tools/sections/bundling.asc +++ b/book/07-git-tools/sections/bundling.asc @@ -1,20 +1,20 @@ [[_bundling]] -=== Bundling +=== Empacotando (Bundling) -Though we've covered the common ways to transfer Git data over a network (HTTP, SSH, etc), there is actually one more way to do so that is not commonly used but can actually be quite useful. +Apesar de termos abordado as maneiras comuns de transferir dados do Git em uma rede (HTTP, SSH, etc), na verdade há uma maneira de mais de fazê-lo que não é muito usada mas que pode ser bastante útil. -Git is capable of "`bundling`" its data into a single file. -This can be useful in various scenarios. -Maybe your network is down and you want to send changes to your co-workers. -Perhaps you're working somewhere offsite and don't have access to the local network for security reasons. -Maybe your wireless/ethernet card just broke. -Maybe you don't have access to a shared server for the moment, you want to email someone updates and you don't want to transfer 40 commits via `format-patch`. +O Git é capaz de "`empacotar`" (bundle) os seus dados em um único arquivo. +Isso pode ser útil em vários cenários. +Talvez a sua rede caiu e você quer enviar alterações para os seus colegas. +Pode ser que você esteja trabalhando externo em algum lugar e não tem acesso à rede local por motivos de segurança. +Talvez sua placa de rede wireless/ethernet simplesmente quebrou. +Talvez você não tenha acesso a um servidor compartilhado no momento, quer mandar atualizações por email para alguém e não quer ter que transferir 40 commits por `format-patch`. -This is where the `git bundle` command can be helpful. -The `bundle` command will package up everything that would normally be pushed over the wire with a `git push` command into a binary file that you can email to someone or put on a flash drive, then unbundle into another repository. +É aí que o comando `git bundle` pode ser útil. +O comando `bundle` empacotará tudo que seria normalmente mandado (pushed) pela rede com um comando `git push` para dentro de um arquivo binário que você pode mandar por email para alguém ou pôr em um pen drive, para depois desempacotar (unbundle) em um outro repositório. -Let's see a simple example. -Let's say you have a repository with two commits: +Vejamos um exemplo simples. +Digamos que você tem um repositório com dois commits: [source,console] ---- @@ -32,7 +32,7 @@ Date: Wed Mar 10 07:34:01 2010 -0800 First commit ---- -If you want to send that repository to someone and you don't have access to a repository to push to, or simply don't want to set one up, you can bundle it with `git bundle create`. +Se você quiser enviar aquele repositório para alguém e você não tiver acesso a um repositório para o qual fazer o push, ou simplesmente não quiser configurar um, você pode empacotá-lo com `git bundle create`. [source,console] ---- @@ -44,14 +44,14 @@ Writing objects: 100% (6/6), 441 bytes, done. Total 6 (delta 0), reused 0 (delta 0) ---- -Now you have a file named `repo.bundle` that has all the data needed to re-create the repository's `master` branch. -With the `bundle` command you need to list out every reference or specific range of commits that you want to be included. -If you intend for this to be cloned somewhere else, you should add HEAD as a reference as well as we've done here. +Agora você tem um arquivo chamado `repo.bundle` que tem todos os dados necessários para recriar a branch `master` do repositório. +Com o comando `bundle` você precisa listar todas as referências ou uma gama específica de commits que você quer que sejam incluídos. +Se você pretende que isto seja clonado em algum lugar, você deveria adicionar o HEAD como referência, bem como nós fizemos aqui. -You can email this `repo.bundle` file to someone else, or put it on a USB drive and walk it over. +Você pode mandar este arquivo `repo.bundle` por email para alguém, ou pô-lo em um pendrive e levá-lo pessoalmente. -On the other side, say you are sent this `repo.bundle` file and want to work on the project. -You can clone from the binary file into a directory, much like you would from a URL. +Na outra ponta, digamos que te enviem este arquivo `repo.bundle` e você queira trabalhar no projeto. +Você pode clonar a partir do arquivo binário para um diretório, mais ou menos igual a quando você faz a partir de uma URL. [source,console] ---- @@ -64,9 +64,9 @@ $ git log --oneline b1ec324 First commit ---- -If you don't include HEAD in the references, you have to also specify `-b master` or whatever branch is included because otherwise it won't know what branch to check out. +Se você não incluir o HEAD nas referências, você tem também que especificar `-b master` ou seja qual for a branch incluída porque senão ele não saberá qual branch utilizar no check out. -Now let's say you do three commits on it and want to send the new commits back via a bundle on a USB stick or email. +Agora digamos que você faça três commits nisso e queira mandar os novos commits de volta através de um bundle em um pen drive ou por email. [source,console] ---- @@ -78,14 +78,14 @@ c99cf5b Fourth commit - second repo b1ec324 First commit ---- -First we need to determine the range of commits we want to include in the bundle. -Unlike the network protocols which figure out the minimum set of data to transfer over the network for us, we'll have to figure this out manually. -Now, you could just do the same thing and bundle the entire repository, which will work, but it's better to just bundle up the difference - just the three commits we just made locally. +Primeiro nós precisamos determinar a gama de commits que queremos incluir no bundle. +Diferente dos protocolos de rede, os quais calculam por nós qual é o conjunto mínimo de dados a se transferir pela rede, nós teremos de calcular isso manualmente. +Você pode apenas fazer a mesma coisa e empacotar (bundle) o repositório inteiro, o que vai funcionar, mas é melhor empacotar apenas a diferença - somente os três commits que acabamos de fazer localmente. -In order to do that, you'll have to calculate the difference. -As we described in <>, you can specify a range of commits in a number of ways. -To get the three commits that we have in our `master` branch that weren't in the branch we originally cloned, we can use something like `origin/master..master` or `master ^origin/master`. -You can test that with the `log` command. +A fim de fazer isso, você terá que calcular a diferença. +Conforme descrevemos em <>, você pode especificar uma gama de commits de uma série de formas. +Para obtermos os três commits que temos na nossa branch `master` e que não estavam na branch que clonamos originalmente, nós podemos usar algo como `origin/master..master` ou `master ^origin/master`. +Você pode testar isso com o comando `log`. [source,console] ---- @@ -95,8 +95,8 @@ c99cf5b Fourth commit - second repo 7011d3d Third commit - second repo ---- -So now that we have the list of commits we want to include in the bundle, let's bundle them up. -We do that with the `git bundle create` command, giving it a filename we want our bundle to be and the range of commits we want to go into it. +Então, agora que temos a lista de commits que queremos incluir no bundle, vamos empacotá-los. +Nós fazemos isso com o comando `git bundle create`, dando a ele um nome de arquivo que queremos que seja o nosso bundle e a gama de commits que queremos por ali dentro. [source,console] ---- @@ -108,11 +108,11 @@ Writing objects: 100% (9/9), 775 bytes, done. Total 9 (delta 0), reused 0 (delta 0) ---- -Now we have a `commits.bundle` file in our directory. -If we take that and send it to our partner, she can then import it into the original repository, even if more work has been done there in the meantime. +Agora nós temos um arquivo `commits.bundle` no nosso diretório. +Se pegarmos isso e mandarmos para a nossa colega, ela então poderá importar para o repositório original, mesmo se mais trabalho tiver sido feito por lá nesse ínterim. -When she gets the bundle, she can inspect it to see what it contains before she imports it into her repository. -The first command is the `bundle verify` command that will make sure the file is actually a valid Git bundle and that you have all the necessary ancestors to reconstitute it properly. +Quando ela receber o bundle, ela pode inspecioná-lo para ver o que ele contém antes que ela o importe para o repositório dela. +O primeiro comando é o comando `bundle verify` que irá confirmar se o arquivo é realmente um bundle válido do Git e se você tem todos os ancestrais necessários para reconstituí-lo de forma correta. [source,console] ---- @@ -124,8 +124,8 @@ The bundle requires these 1 ref ../commits.bundle is okay ---- -If the bundler had created a bundle of just the last two commits they had done, rather than all three, the original repository would not be able to import it, since it is missing requisite history. -The `verify` command would have looked like this instead: +Se a pessoa tivesse criado um bundle apenas com os dois últimos commits que ela tinha feito, ao invés de todos os três, o repositório original não seria capaz de importá-lo, posto que estaria faltando histórico que lhe era requisito. +O comando `verify` ter-se-ia parecido mais com isso, pelo contrário: [source,console] ---- @@ -134,8 +134,8 @@ error: Repository lacks these prerequisite commits: error: 7011d3d8fc200abe0ad561c011c3852a4b7bbe95 Third commit - second repo ---- -However, our first bundle is valid, so we can fetch in commits from it. -If you want to see what branches are in the bundle that can be imported, there is also a command to just list the heads: +Entretanto, nosso primeiro bundle é válido, de modo que nós podemos fazer o fetch dos commits dali. +Se você quer ver quais branches no bundle podem ser importadas, tem também um comando só pra listar os heads: [source,console] ---- @@ -143,9 +143,9 @@ $ git bundle list-heads ../commits.bundle 71b84daaf49abed142a373b6e5c59a22dc6560dc refs/heads/master ---- -The `verify` sub-command will tell you the heads as well. -The point is to see what can be pulled in, so you can use the `fetch` or `pull` commands to import commits from this bundle. -Here we'll fetch the `master` branch of the bundle to a branch named `other-master` in our repository: +O subcomando `verify` também te contará os heads. +O ponto é ver o que pode ser sofrer um pull (pulled in), de forma que você possa usar os comandos `fetch` ou `pull` para importar commits deste bundle. +Aqui nós faremos o fetch da branch `master` do bundle, destinando a uma branch chamada `other-master` em nosso repositório: [source,console] ---- @@ -154,7 +154,7 @@ From ../commits.bundle * [new branch] master -> other-master ---- -Now we can see that we have the imported commits on the `other-master` branch as well as any commits we've done in the meantime in our own `master` branch. +Agora podemos ver que nós temos os commits importados na branch `other-master` assim como quaisquer commits que tenhamos feito nesse meio tempo em nossa própria branch `master`. [source,console] ---- @@ -168,4 +168,4 @@ $ git log --oneline --decorate --graph --all * b1ec324 First commit ---- -So, `git bundle` can be really useful for sharing or doing network-type operations when you don't have the proper network or shared repository to do so. +Sendo assim, o `git bundle` pode ser bastante útil para se compartilhar ou executar operações do tipo-rede quando você não dispõe da rede adequada ou de um repositório compartilhado para fazê-lo. diff --git a/book/07-git-tools/sections/credentials.asc b/book/07-git-tools/sections/credentials.asc index 7c7bc6ed..7538dda5 100644 --- a/book/07-git-tools/sections/credentials.asc +++ b/book/07-git-tools/sections/credentials.asc @@ -1,50 +1,50 @@ [[_credential_caching]] -=== Credential Storage +=== Armazenamento de Credenciais (((credentials))) (((git commands, credential))) -If you use the SSH transport for connecting to remotes, it's possible for you to have a key without a passphrase, which allows you to securely transfer data without typing in your username and password. -However, this isn't possible with the HTTP protocols -- every connection needs a username and password. -This gets even harder for systems with two-factor authentication, where the token you use for a password is randomly generated and unpronounceable. - -Fortunately, Git has a credentials system that can help with this. -Git has a few options provided in the box: - -* The default is not to cache at all. - Every connection will prompt you for your username and password. -* The "`cache`" mode keeps credentials in memory for a certain period of time. - None of the passwords are ever stored on disk, and they are purged from the cache after 15 minutes. -* The "`store`" mode saves the credentials to a plain-text file on disk, and they never expire. - This means that until you change your password for the Git host, you won't ever have to type in your credentials again. - The downside of this approach is that your passwords are stored in cleartext in a plain file in your home directory. -* If you're using macOS, Git comes with an "`osxkeychain`" mode, which caches credentials in the secure keychain that's attached to your system account. - This method stores the credentials on disk, and they never expire, but they're encrypted with the same system that stores HTTPS certificates and Safari auto-fills. -* If you're using Windows, you can enable the *Git Credential Manager* feature when installing https://gitforwindows.org/[Git for Windows] or separately install https://github.com/git-ecosystem/git-credential-manager/releases/latest[the latest GCM] as a standalone service. - This is similar to the "`osxkeychain`" helper described above, but uses the Windows Credential Store to control sensitive information. - It can also serve credentials to WSL1 or WSL2. - See https://github.com/git-ecosystem/git-credential-manager#readme[GCM Install Instructions] for more information. - -You can choose one of these methods by setting a Git configuration value: +Se você usa o transporte SSH para se conectar a remotes, pode ter uma chave sem frase secreta, o que permite transferir dados com segurança sem digitar seu nome de usuário e sua senha. +No entanto, isso não é possível com os protocolos HTTP – toda conexão exige um nome de usuário e uma senha. +Isso se torna ainda mais difícil em sistemas com autenticação de dois fatores, nos quais o token usado como senha é gerado aleatoriamente e é impronunciável. + +Felizmente, o Git possui um sistema de credenciais que pode ajudar com isso. +O Git oferece algumas opções prontas para uso: + +* O padrão é não armazenar nada em cache. + Toda conexão solicitará seu nome de usuário e sua senha. +* O modo "`cache`" mantém as credenciais na memória por determinado período. + Nenhuma senha é armazenada em disco, e elas são removidas do cache depois de 15 minutos. +* O modo "`store`" salva as credenciais em um arquivo de texto puro no disco, e elas nunca expiram. + Isso significa que, enquanto você não alterar sua senha no host Git, nunca mais precisará digitar suas credenciais. + A desvantagem dessa abordagem é que suas senhas ficam armazenadas sem criptografia em um arquivo de texto puro no seu diretório pessoal. +* Se você usa macOS, o Git inclui um modo "`osxkeychain`", que armazena as credenciais no chaveiro seguro associado à sua conta do sistema. + Esse método armazena as credenciais em disco, e elas nunca expiram, mas são criptografadas pelo mesmo sistema que armazena certificados HTTPS e dados de preenchimento automático do Safari. +* Se você usa Windows, pode habilitar o recurso *Git Credential Manager* ao instalar o https://gitforwindows.org/[Git for Windows] ou instalar separadamente https://github.com/git-ecosystem/git-credential-manager/releases/latest[a versão mais recente do GCM] como um serviço independente. + Ele é semelhante ao helper "`osxkeychain`" descrito acima, mas usa o Gerenciador de Credenciais do Windows para controlar informações confidenciais. + Ele também pode fornecer credenciais ao WSL1 ou WSL2. + Consulte as https://github.com/git-ecosystem/git-credential-manager#readme[instruções de instalação do GCM] para obter mais informações. + +Você pode escolher um desses métodos definindo um valor de configuração do Git: [source,console] ---- $ git config --global credential.helper cache ---- -Some of these helpers have options. -The "`store`" helper can take a `--file ` argument, which customizes where the plain-text file is saved (the default is `~/.git-credentials`). -The "`cache`" helper accepts the `--timeout ` option, which changes the amount of time its daemon is kept running (the default is "`900`", or 15 minutes). -Here's an example of how you'd configure the "`store`" helper with a custom file name: +Alguns desses helpers possuem opções. +O helper "`store`" aceita um argumento `--file `, que personaliza o local em que o arquivo de texto puro é salvo (o padrão é `~/.git-credentials`). +O helper "`cache`" aceita a opção `--timeout `, que altera o tempo durante o qual seu daemon permanece em execução (o padrão é "`900`", ou 15 minutos). +Este é um exemplo de como configurar o helper "`store`" com um nome de arquivo personalizado: [source,console] ---- $ git config --global credential.helper 'store --file ~/.my-credentials' ---- -Git even allows you to configure several helpers. -When looking for credentials for a particular host, Git will query them in order, and stop after the first answer is provided. -When saving credentials, Git will send the username and password to *all* of the helpers in the list, and they can choose what to do with them. -Here's what a `.gitconfig` would look like if you had a credentials file on a thumb drive, but wanted to use the in-memory cache to save some typing if the drive isn't plugged in: +O Git permite até mesmo configurar vários helpers. +Ao procurar credenciais para um host específico, o Git consultará os helpers em ordem e parará assim que receber a primeira resposta. +Ao salvar credenciais, o Git enviará o nome de usuário e a senha para *todos* os helpers da lista, e cada um poderá decidir o que fazer com eles. +Este é o aspecto de um arquivo `.gitconfig` caso você tivesse um arquivo de credenciais em um pen drive, mas quisesse usar o cache em memória para evitar digitação quando o dispositivo não estivesse conectado: [source,ini] ---- @@ -53,14 +53,14 @@ Here's what a `.gitconfig` would look like if you had a credentials file on a th helper = cache --timeout 30000 ---- -==== Under the Hood +==== Por Baixo dos Panos -How does this all work? -Git's root command for the credential-helper system is `git credential`, which takes a command as an argument, and then more input through stdin. +Como tudo isso funciona? +O comando principal do Git para o sistema de helpers de credenciais é `git credential`, que recebe um comando como argumento e mais dados pela entrada padrão. -This might be easier to understand with an example. -Let's say that a credential helper has been configured, and the helper has stored credentials for `mygithost`. -Here's a session that uses the "`fill`" command, which is invoked when Git is trying to find credentials for a host: +Talvez seja mais fácil entender com um exemplo. +Suponha que um helper de credenciais tenha sido configurado e armazenado credenciais para `mygithost`. +Esta sessão usa o comando "`fill`", invocado quando o Git tenta encontrar credenciais para um host: [source,console] ---- @@ -84,39 +84,39 @@ username=bob password=s3cre7 ---- -<1> This is the command line that initiates the interaction. -<2> Git-credential is then waiting for input on stdin. - We provide it with the things we know: the protocol and hostname. -<3> A blank line indicates that the input is complete, and the credential system should answer with what it knows. -<4> Git-credential then takes over, and writes to stdout with the bits of information it found. -<5> If credentials are not found, Git asks the user for the username and password, and provides them back to the invoking stdout (here they're attached to the same console). +<1> Esta é a linha de comando que inicia a interação. +<2> Em seguida, Git-credential aguarda dados na entrada padrão. + Fornecemos as informações que conhecemos: o protocolo e o nome do host. +<3> Uma linha em branco indica que a entrada terminou e que o sistema de credenciais deve responder com o que sabe. +<4> Então, Git-credential assume o controle e grava na saída padrão as informações que encontrou. +<5> Se nenhuma credencial for encontrada, o Git solicita ao usuário o nome de usuário e a senha e os devolve na saída padrão do processo que o invocou (aqui, ela está associada ao mesmo console). -The credential system is actually invoking a program that's separate from Git itself; which one and how depends on the `credential.helper` configuration value. -There are several forms it can take: +Na verdade, o sistema de credenciais invoca um programa separado do próprio Git; qual programa e de que maneira dependem do valor de configuração `credential.helper`. +Ele pode assumir várias formas: [options="header"] |====== -| Configuration Value | Behavior -| `foo` | Runs `git-credential-foo` -| `foo -a --opt=bcd` | Runs `git-credential-foo -a --opt=bcd` -| `/absolute/path/foo -xyz` | Runs `/absolute/path/foo -xyz` -| `!f() { echo "password=s3cre7"; }; f` | Code after `!` evaluated in shell +| Valor de Configuração | Comportamento +| `foo` | Executa `git-credential-foo` +| `foo -a --opt=bcd` | Executa `git-credential-foo -a --opt=bcd` +| `/absolute/path/foo -xyz` | Executa `/absolute/path/foo -xyz` +| `!f() { echo "password=s3cre7"; }; f` | O código depois de `!` é avaliado no shell |====== -So the helpers described above are actually named `git-credential-cache`, `git-credential-store`, and so on, and we can configure them to take command-line arguments. -The general form for this is "`git-credential-foo [args] .`" -The stdin/stdout protocol is the same as git-credential, but they use a slightly different set of actions: +Portanto, os helpers descritos acima na verdade se chamam `git-credential-cache`, `git-credential-store` e assim por diante, e podemos configurá-los para receber argumentos de linha de comando. +A forma geral é "`git-credential-foo [args] .`" +O protocolo de entrada e saída padrão é o mesmo de git-credential, mas esses helpers usam um conjunto de ações ligeiramente diferente: -* `get` is a request for a username/password pair. -* `store` is a request to save a set of credentials in this helper's memory. -* `erase` purge the credentials for the given properties from this helper's memory. +* `get` é uma solicitação de um par de nome de usuário e senha. +* `store` é uma solicitação para salvar um conjunto de credenciais na memória desse helper. +* `erase` remove da memória desse helper as credenciais correspondentes às propriedades fornecidas. -For the `store` and `erase` actions, no response is required (Git ignores it anyway). -For the `get` action, however, Git is very interested in what the helper has to say. -If the helper doesn't know anything useful, it can simply exit with no output, but if it does know, it should augment the provided information with the information it has stored. -The output is treated like a series of assignment statements; anything provided will replace what Git already knows. +Para as ações `store` e `erase`, nenhuma resposta é necessária (o Git a ignora de qualquer forma). +Para a ação `get`, porém, o Git se interessa muito pelo que o helper tem a dizer. +Se o helper não souber nada útil, poderá simplesmente encerrar sem produzir saída; se souber, deverá complementar as informações fornecidas com as que armazenou. +A saída é tratada como uma série de atribuições; tudo o que for fornecido substituirá o que o Git já sabe. -Here's the same example from above, but skipping `git-credential` and going straight for `git-credential-store`: +Este é o mesmo exemplo anterior, mas sem passar por `git-credential` e usando diretamente `git-credential-store`: [source,console] ---- @@ -133,52 +133,52 @@ username=bob <3> password=s3cre7 ---- -<1> Here we tell `git-credential-store` to save some credentials: the username "`bob`" and the password "`s3cre7`" are to be used when `https://mygithost` is accessed. -<2> Now we'll retrieve those credentials. - We provide the parts of the connection we already know (`https://mygithost`), and an empty line. -<3> `git-credential-store` replies with the username and password we stored above. +<1> Aqui instruímos `git-credential-store` a salvar algumas credenciais: o nome de usuário "`bob`" e a senha "`s3cre7`" devem ser usados quando `https://mygithost` for acessado. +<2> Agora recuperaremos essas credenciais. + Fornecemos as partes da conexão que já conhecemos (`https://mygithost`) e uma linha em branco. +<3> `git-credential-store` responde com o nome de usuário e a senha que armazenamos acima. -Here's what the `~/git.store` file looks like: +Este é o conteúdo do arquivo `~/git.store`: [source,ini] ---- https://bob:s3cre7@mygithost ---- -It's just a series of lines, each of which contains a credential-decorated URL. -The `osxkeychain` and `wincred` helpers use the native format of their backing stores, while `cache` uses its own in-memory format (which no other process can read). +Ele é apenas uma série de linhas, cada uma contendo uma URL acompanhada de credenciais. +Os helpers `osxkeychain` e `wincred` usam o formato nativo dos armazenamentos nos quais se apoiam, enquanto `cache` usa seu próprio formato em memória (que nenhum outro processo consegue ler). -==== A Custom Credential Cache +==== Um Cache de Credenciais Personalizado -Given that `git-credential-store` and friends are separate programs from Git, it's not much of a leap to realize that _any_ program can be a Git credential helper. -The helpers provided by Git cover many common use cases, but not all. -For example, let's say your team has some credentials that are shared with the entire team, perhaps for deployment. -These are stored in a shared directory, but you don't want to copy them to your own credential store, because they change often. -None of the existing helpers cover this case; let's see what it would take to write our own. -There are several key features this program needs to have: +Como `git-credential-store` e programas semelhantes são separados do Git, não é difícil perceber que _qualquer_ programa pode ser um helper de credenciais do Git. +Os helpers fornecidos pelo Git atendem a muitos casos de uso comuns, mas não a todos. +Por exemplo, suponha que sua equipe tenha credenciais compartilhadas por todos, talvez para fazer deploy. +Elas ficam armazenadas em um diretório compartilhado, mas você não quer copiá-las para seu próprio armazenamento de credenciais, pois elas mudam com frequência. +Nenhum dos helpers existentes atende a esse caso; vejamos o que seria necessário para criar o nosso. +Esse programa precisa ter várias características importantes: -. The only action we need to pay attention to is `get`; `store` and `erase` are write operations, so we'll just exit cleanly when they're received. -. The file format of the shared-credential file is the same as that used by `git-credential-store`. -. The location of that file is fairly standard, but we should allow the user to pass a custom path just in case. +. A única ação à qual precisamos prestar atenção é `get`; `store` e `erase` são operações de escrita, portanto simplesmente encerraremos sem erros ao recebê-las. +. O formato do arquivo de credenciais compartilhadas é o mesmo usado por `git-credential-store`. +. A localização desse arquivo é bastante padronizada, mas devemos permitir que o usuário passe um caminho personalizado por precaução. -Once again, we'll write this extension in Ruby, but any language will work so long as Git can execute the finished product. -Here's the full source code of our new credential helper: +Mais uma vez, escreveremos essa extensão em Ruby, mas qualquer linguagem funcionará, desde que o Git possa executar o produto final. +Este é o código-fonte completo do nosso novo helper de credenciais: [source,ruby] ---- include::../git-credential-read-only[] ---- -<1> Here we parse the command-line options, allowing the user to specify the input file. - The default is `~/.git-credentials`. -<2> This program only responds if the action is `get` and the backing-store file exists. -<3> This loop reads from stdin until the first blank line is reached. - The inputs are stored in the `known` hash for later reference. -<4> This loop reads the contents of the storage file, looking for matches. - If the protocol, host, and username from `known` match this line, the program prints the results to stdout and exits. +<1> Aqui analisamos as opções da linha de comando, permitindo que o usuário especifique o arquivo de entrada. + O padrão é `~/.git-credentials`. +<2> Esse programa só responde se a ação for `get` e o arquivo de armazenamento existir. +<3> Esse laço lê a entrada padrão até encontrar a primeira linha em branco. + As entradas são armazenadas no hash `known` para consulta posterior. +<4> Esse laço lê o conteúdo do arquivo de armazenamento em busca de correspondências. + Se o protocolo, o host e o nome de usuário de `known` corresponderem à linha, o programa imprimirá os resultados na saída padrão e encerrará. -We'll save our helper as `git-credential-read-only`, put it somewhere in our `PATH` and mark it executable. -Here's what an interactive session looks like: +Salvaremos nosso helper como `git-credential-read-only`, colocaremos o arquivo em algum local do `PATH` e o marcaremos como executável. +Esta é a aparência de uma sessão interativa: [source,console] ---- @@ -193,11 +193,11 @@ username=bob password=s3cre7 ---- -Since its name starts with "`git-`", we can use the simple syntax for the configuration value: +Como seu nome começa com "`git-`", podemos usar a sintaxe simples no valor de configuração: [source,console] ---- $ git config --global credential.helper 'read-only --file /mnt/shared/creds' ---- -As you can see, extending this system is pretty straightforward, and can solve some common problems for you and your team. +Como você pode ver, estender esse sistema é bastante simples e pode resolver alguns problemas comuns para você e sua equipe. diff --git a/book/07-git-tools/sections/debugging.asc b/book/07-git-tools/sections/debugging.asc index dd615c1c..df05a027 100644 --- a/book/07-git-tools/sections/debugging.asc +++ b/book/07-git-tools/sections/debugging.asc @@ -1,16 +1,16 @@ -=== Debugging with Git +=== Depurando com Git -In addition to being primarily for version control, Git also provides a couple commands to help you debug your source code projects. -Because Git is designed to handle nearly any type of content, these tools are pretty generic, but they can often help you hunt for a bug or culprit when things go wrong. +Além de ser principalmente para controle de versão, o Git também fornece alguns comandos para ajudá-lo a depurar seus projetos de código-fonte. +Como o Git foi projetado para lidar com quase qualquer tipo de conteúdo, essas ferramentas são bastante genéricas, mas muitas vezes podem ajudá-lo a caçar um bug ou culpado quando as coisas dão errado. [[_file_annotation]] -==== File Annotation +==== Anotação de Arquivo -If you track down a bug in your code and want to know when it was introduced and why, file annotation is often your best tool. -It shows you what commit was the last to modify each line of any file. -So if you see that a method in your code is buggy, you can annotate the file with `git blame` to determine which commit was responsible for the introduction of that line. +Se você rastrear um bug no seu código e quiser saber quando ele foi introduzido e por que, a anotação de arquivo (file annotation) é frequentemente sua melhor ferramenta. +Ela mostra qual commit foi o último a modificar cada linha de qualquer arquivo. +Então, se você ver que um método no seu código está com bugs, você pode anotar o arquivo com `git blame` para determinar qual commit foi responsável pela introdução daquela linha. -The following example uses `git blame` to determine which commit and committer was responsible for lines in the top-level Linux kernel `Makefile` and, further, uses the `-L` option to restrict the output of the annotation to lines 69 through 82 of that file: +O exemplo seguinte usa `git blame` para determinar qual commit e committer foi responsável pelas linhas no `Makefile` de nível superior do kernel do Linux e, além disso, usa a opção `-L` para restringir a saída da anotação às linhas 69 a 82 daquele arquivo: [source,console] ---- @@ -31,18 +31,18 @@ b8b0618cf6fab (Cheng Renquan 2009-05-26 16:03:07 +0800 70) KBUILD_VERBOSE = $ 066b7ed955808 (Michal Marek 2014-07-04 14:29:30 +0200 82) endif ---- -Notice that the first field is the partial SHA-1 of the commit that last modified that line. -The next two fields are values extracted from that commit -- the author name and the authored date of that commit -- so you can easily see who modified that line and when. -After that come the line number and the content of the file. -Also note the `^1da177e4c3f4` commit lines, where the `^` prefix designates lines that were introduced in the repository's initial commit and have remained unchanged ever since. -This is a tad confusing, because now you've seen at least three different ways that Git uses the `^` to modify a commit SHA-1, but that is what it means here. +Note que o primeiro campo é o SHA-1 parcial do commit que modificou aquela linha por último. +Os próximos dois campos são valores extraídos daquele commit -- o nome do autor e a data de autoria daquele commit -- para que você possa ver facilmente quem modificou aquela linha e quando. +Depois disso vêm o número da linha e o conteúdo do arquivo. +Note também as linhas de commit `^1da177e4c3f4`, onde o prefixo `^` designa linhas que foram introduzidas no commit inicial do repositório e permaneceram inalteradas desde então. +Isso é um pouco confuso, porque agora você já viu pelo menos três maneiras diferentes que o Git usa o `^` para modificar um SHA-1 de commit, mas é isso o que ele significa aqui. -Another cool thing about Git is that it doesn't track file renames explicitly. -It records the snapshots and then tries to figure out what was renamed implicitly, after the fact. -One of the interesting features of this is that you can ask it to figure out all sorts of code movement as well. -If you pass `-C` to `git blame`, Git analyzes the file you're annotating and tries to figure out where snippets of code within it originally came from if they were copied from elsewhere. -For example, say you are refactoring a file named `GITServerHandler.m` into multiple files, one of which is `GITPackUpload.m`. -By blaming `GITPackUpload.m` with the `-C` option, you can see where sections of the code originally came from: +Outra coisa legal sobre o Git é que ele não rastreia renomeações de arquivos explicitamente. +Ele grava os snapshots e depois tenta descobrir o que foi renomeado implicitamente, após o fato. +Uma das características interessantes disso é que você também pode pedir a ele para descobrir todos os tipos de movimento de código. +Se você passar `-C` para o `git blame`, o Git analisa o arquivo que você está anotando e tenta descobrir de onde os trechos de código nele originalmente vieram, caso tenham sido copiados de outro lugar. +Por exemplo, digamos que você está refatorando um arquivo chamado `GITServerHandler.m` em vários arquivos, um dos quais é `GITPackUpload.m`. +Anotando o `GITPackUpload.m` com a opção `-C`, você pode ver de onde originalmente vieram seções do código: [source,console] ---- @@ -62,22 +62,22 @@ ad11ac80 GITPackUpload.m (Scott 2009-03-24 150) 56ef2caf GITServerHandler.m (Scott 2009-01-05 153) ---- -This is really useful. -Normally, you get as the original commit the commit where you copied the code over, because that is the first time you touched those lines in this file. -Git tells you the original commit where you wrote those lines, even if it was in another file. +Isso é realmente útil. +Normalmente, você obtém como o commit original o commit onde você copiou o código para lá, porque essa é a primeira vez que você tocou nessas linhas neste arquivo. +O Git diz qual foi o commit original em que você escreveu essas linhas, mesmo que isso tenha sido em outro arquivo. [[_binary_search]] -==== Binary Search +==== Pesquisa Binária (Binary Search) -Annotating a file helps if you know where the issue is to begin with. -If you don't know what is breaking, and there have been dozens or hundreds of commits since the last state where you know the code worked, you'll likely turn to `git bisect` for help. -The `bisect` command does a binary search through your commit history to help you identify as quickly as possible which commit introduced an issue. +Anotar um arquivo ajuda se você sabe, de início, onde o problema está. +Se você não sabe o que está quebrando, e houveram dezenas ou centenas de commits desde o último estado em que você sabe que o código funcionou, você provavelmente vai recorrer ao `git bisect` por ajuda. +O comando `bisect` faz uma pesquisa binária por todo o seu histórico de commits para ajudá-lo a identificar, o mais rápido possível, qual commit introduziu um problema. -Let's say you just pushed out a release of your code to a production environment, you're getting bug reports about something that wasn't happening in your development environment, and you can't imagine why the code is doing that. -You go back to your code, and it turns out you can reproduce the issue, but you can't figure out what is going wrong. -You can _bisect_ the code to find out. -First you run `git bisect start` to get things going, and then you use `git bisect bad` to tell the system that the current commit you're on is broken. -Then, you must tell bisect when the last known good state was, using `git bisect good `: +Digamos que você acabou de dar push de uma release do seu código para um ambiente de produção, e você está recebendo relatos de bugs sobre algo que não estava acontecendo no seu ambiente de desenvolvimento, e você não consegue imaginar por que o código está fazendo isso. +Você volta para o seu código e descobre que consegue reproduzir o problema, mas não consegue descobrir o que está dando errado. +Você pode fazer um _bisect_ do código para descobrir. +Primeiro você roda `git bisect start` para dar o pontapé inicial, e depois você usa `git bisect bad` para dizer ao sistema que o commit atual no qual você está se encontra quebrado. +Então, você tem que informar ao bisect qual foi o último estado sabidamente bom, usando `git bisect good `: [source,console] ---- @@ -88,10 +88,10 @@ Bisecting: 6 revisions left to test after this [ecb6e1bc347ccecc5f9350d878ce677feb13d3b2] Error handling on repo ---- -Git figured out that about 12 commits came between the commit you marked as the last good commit (v1.0) and the current bad version, and it checked out the middle one for you. -At this point, you can run your test to see if the issue exists as of this commit. -If it does, then it was introduced sometime before this middle commit; if it doesn't, then the problem was introduced sometime after the middle commit. -It turns out there is no issue here, and you tell Git that by typing `git bisect good` and continue your journey: +O Git descobriu que houve cerca de 12 commits entre o commit que você marcou como o último commit bom (v1.0) e a atual versão ruim, e fez checkout daquele bem no meio para você. +A esta altura, você pode rodar o seu teste para ver se o problema existe na época deste commit. +Se ele existir, então ele foi introduzido em algum momento antes deste commit intermediário; se ele não existir, então o problema foi introduzido em algum momento após o commit intermediário. +Vê-se que não há nenhum problema aqui, e você conta isso para o Git digitando `git bisect good` e prossegue na sua jornada: [source,console] ---- @@ -100,8 +100,8 @@ Bisecting: 3 revisions left to test after this [b047b02ea83310a70fd603dc8cd7a6cd13d15c04] Secure this thing ---- -Now you're on another commit, halfway between the one you just tested and your bad commit. -You run your test again and find that this commit is broken, so you tell Git that with `git bisect bad`: +Agora você está em um outro commit, bem no meio do caminho entre o que você testou por último e o seu commit ruim. +Você roda o teste novamente e constata que este commit está quebrado, então você informa isto ao Git usando `git bisect bad`: [source,console] ---- @@ -110,8 +110,8 @@ Bisecting: 1 revisions left to test after this [f71ce38690acf49c1f3c9bea38e09d82a5ce6014] Drop exceptions table ---- -This commit is fine, and now Git has all the information it needs to determine where the issue was introduced. -It tells you the SHA-1 of the first bad commit and shows some of the commit information and which files were modified in that commit so you can figure out what happened that may have introduced this bug: +Este commit está bom, e agora o Git tem toda a informação que ele precisa para determinar onde o problema foi introduzido. +Ele te dá o SHA-1 do primeiro commit ruim (bad commit) e mostra algumas das informações do commit e quais arquivos foram modificados nesse commit, para que você possa descobrir o que aconteceu que possivelmente causou este bug: [source,console] ---- @@ -127,17 +127,17 @@ Date: Tue Jan 27 14:48:32 2009 -0800 f24d3c6ebcfc639b1a3814550e62d60b8e68a8e4 M config ---- -When you're finished, you should run `git bisect reset` to reset your HEAD to where you were before you started, or you'll end up in a weird state: +Quando você terminar, você deve rodar `git bisect reset` para resetar seu HEAD de volta para onde você estava antes de você ter começado, ou você vai terminar em um estado estranho: [source,console] ---- $ git bisect reset ---- -This is a powerful tool that can help you check hundreds of commits for an introduced bug in minutes. -In fact, if you have a script that will exit 0 if the project is good or non-0 if the project is bad, you can fully automate `git bisect`. -First, you again tell it the scope of the bisect by providing the known bad and good commits. -You can do this by listing them with the `bisect start` command if you want, listing the known bad commit first and the known good commit second: +Esta é uma ferramenta poderosa que pode ajudar você a checar centenas de commits à procura de um bug introduzido, em minutos. +De fato, se você tiver um script que vai dar exit com 0 caso o projeto seja bom ou não-0 caso o projeto seja ruim, você consegue automatizar o `git bisect` completamente. +Primeiro, mais uma vez você tem que determinar o escopo do bisect informando os commits conhecidos bom (good) e ruim (bad). +Você pode fazer isso listando-os com o comando `bisect start` se quiser, primeiro o commit ruim e depois o bom: [source,console] ---- @@ -145,5 +145,5 @@ $ git bisect start HEAD v1.0 $ git bisect run test-error.sh ---- -Doing so automatically runs `test-error.sh` on each checked-out commit until Git finds the first broken commit. -You can also run something like `make` or `make tests` or whatever you have that runs automated tests for you. +Ao fazer isso o Git executa automaticamente o script `test-error.sh` a cada commit extraído até ele encontrar o primeiro que está com problema. +Você pode ainda, usar comandos, tais como, `make` ou `make tests` ou até mesmo um script qualquer para a execução automatizada dos testes. diff --git a/book/07-git-tools/sections/interactive-staging.asc b/book/07-git-tools/sections/interactive-staging.asc index 1f7a5635..360abe4f 100644 --- a/book/07-git-tools/sections/interactive-staging.asc +++ b/book/07-git-tools/sections/interactive-staging.asc @@ -1,11 +1,11 @@ [[_interactive_staging]] -=== Interactive Staging +=== Área de Stage Interativa -In this section, you'll look at a few interactive Git commands that can help you craft your commits to include only certain combinations and parts of files. -These tools are helpful if you modify a number of files extensively, then decide that you want those changes to be partitioned into several focused commits rather than one big messy commit. -This way, you can make sure your commits are logically separate changesets and can be reviewed easily by the developers working with you. +Nesta seção, você verá alguns comandos interativos do Git que podem ajudá-lo a criar seus commits para incluir apenas certas combinações e partes de arquivos. +Essas ferramentas são úteis se você modificar vários arquivos extensivamente, então decide que quer que essas alterações sejam divididas em vários commits focados em vez de um único commit grande e confuso. +Dessa forma, você pode certificar-se de que seus commits são conjuntos de alterações separados logicamente e podem ser revisados facilmente pelos desenvolvedores que trabalham com você. -If you run `git add` with the `-i` or `--interactive` option, Git enters an interactive shell mode, displaying something like this: +Se você executar `git add` com a opção `-i` ou `--interactive`, o Git entra em um modo shell interativo, exibindo algo como isto: [source,console] ---- @@ -21,14 +21,14 @@ $ git add -i What now> ---- -You can see that this command shows you a much different view of your staging area than you're probably used to -- basically, the same information you get with `git status` but a bit more succinct and informative. -It lists the changes you've staged on the left and unstaged changes on the right. +Você pode ver que este comando mostra uma visão da sua área de stage muito diferente da que você provavelmente está acostumado -- basicamente, a mesma informação que você obtém com `git status`, mas um pouco mais sucinta e informativa. +Ela lista as alterações que estão na área de stage à esquerda e as não preparadas (unstaged) à direita. -After this comes a "`Commands`" section, which allows you to do a number of things like staging and unstaging files, staging parts of files, adding untracked files, and displaying diffs of what has been staged. +Depois disso vem uma seção "`Commands`" (Comandos), que permite fazer uma série de coisas como preparar e retirar arquivos da área de stage, preparar partes de arquivos, adicionar arquivos não rastreados e exibir diffs do que foi preparado (staged). -==== Staging and Unstaging Files +==== Adicionando e Removendo Arquivos do Stage -If you type `u` or `2` (for update) at the `What now>` prompt, you're prompted for which files you want to stage: +Se você digitar `u` ou `2` (para update) no prompt `What now>`, você será questionado sobre quais arquivos deseja preparar (stage): [source,console] ---- @@ -40,7 +40,7 @@ What now> u Update>> ---- -To stage the `TODO` and `index.html` files, you can type the numbers: +Para preparar (stage) os arquivos `TODO` e `index.html`, você pode digitar os números: [source,console] ---- @@ -52,8 +52,8 @@ Update>> 1,2 Update>> ---- -The `*` next to each file means the file is selected to be staged. -If you press Enter after typing nothing at the `Update>>` prompt, Git takes anything selected and stages it for you: +O `*` próximo a cada arquivo significa que o arquivo foi selecionado para ser preparado. +Se você pressionar Enter após não digitar nada no prompt `Update>>`, o Git pegará qualquer coisa selecionada e a preparará para você: [source,console] ---- @@ -70,8 +70,8 @@ What now> s 3: unchanged +5/-1 lib/simplegit.rb ---- -Now you can see that the `TODO` and `index.html` files are staged and the `simplegit.rb` file is still unstaged. -If you want to unstage the `TODO` file at this point, you use the `r` or `3` (for revert) option: +Agora você pode ver que os arquivos `TODO` e `index.html` estão preparados (staged) e o arquivo `simplegit.rb` ainda não está (unstaged). +Se você deseja remover (unstage) o arquivo `TODO` neste momento, use a opção `r` ou `3` (para revert): [source,console] ---- @@ -92,7 +92,7 @@ Revert>> [enter] reverted one path ---- -Looking at your Git status again, you can see that you've unstaged the `TODO` file: +Olhando para o seu status do Git novamente, você pode ver que você retirou o arquivo `TODO` do stage: [source,console] ---- @@ -106,9 +106,9 @@ What now> s 3: unchanged +5/-1 lib/simplegit.rb ---- -To see the diff of what you've staged, you can use the `d` or `6` (for diff) command. -It shows you a list of your staged files, and you can select the ones for which you would like to see the staged diff. -This is much like specifying `git diff --cached` on the command line: +Para ver o diff do que você preparou, você pode usar o comando `d` ou `6` (para diff). +Ele mostra uma lista dos seus arquivos preparados, e você pode selecionar aqueles para os quais gostaria de ver o diff. +Isso é muito parecido com especificar `git diff --cached` na linha de comando: [source,console] ---- @@ -133,14 +133,14 @@ index 4d07108..4335f49 100644