From 6bbe4f8c461800f02f82c6438d28d1a307060589 Mon Sep 17 00:00:00 2001 From: gustadsg <59234896+gustadsg@users.noreply.github.com> Date: Wed, 4 Mar 2026 16:29:32 -0300 Subject: [PATCH] =?UTF-8?q?Tradu=C3=A7=C3=A3o=20do=20Cap=C3=ADtulo=208=20S?= =?UTF-8?q?e=C3=A7=C3=A3o=201?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- book/08-customizing-git/sections/config.asc | 283 ++++++++++---------- 1 file changed, 142 insertions(+), 141 deletions(-) diff --git a/book/08-customizing-git/sections/config.asc b/book/08-customizing-git/sections/config.asc index 0085c893..5c032ca6 100644 --- a/book/08-customizing-git/sections/config.asc +++ b/book/08-customizing-git/sections/config.asc @@ -1,81 +1,82 @@ [[r_git_config]] -=== Git Configuration +=== Configuração do Git (((git commands, config))) -As you briefly saw in <>, you can specify Git configuration settings with the `git config` command. -One of the first things you did was set up your name and email address: +Como você viu brevemente em <>, você pode ajustar configurações do Git com o comando `git config`. +Uma das primeiras coisas que você fez foi configurar seu nome e e-mail: + [source,console] ---- -$ git config --global user.name "John Doe" -$ git config --global user.email johndoe@example.com +$ git config --global user.name "Fulano de Tal" +$ git config --global user.email fulanodetal@exemplo.br ---- -Now you'll learn a few of the more interesting options that you can set in this manner to customize your Git usage. +Agora você aprenderá algumas das opções mais interessantes que podem ser configuradas para personalizar seu uso do Git. + +Antes, uma revisão rápida: o Git usa uma série de arquivos de configuração para determinar comportamentos não padrão desejados. +O primeiro lugar em que o Git procura por esses valores é o arquivo `/etc/gitconfig`, que contém definições para todos os usuários do sistema e todos os seus repositórios. +Se você passar a opção `--system` para o `git config`, o Git vai ler e escrever especificamente neste arquivo. -First, a quick review: Git uses a series of configuration files to determine non-default behavior that you may want. -The first place Git looks for these values is in an `/etc/gitconfig` file, which contains values for every user on the system and all of their repositories. -If you pass the option `--system` to `git config`, it reads and writes from this file specifically. -The next place Git looks is the `~/.gitconfig` (or `~/.config/git/config`) file, which is specific to each user. -You can make Git read and write to this file by passing the `--global` option. +O próximo lugar que o Git olha é o arquivo `~/.gitconfig` (ou `~/.config/git/config`), que é específico para cada usuário. +Você pode fazer o Git ler e escrever neste arquivo usando a opção `--global`. -Finally, Git looks for configuration values in the configuration file in the Git directory (`.git/config`) of whatever repository you're currently using. -These values are specific to that single repository. +Por último, Git procura por definições no arquivo de configuração do repositório Git (.git/config) que você estiver usando no momento. -Each of these ``levels'' (system, global, local) overwrites values in the previous level, so values in `.git/config` trump those in `/etc/gitconfig`, for instance. +Cada um destes ``níveis'' (sistema, global, local) sobrescreve as definições do nível anterior, de forma que definições em `.git/config` têm prioridade sobre aquelas em `/etc/gitconfig/`, por exemplo. [NOTE] ==== -Git's configuration files are plain-text, so you can also set these values by manually editing the file and inserting the correct syntax. -It's generally easier to run the `git config` command, though. +Os arquivos de configuração do Git são texto simples, então você também pode ajustar essas definições editando o arquivo manualmente, usando a sintaxe correta. +No entanto, costuma ser mais fácil usar o comando `git config`. ==== -==== Basic Client Configuration +==== Configuração Básica do Cliente -The configuration options recognized by Git fall into two categories: client-side and server-side. -The majority of the options are client-side – configuring your personal working preferences. -Many, _many_ configuration options are supported, but a large fraction of them are only useful in certain edge cases. -We'll only be covering the most common and most useful here. -If you want to see a list of all the options your version of Git recognizes, you can run +As opções de configuração reconhecidas pelo Git se encaixam em duas categorias: do cliente e do servidor. +A maioria das opções são do cliente - configurando suas preferências pessoais de trabalho. +Várias, _várias_ opções de configuração são suportadas, mas grande parte delas são úteis apenas em alguns casos específicos. +Aqui cobriremos apenas os casos mais comuns e úteis. +Se você quiser ver a lista de todas as opções que a sua versão do git reconhece, você pode executar [source,console] ---- $ man git-config ---- -This command lists all the available options in quite a bit of detail. -You can also find this reference material at http://git-scm.com/docs/git-config.html[]. +Este comando lista todas as opções disponíveis em um bom nível de detalhe. +Você também pode ver a referência em http://git-scm.com/docs/git-config.html[]. ===== `core.editor` ((($EDITOR)))((($VISUAL, see $EDITOR))) -By default, Git uses whatever you've set as your default text editor (`$VISUAL` or `$EDITOR`) or else falls back to the `vi` editor to create and edit your commit and tag messages. -To change that default to something else, you can use the `core.editor` setting: +Por padrão, Git usa seu editor de texto padrão (`$VISUAL` or `$EDITOR`) ou então usa o `vi` para criar e editar suas mensagens de commits e tags. +Para alterar do editor padrão para algum outro, você pode usar a definição `core.editor`: [source,console] ---- $ git config --global core.editor emacs ---- -Now, no matter what is set as your default shell editor, Git will fire up Emacs to edit messages. +Agora, não importa qual seja seja o editor de texto padrão do seu shell, o Git sempre usará o Emacs para editar mensagens. ===== `commit.template` (((commit templates))) -If you set this to the path of a file on your system, Git will use that file as the default message when you commit. -For instance, suppose you create a template file at `~/.gitmessage.txt` that looks like this: +Se você definir como o caminho para um arquivo no seu computador, o Git usará esse arquivo como a mensagem padrão quando você fizer commit. +Por exemplo, suponha que você tenha criado um arquivo de template em `~/.gitmessage.txt` que se pareça com isso: [source,text] ---- -subject line +linha de assunto -what happened +o que aconteceu [ticket: X] ---- -To tell Git to use it as the default message that appears in your editor when you run `git commit`, set the `commit.template` configuration value: +Para dizer ao Git para usá-la como mensagem padrão no seu editor de texto quando você executar o comando `git commit`, defina valor da configuração `commit.template`: [source,console] ---- @@ -83,13 +84,13 @@ $ git config --global commit.template ~/.gitmessage.txt $ git commit ---- -Then, your editor will open to something like this for your placeholder commit message when you commit: +Assim, o seu editor iniciará com algo parecido com esse modelo de mensagem quando você fizer commit: [source,text] ---- -subject line +linha de assunto -what happened +o que aconteceu [ticket: X] # Please enter the commit message for your changes. Lines starting @@ -105,33 +106,33 @@ what happened ".git/COMMIT_EDITMSG" 14L, 297C ---- -If your team has a commit-message policy, then putting a template for that policy on your system and configuring Git to use it by default can help increase the chance of that policy being followed regularly. +Se seu time tem uma política de mensagem de commit, configurar um modelo para essa política no seu sistema e configurar o Git para usá-lo por padrão pode aumentar as chances dessa política ser seguida com regularidade. ===== `core.pager` (((pager))) -This setting determines which pager is used when Git pages output such as `log` and `diff`. -You can set it to `more` or to your favorite pager (by default, it's `less`), or you can turn it off by setting it to a blank string: +Essa configuração determina qual pager será utilizado quando Git faz paginação de saídas como `log` e `diff`. +Você pode definir como `more`ou para seu pager favorito (por padrão, é `less`), ou você pode desativar atribuindo uma string vazia: [source,console] ---- $ git config --global core.pager '' ---- -If you run that, Git will page the entire output of all commands, no matter how long they are. +Se você executar isso, Git irá imprimir a saída completa de todos os comandos, independente de quão longa ela for. ===== `user.signingkey` (((GPG))) -If you're making signed annotated tags (as discussed in <>), setting your GPG signing key as a configuration setting makes things easier. -Set your key ID like so: +Se você estiver criando tags anotadas assinadas (como discutido em <>), definir sua chave de assinatura GPG nas configurações torna as coisas mais fáceis. +Defina a sua chave desta forma: [source,console] ---- $ git config --global user.signingkey ---- -Now, you can sign tags without having to specify your key every time with the `git tag` command: +Agora, você consegue assinar tags sem ter que especificar sua chave toda vez no comando `git tag`: [source,console] ---- @@ -141,14 +142,14 @@ $ git tag -s ===== `core.excludesfile` (((excludes)))(((.gitignore))) -You can put patterns in your project's `.gitignore` file to have Git not see them as untracked files or try to stage them when you run `git add` on them, as discussed in <>. +Você pode colocar padrões no arquivo `.gitignore` do seu projeto para que o git não os veja como arquivos não rastreados nem tente adicioná-los quando você executar `git add`, como discutido em <>. -But sometimes you want to ignore certain files for all repositories that you work with. -If your computer is running Mac OS X, you're probably familiar with `.DS_Store` files. -If your preferred editor is Emacs or Vim, you know about filenames that end with a `~` or `.swp`. +Porém, algumas vezes você deseja ignorar alguns arquivos em todos os repositórios em que você trabalha. +Se seu computador estiver rodando Mac OS X, você provavelmente está familiarizado com os arquivos `.DS_Store`. +Se seu editor favorito for Emacs ou Vim, você entende sobre nomes de arquivo que terminam com `~` ou `.swp`. -This setting lets you write a kind of global `.gitignore` file. -If you create a `~/.gitignore_global` file with these contents: +Essa configuração permite que você escreva uma espécie de `.gitignore` global. +Se você criar o arquivo `~/.gitignore_global` com este conteúdo: [source,ini] ---- @@ -157,12 +158,12 @@ If you create a `~/.gitignore_global` file with these contents: .DS_Store ---- -…and you run `git config --global core.excludesfile ~/.gitignore_global`, Git will never again bother you about those files. +…e se você executar `git config --global core.excludesfile ~/.gitignore_global`, Git nunca mais o incomodará com esses arquivos. ===== `help.autocorrect` (((autocorrect))) -If you mistype a command, it shows you something like this: +Se você cometer um erro de digitação em algum comando, git exibirá algo como: [source,console] ---- @@ -173,8 +174,8 @@ Did you mean this? checkout ---- -Git helpfully tries to figure out what you meant, but it still refuses to do it. -If you set `help.autocorrect` to 1, Git will actually run this command for you: +O Git tenta descobrir o que você quis dizer, mas se recusa a executar. +Se você definir `help.autocorrect` como 1, o Git executará automaticamente este comando por você: [source,console] ---- @@ -184,67 +185,67 @@ Continuing under the assumption that you meant 'checkout' in 0.1 seconds automatically... ---- -Note that ``0.1 seconds'' business. `help.autocorrect` is actually an integer which represents tenths of a second. -So if you set it to 50, Git will give you 5 seconds to change your mind before executing the autocorrected command. +Observe o ``0.1 seconds''. `help.autocorrect` na verdade é um inteiro que representa décimos de segundo. +Então, se você defini-lo como 50, o Git te dará 5 segundos para mudar de ideia antes de executar o comando automaticamente corrigido. -==== Colors in Git +==== Cores no Git (((color))) -Git fully supports colored terminal output, which greatly aids in visually parsing command output quickly and easily. -A number of options can help you set the coloring to your preference. +O Git suporta saída colorida via terminal, o que ajuda muito na compreensão da saída dos comandos de forma rápida e fácil. +Várias opções podem te ajudar a definir suas preferências de cores. ===== `color.ui` -Git automatically colors most of its output, but there's a master switch if you don't like this behavior. -To turn off all Git's colored terminal output, do this: +O Git colore automaticamente a maior parte da sua saída, mas tem um interruptor principal se você não gostar deste comportamento +Para desligar a saída colorida do Git, faça isso: [source,console] ---- $ git config --global color.ui false ---- -The default setting is `auto`, which colors output when it's going straight to a terminal, but omits the color-control codes when the output is redirected to a pipe or a file. +A configuração padrão é `auto`, o que colore a saída quando ela está indo direto para o terminal, mas omite o controle de cor quando a saída é redirecionada para um pipe ou arquivo. -You can also set it to `always` to ignore the difference between terminals and pipes. -You'll rarely want this; in most scenarios, if you want color codes in your redirected output, you can instead pass a `--color` flag to the Git command to force it to use color codes. -The default setting is almost always what you'll want. +Você também pode defini-lo para `always` para ignorar a difereça entre terminais e pipes. +Você raramente vai quer fazer isso; na maioria dos casos, se você quiser manter as cores na saída redirecionada, poderá passar a opção `--color` para o comando Git para foçar o uso de cores. +A configuração padrão é quase sempre o que você quer usar. ===== `color.*` -If you want to be more specific about which commands are colored and how, Git provides verb-specific coloring settings. -Each of these can be set to `true`, `false`, or `always`: +Se você quiser ser mais específico em relação a quais comandos são coloridos e como, o Git dispõe de configurações específicas por ação. +Cada um dos itens abaixo pode ser configurado como `true`, `false`, or `always`: color.branch color.diff color.interactive color.status -In addition, each of these has subsettings you can use to set specific colors for parts of the output, if you want to override each color. -For example, to set the meta information in your diff output to blue foreground, black background, and bold text, you can run +Além disso, cada um tem subconfigurações que você pode usar para definir cores específicar para partes da saída, se você quiser sobrescrever cada cor. +Por exemplo, para definir os metadados da sua saída diff para cor de primeiro plano azul, cor de fundo preta e texto em negrito, você pode executar: [source,console] ---- $ git config --global color.diff.meta "blue black bold" ---- -You can set the color to any of the following values: `normal`, `black`, `red`, `green`, `yellow`, `blue`, `magenta`, `cyan`, or `white`. -If you want an attribute like bold in the previous example, you can choose from `bold`, `dim`, `ul` (underline), `blink`, and `reverse` (swap foreground and background). +Você pode definir a cor como qualquer um desses valores: `normal`, `black`, `red`, `green`, `yellow`, `blue`, `magenta`, `cyan`, or `white`. +Se você quiser um atributo como o negrito do exemplo anterior, você pode escolher entre `bold`, `dim`, `ul` (sublinhado), `blink`, e `reverse` (troca plano de fundo e primeiro plano). [[r_external_merge_tools]] -==== External Merge and Diff Tools +==== Ferramentas de Merge e Diff Externas (((mergetool)))(((difftool))) -Although Git has an internal implementation of diff, which is what we've been showing in this book, you can set up an external tool instead. -You can also set up a graphical merge-conflict-resolution tool instead of having to resolve conflicts manually. -We'll demonstrate setting up the Perforce Visual Merge Tool (P4Merge) to do your diffs and merge resolutions, because it's a nice graphical tool and it's free. +Apesar de o Git possuir uma implementação interna de diff, que viemos mostrando ao longo deste livro, você pode configurar uma ferramenta externa. +Você também pode configurar uma ferramenta gráfica de resolução de conflitos, em vez de resolvê-los manualmente. +Nós demonstraremos como configurar o Performance Visual Merge (P4Merge) para fazer seus diffs e resoluções de conflitos, porque é uma interface e boa e gratuita. -If you want to try this out, P4Merge works on all major platforms, so you should be able to do so. -We'll use path names in the examples that work on Mac and Linux systems; for Windows, you'll have to change `/usr/local/bin` to an executable path in your environment. +Se quiser testar, P4Merge funciona na maior parte das plataformas, então você provavelmente conseguirá usar. +Nos exemplos, usaremos caminhos válidos em Mac e Linux; se você usa Windows, substitua `/usr/local/bin` pelo caminho do executável no seu ambiente. -To begin, https://www.perforce.com/product/components/perforce-visual-merge-and-diff-tools[download P4Merge from Perforce]. -Next, you'll set up external wrapper scripts to run your commands. -We'll use the Mac path for the executable; in other systems, it will be where your `p4merge` binary is installed. -Set up a merge wrapper script named `extMerge` that calls your binary with all the arguments provided: +Para começar, https://www.perforce.com/product/components/perforce-visual-merge-and-diff-tools[baixe P4Merge no Perforce]. +Depois, você deverá configurar wrapper scripts externos para executar seus comandos. +Usaremos o caminho do Mac para o executável; em outras plataformas, será onde o seu `p4merge` estiver instalado. +Configure um wrapper script de merge chamado `extMerge` para chamar seu binário com todos os argumentos disponíveis: [source,console] ---- @@ -253,15 +254,15 @@ $ cat /usr/local/bin/extMerge /Applications/p4merge.app/Contents/MacOS/p4merge $* ---- -The diff wrapper checks to make sure seven arguments are provided and passes two of them to your merge script. -By default, Git passes the following arguments to the diff program: +O diff wrapper verifica que sete argumentos foram enviados e passa dois deles para seu script de merge. +Por padrão, o Git passa os seguintes argumentos para o programa de diff: [source] ---- path old-file old-hex old-mode new-file new-hex new-mode ---- -Because you only want the `old-file` and `new-file` arguments, you use the wrapper script to pass the ones you need. +Como você só quer os argumentos `old-file` e `new-file`, você pode usar o wrapper script para passar apenas o que precisa. [source,console] ---- @@ -270,7 +271,7 @@ $ cat /usr/local/bin/extDiff [ $# -eq 7 ] && /usr/local/bin/extMerge "$2" "$5" ---- -You also need to make sure these tools are executable: +Você também precisa garantir que as ferramentas são executáveis: [source,console] ---- @@ -278,9 +279,9 @@ $ sudo chmod +x /usr/local/bin/extMerge $ sudo chmod +x /usr/local/bin/extDiff ---- -Now you can set up your config file to use your custom merge resolution and diff tools. -This takes a number of custom settings: `merge.tool` to tell Git what strategy to use, `mergetool..cmd` to specify how to run the command, `mergetool..trustExitCode` to tell Git if the exit code of that program indicates a successful merge resolution or not, and `diff.external` to tell Git what command to run for diffs. -So, you can either run four config commands +Agora você pode ajustar seu arquivo de configuração para usar suas ferramentas customizadas de resolução de merge e diff. +Você precisará ajustar algumas definições: `merge.tool` para informar ao git qual estratégia usar, `mergetool..cmd` para dizer ao git como executar o comando, `mergetool..trustExitCode` para dizer ao Git o código de saída do programa que indica resolução com sucesso ou não, e `diff.external` para dizer ao Git que comando executar para mostrar diffs. +Para isso, você pode ou executar quatro comandos de configuração [source,console] ---- @@ -290,7 +291,7 @@ $ git config --global mergetool.extMerge.cmd \ $ git config --global mergetool.extMerge.trustExitCode false $ git config --global diff.external extDiff ---- -or you can edit your `~/.gitconfig` file to add these lines: +ou pode editar seu arquivo `~/.gitconfig` adicionando essas linhas: [source,ini] ---- @@ -303,22 +304,22 @@ or you can edit your `~/.gitconfig` file to add these lines: external = extDiff ---- -After all this is set, if you run diff commands such as this: +Depois de configurar tudo, se você executar comandos de diff como este: [source,console] ---- $ git diff 32d1776b1^ 32d1776b1 ---- -Instead of getting the diff output on the command line, Git fires up P4Merge, which looks something like this: +Ao invés de receber a saída do diff no terminal, o Git abrirá o P4Merge, que tem um visual mais ou menos assim: .P4Merge. image::images/p4merge.png[P4Merge.] -If you try to merge two branches and subsequently have merge conflicts, you can run the command `git mergetool`; it starts P4Merge to let you resolve the conflicts through that GUI tool. +Se você tentar fazer merge de duas branches e houver conflitos de merge, você pode executar o comando `git mergetool`; isso abrirá o P4Merge para permitir que você resolva os conflitos usando essa ferramenta com interface gráfica. -The nice thing about this wrapper setup is that you can change your diff and merge tools easily. -For example, to change your `extDiff` and `extMerge` tools to run the KDiff3 tool instead, all you have to do is edit your `extMerge` file: +A parte boa dessa configuração de wrapper é que você pode mudar as suas ferramentas de diff e merge facilmente. +Por exemplo, para mudar suas ferramentas `extDiff` e `extMerge` para executar KDiff3, tudo que precisa fazer é editar seu arquivo `extMerge`: [source,console] ---- @@ -327,10 +328,10 @@ $ cat /usr/local/bin/extMerge /Applications/kdiff3.app/Contents/MacOS/kdiff3 $* ---- -Now, Git will use the KDiff3 tool for diff viewing and merge conflict resolution. +Agora, o Git usará a ferramenta KDiff3 para exibição de diff e resolução de conflitos. -Git comes preset to use a number of other merge-resolution tools without your having to set up the cmd configuration. -To see a list of the tools it supports, try this: +O Git já vem preparado para algumas ferramentas de resolução de merge sem você precisar fazer configuração no terminal. +Para a lista de ferramentas suportadas, faça isso: [source,console] ---- @@ -362,49 +363,49 @@ Some of the tools listed above only work in a windowed environment. If run in a terminal-only session, they will fail. ---- -If you're not interested in using KDiff3 for diff but rather want to use it just for merge resolution, and the kdiff3 command is in your path, then you can run +Se você não tem interesse em usar a ferramenta KDiff3 para diff, mas prefere utilizá-la em resolução de merge e o comando kdiff3 está definido no seu path, você pode executar [source,console] ---- $ git config --global merge.tool kdiff3 ---- -If you run this instead of setting up the `extMerge` and `extDiff` files, Git will use KDiff3 for merge resolution and the normal Git diff tool for diffs. +Se executar esse comando ao invés de configurar os arquivos `extMerge` e `extDiff`, o Git utilizará KDiff3 para resolução de merge e a ferramenta interna para diffs. -==== Formatting and Whitespace +==== Formatação e Espaço em Branco (((whitespace))) -Formatting and whitespace issues are some of the more frustrating and subtle problems that many developers encounter when collaborating, especially cross-platform. -It's very easy for patches or other collaborated work to introduce subtle whitespace changes because editors silently introduce them, and if your files ever touch a Windows system, their line endings might be replaced. -Git has a few configuration options to help with these issues. +Problemas de formatação e espaço em branco são alguns dos problemas mais frustrantes e sutis que muitos desenvolvedores podem encontrar em colaboração, especialmente cross-platform. +É muito fácil que patches criados por outros introduzam mudanças sutis de espaço em branco porque editores os adicionam de forma silenciosa, e se seus arquivos tocarem um sistema Windows, os fins de linha serão substituídos. +O Git tem algumas opções para ajudar com esses problemas. ===== `core.autocrlf` (((crlf)))(((line endings))) -If you're programming on Windows and working with people who are not (or vice-versa), you'll probably run into line-ending issues at some point. -This is because Windows uses both a carriage-return character and a linefeed character for newlines in its files, whereas Mac and Linux systems use only the linefeed character. -This is a subtle but incredibly annoying fact of cross-platform work; many editors on Windows silently replace existing LF-style line endings with CRLF, or insert both line-ending characters when the user hits the enter key. +Se estiver programando em Windows e trabalhando com pessoas que não estão (ou vice-versa), você provavelmente vai ter problema com fins de linha em algum momento. +Isso aocntece porque o Windows usa tanto ambos caracteres de carriage-return character e linefeed (CR e LF) para novas linhas nos seus arquivos, ao mesmo tempo que Mac e Linux usam apenas LF. +Essa é uma diferença sutil e que incomoda bastante em trabalho cross-platform; muitos editores de texto no Windows silenciosamente substituem fins de linha LF existentes por CRLF, ou inserem ambos os caracteres de fim de linha quando a tecla enter é pressionada. -Git can handle this by auto-converting CRLF line endings into LF when you add a file to the index, and vice versa when it checks out code onto your filesystem. -You can turn on this functionality with the `core.autocrlf` setting. -If you're on a Windows machine, set it to `true` – this converts LF endings into CRLF when you check out code: +O Git lida com isso convertendo automaticamente todos os fins de linha CRLF para LF quando um arquivo é adicionado ao index e faz o processo inverso quando leva código para o seu sistema de arquivos. +Você pode ativar essa funcionalidade por meio da configuração `core.autocrlf`. +Se você estiver usando Windows, defina-a como `true` - isso converte os fins de linha de LF para CRLF quando trouxer código para sua máquina: [source,console] ---- $ git config --global core.autocrlf true ---- -If you're on a Linux or Mac system that uses LF line endings, then you don't want Git to automatically convert them when you check out files; however, if a file with CRLF endings accidentally gets introduced, then you may want Git to fix it. -You can tell Git to convert CRLF to LF on commit but not the other way around by setting `core.autocrlf` to input: +Se estiver usando Linux ou Mac que use fim de linha LF, você não vai querer que o Git faça essa conversão automática; no entanto, se um arquivo com CRLF acidentalmente for introduzido, você pode querer que o Git o corrija. +Você pode dizer ao Git para converter CRFL em LF ao fazer commit, mas não o caminho inverso definindo `core.autocrlf` como `input`: [source,console] ---- $ git config --global core.autocrlf input ---- -This setup should leave you with CRLF endings in Windows checkouts, but LF endings on Mac and Linux systems and in the repository. +Essa configuração deve deve permitir que tenha CRLF nos checkouts em Windows e apenas LF em sistemas Mac e Linux e no repositório. -If you're a Windows programmer doing a Windows-only project, then you can turn off this functionality, recording the carriage returns in the repository by setting the config value to `false`: +Se em todo o projeto apenas Windows é utilizado, você pode desligar essa funcionalidade, mantendo o padrão CRLF no repositório. Para isso defina `core.autocrlf` como `false`: [source,console] ---- @@ -413,16 +414,16 @@ $ git config --global core.autocrlf false ===== `core.whitespace` -Git comes preset to detect and fix some whitespace issues. -It can look for six primary whitespace issues – three are enabled by default and can be turned off, and three are disabled by default but can be activated. +O Git vem pré configurado para detectar e resolver alguns problemas de espaço em branco. +Ele procura por seis tipos primários de problemas - três são habilitados por padrão e os outros três desligados, mas podem ser habilitados. -The three that are turned on by default are `blank-at-eol`, which looks for spaces at the end of a line; `blank-at-eof`, which notices blank lines at the end of a file; and `space-before-tab`, which looks for spaces before tabs at the beginning of a line. +Os três que são habilitados por padrão são `blank-at-eol`, que busca espaço em branco no fim da linha; `blank-at-eof`, que busca linhas em branco no fim do arquivo; e `space-before-tab`, que busca por espaço em branco antes dos tabs no início da linha. -The three that are disabled by default but can be turned on are `indent-with-non-tab`, which looks for lines that begin with spaces instead of tabs (and is controlled by the `tabwidth` option); `tab-in-indent`, which watches for tabs in the indentation portion of a line; and `cr-at-eol`, which tells Git that carriage returns at the end of lines are OK. +Os três que vem desabilitados por padrão, mas podem ser habilitados são `indent-with-non-tab`, que busca linhas que começam com espaços em branco ao invés de tabs (e é controlado pela opção `tabwidth`); `tab-in-indent`, que procura por tabs na porção de indentação da linha; e `cr-at-eol`, que informa ao Git que é aceitável caracteres CR no fim das. -You can tell Git which of these you want enabled by setting `core.whitespace` to the values you want on or off, separated by commas. -You can disable an option by prepending a `-` in front of its name, or use the default value by leaving it out of the setting string entirely. -For example, if you want all but `space-before-tab` to be set, you can do this (with `trailing-space` being a short-hand to cover both `blank-at-eol` and `blank-at-eof`): +Você pode dizer ao Git quais dessas quer habilitar definindo `core.whitespace` com os valores que você quer ligados ou desligados, separados por vírgulas. +Você pode desabilitar uma opção acrescentando um `-` na frente do nome, ou usar o valor default deixando o nome fora da string de configuração. +Por exemplo, se quiser deixar tudo menos o `space-before-tab` habilitado, pode fazer assim (sendo `trailing-space` um atalho para `blank-at-eol` e `blank-at-eof`): [source,console] ---- @@ -430,7 +431,7 @@ $ git config --global core.whitespace \ trailing-space,-space-before-tab,indent-with-non-tab,tab-in-indent,cr-at-eol ---- -Or you can specify the customizing part only: +Ou você pode customizar apenas a parte customizada: [source,console] ---- @@ -438,67 +439,67 @@ $ git config --global core.whitespace \ -space-before-tab,indent-with-non-tab,tab-in-indent,cr-at-eol ---- -Git will detect these issues when you run a `git diff` command and try to color them so you can possibly fix them before you commit. -It will also use these values to help you when you apply patches with `git apply`. -When you're applying patches, you can ask Git to warn you if it's applying patches with the specified whitespace issues: +O Git vai detectar esses problemas quando você executar o comando `git diff` e tentar colori-los para que você possa resolvê-los antes de fazer commit. +Ele também usará essas configurações para te ajudar a aplicar patches com `git apply`. +Quando você estiver aplicando patches, você pode pedir ao Git para te avisar se terá os problemas de espaço em branco especificados. [source,console] ---- $ git apply --whitespace=warn ---- -Or you can have Git try to automatically fix the issue before applying the patch: +Ou você pode deixar o Git tentar resolver o problema automaticamente antes de aplicar o patch: [source,console] ---- $ git apply --whitespace=fix ---- -These options apply to the `git rebase` command as well. -If you've committed whitespace issues but haven't yet pushed upstream, you can run `git rebase --whitespace=fix` to have Git automatically fix whitespace issues as it's rewriting the patches. +Essas opções também se aplicam ao comando `git rebase`. +Se você já houver commitado problemas de espaço em branch e ainda não houver enviado para o upstream, você pode executar `git rebase --whitespace=fix` para deixar o Git fazer correções automáticas enquanto reescreve os patches. -==== Server Configuration +==== Configuração do Servidor -Not nearly as many configuration options are available for the server side of Git, but there are a few interesting ones you may want to take note of. +Muito menos opções de configuração estão disponíveis para o lado do servidor do Git, mas há algumas opções interessantes que você pode querer anotar. ===== `receive.fsckObjects` -Git is capable of making sure every object received during a push still matches its SHA-1 checksum and points to valid objects. -However, it doesn't do this by default; it's a fairly expensive operation, and might slow down the operation, especially on large repositories or pushes. -If you want Git to check object consistency on every push, you can force it to do so by setting `receive.fsckObjects` to true: +O Git é capaz de garantir que cada objeto recebido durante um push ainda corresponde com sua soma SHA-1 e aponta para objetos válidos. +No entanto, isso não é feito por padrão; é uma operação relativamente cara, e por isso pode retardar a operação, especialmente em grandes repositórios ou pushes. +Se você quiser que o Git cheque a consistência dos objetos em todos os pushes, você pode forçar isso definindo a configuração `receive.fsckObjects` como `true`: [source,console] ---- $ git config --system receive.fsckObjects true ---- -Now, Git will check the integrity of your repository before each push is accepted to make sure faulty (or malicious) clients aren't introducing corrupt data. +Agora, o Git irá checar a integridade do seu repositório antes de cada push ser aceito para garantir que clientes defeituosos (ou maliciosos) não estejam introduzindo dados corrompidos. ===== `receive.denyNonFastForwards` -If you rebase commits that you've already pushed and then try to push again, or otherwise try to push a commit to a remote branch that doesn't contain the commit that the remote branch currently points to, you'll be denied. -This is generally good policy; but in the case of the rebase, you may determine that you know what you're doing and can force-update the remote branch with a `-f` flag to your push command. +Se você fizer rebase de commits que você ja houver feito push e tentar fazer push novamente, ou então tentar fazer push de um commit para uma branch remota que não contém o commit para o qual a branch remota aponta atualmente, a operação será negada. +Isso geralmente é uma boa prática; mas no caso de rebase, você pode dizer que sabe o que está fazendo e forçar a atualização da branch remota usando a opção `-f` no seu comando de push. -To tell Git to refuse force-pushes, set `receive.denyNonFastForwards`: +Para dizer ao Git para recusar pushes forçados, defina `receive.denyNonFastForwards`: [source,console] ---- $ git config --system receive.denyNonFastForwards true ---- -The other way you can do this is via server-side receive hooks, which we'll cover in a bit. -That approach lets you do more complex things like deny non-fast-forwards to a certain subset of users. +A outra forma de fazer isso é por meio de receive hooks no servidor, veremos isto num instante. +Essa abordagem permite que você faça coisas mais complexas como negar non-fast-forwards para um certo subconjunto de usuários. ===== `receive.denyDeletes` -One of the workarounds to the `denyNonFastForwards` policy is for the user to delete the branch and then push it back up with the new reference. -To avoid this, set `receive.denyDeletes` to true: +Uma solução alternativa à política de `denyNonFastForwards` para o usuário é deletar a branch e então enviá-la novamente com a nova referência. +Para evitar que isso aconteça, defina `receive.denyDeletes` como true: [source,console] ---- $ git config --system receive.denyDeletes true ---- -This denies any deletion of branches or tags – no user can do it. -To remove remote branches, you must remove the ref files from the server manually. -There are also more interesting ways to do this on a per-user basis via ACLs, as you'll learn in <>. +Isso nega qualquer deleção de branches ou tags - nenhum usuário conseguirá fazer isso. +Para remover branches remotas, você precisará remover os arquivos de ref do servidor manualmente. +Há também maneiras mais interessantes de fazer isso por usuário via ACLs, como você aprenderá em <>.