Você está na página 1de 46

Gaga’s Codex - Git

Gabriel Cardoso
11 de setembro de 2022
Conteúdo

1 INTRODUÇÃO 1
1.1 OQUE É GIT? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 VANTAGENS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.3 INSTALAÇÃO DO GIT NO WINDOWS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.4 INSTALAÇÃO DO P4 MERGE NO WINDOWS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

2 ESTRUTURA E WORKFLOW DO GIT 2


2.1 DOCUMENTOS MONITORADOS E NÃO MONITORADOS PELO GIT . . . . . . . . . . . . . . . . . . . 2
2.2 MOVIMENTAÇÃO PARA WORKING DIRECTORY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.3 MOVIMENTAÇÃO ADD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.4 MOVIMENTAÇÃO COMMIT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.5 MOVIMENTAÇÃO PUSH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.6 MOVIMENTAÇÃO PULL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

3 FUNÇÕES E ELEMENTOS DO GIT 8


3.1 ALIAS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.1.1 ALIASES ÚTEIS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.2 CONFIG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.2.1 NÍVEIS E ARQUIVOS DO GIT CONFIG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.2.2 COMO GRAVAR VALORES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.3 IGNORING . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.4 BRANCHING & MERGING . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.5 REBASING . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.6 STASHING . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.7 CHEERY-PICK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.7.1 EXEMPLOS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.8 TAGGING . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.8.1 APLICANDO TAGS PARA VERSIONAMENTO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.9 ARQUIVO README.MD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.9.1 ELEMENTOS PADRÃO DO README . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.9.2 SINTAXE DE FORMATAÇÃO DO README . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3.9.3 AUTO-GENERATED TABLE OF CONTENTS FOR README FILES . . . . . . . . . . . . . . . . . 15
3.9.4 GERADOR DE README FILE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

4 CONFLITOS NO GIT 15

5 UTILIZANDO O GIT (COM GITHUB) NO WINDOWS 15


5.1 CRIANDO UM NOVO DIRETÓRIO GITHUB WEB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
5.2 CONFIGURANDO EDITOR DE TEXTO (SUBLIME) ALTERNATIVO NO GIT NO WINDOWS PELO
GITBASH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
5.3 CONFIGURANDO O GIT NO WINDOWS PELO GITBASH . . . . . . . . . . . . . . . . . . . . . . . . . . 16
5.4 CLONANDO O NOVO DIRETÓRIO PARA O WINDOWS . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
5.5 ADICIONANDO UM ARQUIVO AO GITHUB - CAMINHO COMPLETO . . . . . . . . . . . . . . . . . . . 16
5.6 OPERANDO BRANCHES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
5.6.1 CRIANDO UMA NOVA BRANCH + MERGE FAST FORWARD . . . . . . . . . . . . . . . . . . . . 17
5.6.2 APLICANDO COMANDO MERGE NOT FAST FORWARD . . . . . . . . . . . . . . . . . . . . . . . 17
5.7 REALIZANDO COMPARAÇÕES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
5.7.1 WORKING DIRECTORY VS STAGING AREA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
5.7.2 WORKING DIRECTORY VS REPOSITORY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
5.7.3 STAGING AREA VS REPOSITORY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
5.7.4 COMPARAÇÃO DE UM ARQUIVO ESPECÍFICO . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
5.7.5 COMPARAÇÃO DE UM COMMIT COM O ÚLTIMO COMMIT . . . . . . . . . . . . . . . . . . . . 18
5.7.6 COMPARAÇÃO COM FERRAMENTA GRÁFICA P4MERGE . . . . . . . . . . . . . . . . . . . . . 18
5.8 APLICANDO REBASE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
5.9 OPERANDO STASHES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
5.9.1 APLICANDO STASH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
5.9.2 APLICANDO O STASH EM ARQUIVOS NÃO RASTREADOS . . . . . . . . . . . . . . . . . . . . . 20
5.9.3 LIMPANDO O STASH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
5.9.4 RESTAURANDO O STASH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
5.9.5 APLICANDO O STASHES MULTIPLOS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
5.9.6 VISUALIZANDO UM STASH ESEPCÍFICO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
5.9.7 RESTAURANDO UM STASH ESEPCÍFICO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
5.9.8 DELETANDO UM STASH ESEPCÍFICO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
5.9.9 DELETANDO TODOS OS STASHES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
5.9.10 APLICANDO STASH EM UMA BRANCH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
5.10 OPERANDO TAGS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
5.10.1 VISUALIZAR LISTA DE TAGS EXISTENTES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
5.10.2 VISUALIZANDO INFORMAÇÕES DE UMA TAG . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
5.10.3 CRIANDO UMA LIGTHWEIGHT TAG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
5.10.4 DELETANDO UMA LIGTHWEIGHT TAG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
5.10.5 CRIANDO UMA ANNOTATED TAG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
5.10.6 COMPARANDO DIFERENÇAS ENTRE TAGS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
5.10.7 APLICANDO UMA TAG EM UM COMMIT ANTERIOR . . . . . . . . . . . . . . . . . . . . . . . . 22
5.10.8 ATUALIZAR UMA TAG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
5.10.9 REALIZAR UM PUSH A PARTIR DE UMA TAG . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
5.10.10 REALIZAR PUSH DE TODAS AS TAG . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
5.10.11 DELETAR UMA TAG QUE ESTEJA NO GITHUB (REMOTE REPO) . . . . . . . . . . . . . . . . 22

6 LISTA DE COMANDOS 22
6.1 GIT OPTIONS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
6.1.1 MAIN PORCELAIN COMMANDS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
6.1.2 ANCILLARY COMMANDS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
6.1.3 INTERACTING WITH OTHERS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
6.1.4 RESET, RESTORE AND REVERT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
6.2 LOW-LEVEL COMMANDS (PLUMBING) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
6.2.1 MANIPULATION COMMANDS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
6.3 INTERROGATION COMMANDS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
6.3.1 SYNCING REPOSITORIES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
6.3.2 INTERNAL HELPER COMMANDS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
6.4 GUIDES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
6.5 IDENTIFIER TERMINOLOGY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
6.6 SYMBOLIC IDENTIFIERS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
6.7 ENVIRONMENT VARIABLES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
6.7.1 THE GIT REPOSITORY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
6.7.2 GIT COMMITS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
6.7.3 GIT DIFFS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
6.7.4 OTHER . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

7 MATERIAL DE REFERÊNCIA 41
Lista de Figuras
1 Git Workflow - Documentos monitorados e não monitorados pelo Git . . . . . . . . . . . . . . . . . . . . . . . 2
2 Git Workflow - Movimentação para Working Directory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
3 Git Workflow - Movimentação Add . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
4 Git Workflow - Movimentação commit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
5 Git Workflow - Movimentação Push . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
6 Git Workflow - Movimentação Pull . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
7 Exemplo de branching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
8 Exemplo de rebasing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
9 Exemplo de versionamento semântico . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
10 Tela do Git Bash para difftool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
11 Tela do P4Merge evidenciando diferenças . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Lista de Tabelas
1 A tabela de editores populares e comandos git config correspondentes . . . . . . . . . . . . . . . . . . . . . . 9
2 Tabela com elementos de um README . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3 Sintaxe de formatação do README . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Gabriel Cardoso Gaga’s Codex - Git 1

1 INTRODUÇÃO
1.1 OQUE É GIT?
Git is a free and open source distributed version control system designed to handle everything from small to very large
projects with speed and efficiency.
Git is easy to learn and has a tiny footprint with lightning fast performance. It outclasses SCM tools like Subversion,
CVS, Perforce, and ClearCase with features like cheap local branching, convenient staging areas, and multiple workflows.

1.2 VANTAGENS
ˆ Branching and Merging

ˆ Small and Fast

ˆ Distributed

ˆ Data Assurance

ˆ Free and Open Source

1.3 INSTALAÇÃO DO GIT NO WINDOWS


1. Baixar o arquivo do git do site oficical: https://git-scm.com/download/win
2. Após baixar, instale o programa executando o arquivo baixado.
3. No promt, utilize o comando: [git –version]. Se o promt retornar a versão do git a intalação foi concluı́da com sucesso.

1.4 INSTALAÇÃO DO P4 MERGE NO WINDOWS


O P4Merge é uma aplicação muito útil par resolver conflitos de alterações em códigos no momento dos commits. Para instalar
siga os passos adiante:

1. Acesse o site para baixar a versão mais indicada para o sistema operacional: https://www.perforce.com/downloads/visual-
merge-tool
2. Execute o instalador e finalize as opções

Gabriel Cardoso Gaga’s Codex - Git Página 1


Gabriel Cardoso Gaga’s Codex - Git 2

2 ESTRUTURA E WORKFLOW DO GIT


2.1 DOCUMENTOS MONITORADOS E NÃO MONITORADOS PELO GIT

Arquivos no Sistema Operacional Arquivos no Sistema Git

Arquivos Locais Arquivos Remotos

Não os
Working Directory Staging Area Repository Repository

d
itora
Mon o Git
pel .jar .txt .txt .txt

.rar

dos
Não os.rar dos dos itora
.rar
d itora itora M o n
Git
itora Mon Git Mon Git pelo
Mon o Git pelo pelo
.rar pel

.jar .txt

Figura 1: Git Workflow - Documentos monitorados e não monitorados pelo Git

Gabriel Cardoso Gaga’s Codex - Git Página 2


Gabriel Cardoso Gaga’s Codex - Git 3

2.2 MOVIMENTAÇÃO PARA WORKING DIRECTORY

Arquivos no Sistema Operacional Arquivos no Sistema Git

Arquivos Locais Arquivos Remotos

Working Directory Staging Area Repository Repository

.txt .txt

Mover de Diretório
O movimento é possível de ser realizado
movendo o arquivo de uma pasta não
configurada para o Git no sistema
operacional para uma pasta configurada.
Este movimento não faz com que o arquivo
se torne monitorado, somente estará no
mesmo diretório de trabalho.

Figura 2: Git Workflow - Movimentação para Working Directory

Gabriel Cardoso Gaga’s Codex - Git Página 3


Gabriel Cardoso Gaga’s Codex - Git 4

2.3 MOVIMENTAÇÃO ADD

Arquivos no Sistema Git

Arquivos Locais Arquivos Remotos

Working Directory Staging Area Repository Repository

.txt .txt

Mover de Área
O movimento é possível através do comando
git add. O Comando faz com que o arquivo
entre na Staging Area tornando-se
monitorável e sucesstível a commits.
Qualquer alteração no conteúdo ou nome
deste arquivo será rastreável.

Figura 3: Git Workflow - Movimentação Add

Gabriel Cardoso Gaga’s Codex - Git Página 4


Gabriel Cardoso Gaga’s Codex - Git 5

2.4 MOVIMENTAÇÃO COMMIT

Arquivos no Sistema Git

Arquivos Locais Arquivos Remotos

Working Directory Staging Area Repository Repository

.txt .txt

Mover de Área
O movimento é possível através do comando
git comit. O Comando faz com que o
arquivo entre no repositório local e
considerado como mais recente localmente.
Qualquer alteração no conteúdo ou nome
deste arquivo fará com que ele volte para a
Stagin Area e para ser oficializado deverá
passar por mais um comit..

Figura 4: Git Workflow - Movimentação commit

Gabriel Cardoso Gaga’s Codex - Git Página 5


Gabriel Cardoso Gaga’s Codex - Git 6

2.5 MOVIMENTAÇÃO PUSH

Arquivos no Sistema Git

Arquivos Locais Arquivos Remotos

Working Directory Staging Area Repository Repository

.txt .txt

Subir para Nuvem


O movimento é possível através do comando
git push. O Comando faz com que o arquivo
seja enviado ao repositório remoto e
considerado como oficial.

Figura 5: Git Workflow - Movimentação Push

Gabriel Cardoso Gaga’s Codex - Git Página 6


Gabriel Cardoso Gaga’s Codex - Git 7

2.6 MOVIMENTAÇÃO PULL

Arquivos no Sistema Git

Arquivos Locais Arquivos Remotos

Working Directory Staging Area Repository Repository

.txt .txt

Baixar da Nuvem
O movimento é possível através do comando
git pull. O Comando faz com que o arquivo
seja baixando do repositório remoto em sua
versão mais recente.

Figura 6: Git Workflow - Movimentação Pull

Gabriel Cardoso Gaga’s Codex - Git Página 7


Gabriel Cardoso Gaga’s Codex - Git 8

3 FUNÇÕES E ELEMENTOS DO GIT


3.1 ALIAS
Os alias no git são atalhos para comandos do git e até comandos shell. E é bem fácil cadastrar um alias:
sensitive1 g i t c o n f i g == g l o b a l a l i a s . s t s t a t u s
Com esse código, você cadastra um alias ”st”para o subcomando ”status”do git. A opção –global quer dizer que o alias
será aplicado no arquivo .gitconfig dentro do seu diretório home, e por isso o alias será aplicado em todos seus repositórios.
Sem esta opção, o alias será aplicado no .gitconfig do repositório atual, logo só será aplicado apenas a ele.
Para utilizar o alias criado basta chamar o comando:
sensitive1 git st

3.1.1 ALIASES ÚTEIS


Existem alguns comandos muito úteis, porém extensos e confusos. Para facilitar o uso do git seguem abaixo alguns
alias recomendados:
1. log completo
sensitive1 g i t c o n f i g == g l o b a l a l i a s . l o g s ’ l o g == o n e l i n e ==graph == d e c o r a t e
== a l l ’

2. status resumido
sensitive1 g i t c o n f i g == g l o b a l a l i a s . s t ’ s t a t u s =sb ’

3.2 CONFIG
O comando git config é a função conveniente usada para definir valores de configuração do Git em projetos de nı́vel
global ou local. Esses nı́veis de configuração correspondem aos arquivos de texto do .gitconfig. Executar o git config modifica
arquivos de texto de configuração.
O caso de uso mais básico do git config é chamar o comando com o nome de configuração, o que vai exibir o valor
definido desse nome. Nomes de configuração são cadeias de caracteres delimitadas por pontos compostas de ”seções”e
”chaves”baseadas na hierarquia. Por exemplo: user.email.
sensitive1 g i t c o n f i g user . email

Nesse exemplo, o e-mail é propriedade filho do bloco de configuração do usuário. Isso retorna o endereço de e-mail
configurado que o Git associa com commits criados no local.

3.2.1 NÍVEIS E ARQUIVOS DO GIT CONFIG


O comando git config pode aceitar argumentos para especificar o nı́vel de configuração no qual operar. Os seguintes nı́veis
de configuração estão disponı́veis:
ˆ - -local
Por padrão, o git config grava em nı́vel local se não houver nenhuma opção de configuração. A configuração de nı́vel
local é aplicada no repositório do contexto em que o git config for invocado. Os valores de configuração local são
armazenados em um arquivo que pode ser encontrado no diretório .git do repositório: .git/config
ˆ - -global
A configuração de nı́vel global é especı́fica do usuário, ou seja, ela é aplicada a usuários do sistema operacional. Os
valores de configuração global são armazenados em um arquivo localizado no diretório de base do usuário. /.gitconfig
em sistemas Unix e C: /Users
.gitconfig no Windows
ˆ - -system
A configuração de nı́vel do sistema é aplicada em toda a máquina. Ela abrange todos os usuários do sistema operacional
e todos os repositórios. O arquivo de configuração de nı́vel do sistema está no arquivo gitconfig localizado fora do
caminho raiz do sistema. $(prefix)/etc/gitconfig em sistemas Unix. No Windows, esse arquivo pode ser encontrado
em C:/Documents and Settings/All Users/Application Data/Git/config no Windows XP e em C:/ProgramData/Git/
config no Windows Vista e versões mais recentes.

Gabriel Cardoso Gaga’s Codex - Git Página 8


Gabriel Cardoso Gaga’s Codex - Git 9

Portanto, a ordem de prioridade para os nı́veis de configuração é: local, global, sistema. Quando o Git procurar valores
de configuração, ele vai começar no nı́vel local e ir até o nı́vel de sistema.

3.2.2 COMO GRAVAR VALORES


Para ampliar o conhecimento sobre o git config, será analisado o exemplo no qual o seguinte valor foi gravado:
sensitive1 g i t c o n f i g == g l o b a l u s e r . e m a i l ” your email@example . com”

Nesse exemplo, o valor your email@example.com é gravado no nome de configuração user.email. Ele usa o sinalizador
–global, então esse valor é definido para o usuário atual do sistema operacional. git config editor – core.editor

Muitos comandos Git iniciam o editor de texto para solicitar mais entradas. Um dos casos de uso mais comuns do
git config é configurar qual editor o Git deve usar. A tabela de editores populares e comandos git config correspondentes é
apresentada abaixo:

Editor Comando config

Atom git config –global core.editor ”atom –wait”

emacs git config –global core.editor ”emacs”

nano git config –global core.editor ”nano -w”

vim git config –global core.editor ”vim”

Sublime Text (Mac) git config –global core.editor ”subl -n -w”

Sublime Text (Windows, instalação de 32 bits) git config –global core.editor ”’c:/program files (x86)/sublime text 3/sublimetext.exe’ -w”

Sublime Text (Windows, instalação de 64 bits) git config –global core.editor ”’c:/program files/sublime text 3/sublimetext.exe’ -w”

TextMate git config –global core.editor ”mate -w”

Tabela 1: A tabela de editores populares e comandos git config correspondentes

3.3 IGNORING
O Git vê cada arquivo em sua cópia de trabalho em um de três estados:

1. rastreado – um arquivo que já passou pelo staging ou commit;


2. não rastreado – um arquivo que não passou pelo staging ou commit; ou
3. ignorado – um arquivo que o Git foi forçado a ignorar.
Os arquivos ignorados costumam ser artefatos de desenvolvimento e arquivos gerados por máquina que podem ser
derivados da fonte do seu repositório ou que não devem passar por commit. Exemplos comuns incluem:
ˆ caches de dependência, como o conteúdo de node modules ou packages

ˆ código compilado, como arquivos .o, .pyc e .class

ˆ diretórios de saı́da de build, como /bin, out ou target

ˆ arquivos gerados no perı́odo de execução, como .log, .lock ou .tmp

ˆ arquivos de sistema ocultos, como .DS Store ou Thumbs.db

ˆ arquivos pessoais de configuração do IDE, como .ideaworkspace.xml

Os arquivos ignorados são rastreados em um arquivo especial chamado .gitignore, que é verificado na origem do seu
repositório. Não há nenhum comando git ignore explı́cito: é preciso editar e fazer commit do arquivo .gitignore à mão
quando você tiver novos arquivos que quer ignorar. Os arquivos .gitignore contêm padrões que são comparados com nomes
de arquivos em seu repositório para determinar se devem ou não ser ignorados. Para comentar uma linha no arquivo .gitignore
adicione o sı́mbolo # ao inı́cio da linha.
Exemplos (dentro do arquivo .gitignore):

# ignore all logs


*.log

# ignore the file literally named foo[01].txt


foo\[01\].txt

Gabriel Cardoso Gaga’s Codex - Git Página 9


Gabriel Cardoso Gaga’s Codex - Git 10

Abaixo está um exemplo de commit forçado de arquivo ignorado:


sensitive1 cat . g i t i g n o r e
sensitive2 *. log
sensitive3
sensitive4 g i t add = f debug . l o g
sensitive5
sensitive6 g i t commit =m ” Force adding debug . l o g ”

3.4 BRANCHING & MERGING


É importante utilizar branchs para separar linhas de desenvolvimento da linha de produção. O ideal é que se dê o
nome do recurso, módulo ou Bug a ser corrigido para a branch que for criada para desenvolvê-lo.

Branch Branch Branch Branch


Produto
Produto
Produto
Produto

comit1 comit2 comit3 comit4

Production Production
V1.1.1 V1.2.0

Production
Production

V1.0.0 V1.1.0

Branch Branch Branch


NF
NF
NF

comit1 comit2 comit3

Figura 7: Exemplo de branching

É possı́vel renomear, deletar e criar branches. Branches são labels. O merge do tipo FastForward só é possı́vel quando
não houve alteração da branch principal enquanto houve alteração da branch a ser mesclada (merged). No fast-forward
a branch desaparece ao sofrer o mergge. É possı́vel desabilitar o fast-forward mergge. Pode ser vantajoso desabilitar o
fast-forward merge para manter o histórico de alterações realizadas em branches.
Quando há alterações em arquivos de branches diferentes mas em linhas de códigos iguais ocorre um conflito de merge.
O git não permite dar o merge até que os conflitos sejam resolvidos de forma que não haja diferença.
É recomendado utilizar o ”P4MERGE”. ele ajuda a visualizare resolver os conflitos. Ao resolver problemas de
conflitos o git salva uma cópia do conflito para caso seja necessário visualizar no futuro. É possı́vel configurar o arquivo
”.gitignore”para que não sejam salvos esses arquivos ”.orig”.

3.5 REBASING
O Rebase transforma a linha principal de desenvolvimento para uma branch. Ao final o fluxo passa a ser rastreado
através da branch que recebeu o release.

Branch Branch Branch Branch


Produto
Produto
Produto
Produto

Production Production Production


comit1 comit2 comit3 comit4
V2.0.0 V2.0.1 V2.0.2

Production Production
V1.1.1 V1.2.0

Production
Production
Production
V1.0.0 V1.1.0 V1.2.1

Branch Branch Branch


NF
NF
NF

comit1 comit2 comit3

Figura 8: Exemplo de rebasing

Gabriel Cardoso Gaga’s Codex - Git Página 10


Gabriel Cardoso Gaga’s Codex - Git 11

É possı́vel abortar um rebase em caso de conflitos. É possı́vel fazer um rebase em um pull. As alterações já chegam
como rebase.

3.6 STASHING
O stash serve para reservar alterações realizadas que ainda não podem ser commitadas em um ”local”seguro. As
alterações ficarão no stash até que sejam resgatadas. Eqnuanto as alterações estiverem reservadas, outras alterações poderão
ser realizadas e commitadas independentemente.

ˆ Um ”stash”pode ser recuperado ou apagado.


ˆ É possı́vel colocar em um ”stash”arquivos não rastreados.
ˆ Vários ”stash”podem coexistir. É possı́vel se referir a stash por meio da posição, EX:

sensitive1 \ git s t a s h show stash@ \{0}


sensitive2 \ git s t a s h show stash@ \{1}
sensitive3 \ git s t a s h show stash@ \{2}
sensitive4 .
sensitive5 .
sensitive6 .
sensitive7 \ git s t a s h show stash@ \{n}

ˆ É possı́vel ”resgatar”cada stash separadamente ou todas simultaneamente.

sensitive1 git stash clear

ˆ É possı́vel fazer stash em uma Branch especı́fica.

3.7 CHEERY-PICK
Given one or more existing commits, apply the change each one introduces, recording a new commit for each. This
requires your working tree to be clean (no modifications from the HEAD commit). When it is not obvious how to apply a
change, the following happens:

1. The current branch and HEAD pointer stay at the last commit successfully made.
2. The CHERRY PICK HEAD ref is set to point at the commit that introduced the change that is difficult to apply.
3. Paths in which the change applied cleanly are updated both in the index file and in your working tree.
4. For conflicting paths, the index file records up to three versions, as described in the ”TRUE MERGE”section of
git-merge[1]. The working tree files will include a description of the conflict bracketed by the usual conflict markers
<<<<<<< and >>>>>>>.
5. No other modifications are made.

3.7.1 EXEMPLOS

sensitive1 g i t c h e r r y = p i c k master

Apply the change introduced by the commit at the tip of the master branch and create a new commit with this change.
sensitive1 g i t c h e r r y = p i c k . . master
sensitive2 g i t c h e r r y = p i c k ˆHEAD master
Apply the changes introduced by all commits that are ancestors of master but not of HEAD to produce new commits.
sensitive1 g i t c h e r r y = p i c k maint next ˆ master
sensitive2 g i t c h e r r y = p i c k maint master . . next
Apply the changes introduced by all commits that are ancestors of maint or next, but not master or any of its ancestors.
Note that the latter does not mean maint and everything between master and next; specifically, maint will not be used if it
is included in master.

Gabriel Cardoso Gaga’s Codex - Git Página 11


Gabriel Cardoso Gaga’s Codex - Git 12

sensitive1 g i t c h e r r y = p i c k master ˜4 master ˜2


Apply the changes introduced by the fifth and third last commits pointed to by master and create 2 new commits
with these changes.
sensitive1 g i t c h e r r y = p i c k =n master ˜1 next
Apply to the working tree and the index the changes introduced by the second last commit pointed to by master and
by the last commit pointed to by next, but do not create any commit with these changes.
sensitive1 g i t c h e r r y = p i c k == f f . . next
If history is linear and HEAD is an ancestor of next, update the working tree and advance the HEAD pointer to match
next. Otherwise, apply the changes introduced by those commits that are in next but not HEAD to the current branch,
creating a new commit for each new change.
sensitive1 g i t rev = l i s t == r e v e r s e master == README | g i t c h e r r y = p i c k =n == s t d i n
Apply the changes introduced by all commits on the master branch that touched README to the working tree and
index, so the result can be inspected and made into a single new commit if suitable.

3.8 TAGGING
São labels que podem ser aplicados a qualquer commit. Servem para marcar entregas, versão ou destacar alguma
informação importante do desenvolvimento do código.
Há diferentes tipos de tags:
ˆ Lightweight Tag
ˆ Anotated Tag
É possı́vel adicionar um tag na versão de commit atual ou em uma commit anterior.
É possı́vel comparar commits tageados chamando por suas tags, por ex: Duas versões de software e diferentes.
É possı́vel realizar push baseado no nome da Tag. Pode ser utilizado para upar novas versões.
Uma anotaded tag é uma tag que possui uma descrição inserida ao cadastrá-la. Dessa forma é possı́vel saber o que
ela significa, por exemplo.

3.8.1 APLICANDO TAGS PARA VERSIONAMENTO

É importante que em desenvolvimentos de software se respeite a aplicação de lógica de versionamento às versões do
software. É recomendado a utilização do versionamento semântico 2.0.0. Este versionamento implica em uma formação de
código composto por três partes:
ˆ versão Maior(MAJOR): quando fizer mudanças incompatı́veis na API, versão
ˆ Menor(MINOR): quando adicionar funcionalidades mantendo compatibilidade
ˆ versão de Correção(PATCH): quando corrigir falhas mantendo compatibilidade.
ˆ Rótulos adicionais para pré-lançamento(pre-release) e metadados de construção(build) estão disponı́veis como extensão
ao formato MAJOR.MINOR.PATCH.

Figura 9: Exemplo de versionamento semântico

Gabriel Cardoso Gaga’s Codex - Git Página 12


Gabriel Cardoso Gaga’s Codex - Git 13

Para mais informações sobre versionamento consultar a documentação disponı́vel em: https://semver.org/lang/pt-
BR/.
Uma maneira ideal de se marcar as versões de software é por meio de TAGs com descrições padrão de versionamento.
A figura 9 mostra o padrão de versionamento de software indicado e amplamente utilizado atualmente.

3.9 ARQUIVO README.MD


You can add a README file to your repository to tell other people why your project is useful, what they can do with
your project, and how they can use it.
You can add a README file to a repository to communicate important information about your project. A README,
along with a repository license, citation file, contribution guidelines, and a code of conduct, communicates expectations for
your project and helps you manage contributions.
If you put your README file in your repository’s hidden .github, root, or docs directory, GitHub will recognize and
automatically surface your README to repository visitors.
If a repository contains more than one README file, then the file shown is chosen from locations in the following
order: the .github directory, then the repository’s root directory, and finally the docs directory.

3.9.1 ELEMENTOS PADRÃO DO README

GitHub repository and Definition Example


README file elements

About An about section is generally several sentences https://github.com/EnvironmentOntology/envo#the-environment-ontology


long, appears at the top of a README.md file,
and describes the purpose of the repository

Citation The permanent URL and/or DOI of the repor- https://github.com/dagendresen/darwincore-germplasm#citation


ting format

Contribute GitHub repository managers will sometimes https://github.com/opengeospatial/weather-on-the-web#contributing


provide guidelines for contributing in the re-
pository’s README file or in a separate file
typically named CONTRIBUTING.md

Funding List of organizations financially supporting ef- https://github.com/NCEAS/oboe#citation-and-credits


forts

Getting started This section provides visitors to repository https://github.com/tdwg/dwc#getting-started


with guidance on what they can find on
GitHub page, and general folder structure

History Paragraph describing development of repor- https://github.com/NCEAS/eml#history


ting format or ontology

License License information describes parameters for https://github.com/EnvironmentOntology/environmental-exposure-


use of material in GitHub repository ontology/blob/master/LICENSE.txt

Resources Slack channel, wiki, other groups doing similar https://github.com/ESIPFed/science-on-schema.org//#resources


work

Terms Repositories for data reporting formats and https://github.com/EcologicalTraitData/ETS/blob/master/ETS.csv


ontologies may have files that contain requi-
red or optional vocabularies

Use case guide Example of how reporting format or ontology https://github.com/EcologicalTraitData/ETS/blob/master/bestpractice.Rmd


can be used

Version Release information, often provided in seman- https://github.com/NCEAS/eml/releases


tic versioning’s MAJOR.MINOR.PATCH for-
mat (https://semver.org/)

Visual structure Flow-chart or image file (JPG, PNG) depicting https://github.com/tdwg/dwc#repo-structure


repository directory structure

Tabela 2: Tabela com elementos de um README

Gabriel Cardoso Gaga’s Codex - Git Página 13


Gabriel Cardoso Gaga’s Codex - Git 14

3.9.2 SINTAXE DE FORMATAÇÃO DO README

Nome Descrição Exemplo


Normal text If you want to write normal text then You can write simple text like this
write simple text here, no need to add
any tags it will automatically convert
into text.
Headings For writing headings, you have to add # heading
hash # symbol at the beginning of the
line. The number of the hash symbol will
increase heading type will change accor-
ding to that.
Hyperlinks You can add a hyperlink in a markdown [link name](targetURL)
file by using the below tag.
Hyperlinks You can also write link title (While ho- [link name](targetURL ”Link title”)
vering over the link the title will appear)
Strong and italic text You can write strong and italic text by Italic text here
appending underscores before and en- **Bold Text here**
ding of the line, for italic text add double
star ** before and ending of the line for
strong/bold text.
StrikeThrough If you want to strike through a word or Strikethrough text
line then add two tilde symbol at the be-
ginning and end of the line.
Images You can add images in a markdown file ![imagename](TargetUrl)
by using the below tag.
Tables You can write a table by using the below —Name—Email—Address— ¡====== This is the heading of
format of text. the table
——-——–———-— ¡====== This is the separator.
—John—john@example.com—Address1— ¡=== This is the ta-
ble body.
Quotes If you want to write quotes the just add ¿Your quote looks like this.
a ¿ symbol at the beginning of the line.
Code You can write code by appending ‘ sym- forEach()’ method iterates each element of na array.
bol at the beginning and end of the line.
Code block If you want to write a block of code then “‘Language
add “‘ at starting and ending of the code. your code
“‘
You can specify your language after
the “‘ at starting of the line.
List You can write an ordered list, unordered 1. Item 1
list, and mixed list. 2. Item 2
3. Item 3
* Sub item 1
* Sub item 3
* Unordered item
* Unordered item
* Unordered item
Horizontal line If you want to add a horizontal line in Sample text
the markdown file then simply add — or ***
*** Sample text

Sobrescrito Place a text up. <sup> Texto </sup>
Subscrito Place a text down. <sub> Texto </sub>

Tabela 3: Sintaxe de formatação do README

Gabriel Cardoso Gaga’s Codex - Git Página 14


Gabriel Cardoso Gaga’s Codex - Git 15

3.9.3 AUTO-GENERATED TABLE OF CONTENTS FOR README FILES


For the rendered view of any Markdown file in a repository, including README files, GitHub will automatically generate
a table of contents based on section headings. You can view the table of contents for a README file by clicking the menu
icon at the top left of the rendered page.

3.9.4 GERADOR DE README FILE


Há geradores/editores com interface melhorada para arquivos .md que fazem a geração e edição mais fácil e rápida. O site
a seguir é um exemplo: https://rahuldkjain.github.io/gh-profile-readme-generator/

4 CONFLITOS NO GIT
Há basicamente duas maneiras de se resolver problemas de conflitos em código, um deles é verificar o próprio arquivo
e localizar onde o git marca o conflito. Ao excluir uma parte do texto onde há o conflito deixando somente o desejado, o Git
irá reconhecer o que foi priorizado.
Outra maneira é por meio de uma ferramenta de destaque de diferenças, o P4Merge é a ferramenta indicada para isso.
Para utilizar a ferramenta P4Merge basta subustituir o comando ”diff”por ”difftool”.

5 UTILIZANDO O GIT (COM GITHUB) NO WINDOWS


5.1 CRIANDO UM NOVO DIRETÓRIO GITHUB WEB
1. Acesse: https://github.com/;
2. Faça o login;
3. Localize na página o botão de ”+ New Repository”e clique-o;
4. Adicione um nome ao repositório que será criado;
5. É aconselhado preencher o campo de descrição;
6. Selecione se o repositório será público ou privado. Se for público todos que utilizam o github poderão ter acesso, caso
seja privado não;
7. Selecione a marca de ”Inicializar o repositório com um README”;
8. Caso queira, altere as demais opções;
9. Aperte o botão de finalizar o processo;
10. Repositório criado com sucesso!

5.2 CONFIGURANDO EDITOR DE TEXTO (SUBLIME) ALTERNATIVO NO GIT NO


WINDOWS PELO GITBASH
Para abrir o editor de texto como o Git Bash siga os passos:
1. Abra o windows explorer e clique em Propriedades do Meu computador.
2. Na janela de Propriedades do Sistema, clique na aba Avançado.
3. Em seguida clique em Variáveis de Ambiente
4. No campo de variáveis do sistema selecione a opção PAth da lista
5. Clique em editar
6. digite ao final do valor ”;”
7. Em seguida cole o endereço da pasta do editor de texto
8. Clique em Ok em todas as janelas e saia
Para configurar o editor de texto como o sublime digite o comando:
sensitive1 g i t c o n f i g == g l o b a l c o r e . e d i t o r ” ’ c : / program f i l e s / s u b l i m e t e x t /
s u b l i m e t e x t . exe ’ =w”

Gabriel Cardoso Gaga’s Codex - Git Página 15


Gabriel Cardoso Gaga’s Codex - Git 16

5.3 CONFIGURANDO O GIT NO WINDOWS PELO GITBASH


1. Abra o GitBash (Terminal do GIT);
2. digite os comandos:

sensitive1 g i t c o n f i g == g l o b a l u s e r . name ” G a b r i e l Cardoso ”


sensitive2 g i t c o n f i g == g l o b a l u s e r . e m a i l ” g a b r i e l f f c a r d o s o @ g m a i l . com”

3. Para conferir se as informações digitadas estão corretas digite o comando:

sensitive1 g i t c o n f i g == g l o b a l == l i s t

5.4 CLONANDO O NOVO DIRETÓRIO PARA O WINDOWS


1. Abra o GitBash (Terminal do GIT) de preferência já abra na pasta que deseja sincronizar com o Github;
2. Certifique-se de que o diretório atual do Git Bash esteja na pasta que deseja receber os arquivos de sincronização;
3. Localize na página do diretório do Github a sessão de URL para clonagem e copie o endereço apontado;
4. Digite o comando:

sensitive1 g i t c l o n e h t t p s : / / g i t h u b . com/ GabrielFFC /DocMan . g i t

5.5 ADICIONANDO UM ARQUIVO AO GITHUB - CAMINHO COMPLETO


1. Na pasta já sincronizada com o Github crie um arquivo chamado ”Codigo.txt”;
2. Dentro do arquivo escreva ”Um código de exemplo.”;
3. Abra o GitBash (Terminal do GIT) de preferência já abra na pasta que deseja sincronizar com o Github;
4. Certifique-se de que o diretório atual do Git Bash esteja na pasta que deseja receber os arquivos de sincronização;
5. No Git Bash digite o comando:

sensitive1 git status

6. Após o comando será possı́vel que o Git detectou que há um novo arquivo que não está rastreado. Para rastrear o
arquivo com o Git digite:

sensitive1 g i t add ” Codigo . t x t ”

7. O arquivo agora está adicionado ao Working Directory do git e será rastreado em relação às alterações realizadas;
8. Apesar de já colocar o arquivo como rastreado, ele somente se encontra registrado localmente na máquina, para ”su-
bir”o arquivo para o Github ainda são necessário alguns passos. É necessário realizar o Commit, para isso digite o
comando:

sensitive1 g i t commit =m ”Mensagem do p r i m e i r o commit . ”

9. Foi realizado o commit, ou seja, a oficialização local daquela versão do arquivo. Porém é necessário que o arquivo
seja enviado para a nuvem e o commit não faz isso. Deve-se utilizar o comando Push para ”empurrar”o arquivo para
a nuvem. Como boa prática, sempre é interessante realizar um ”Pull”antes do ”Push. O comando ”Pull”serve para
baixar todos os arquivos que venha a ser alterados por outros usuários ou diretamente pela interface Web. Execute os
seguintes comandos:

sensitive1 git pull


sensitive2 g i t push

Gabriel Cardoso Gaga’s Codex - Git Página 16


Gabriel Cardoso Gaga’s Codex - Git 17

10. A mensagem de retorno do Git mostrará qual o resultado da operação. Neste caso especı́fico mostrará que o arquivo
foi empurrado para o Github com sucesso.
11. Acesse o Github pelo navegador e atualize a página. Verá que o novo arquivo foi adicionado no repositório remoto.

5.6 OPERANDO BRANCHES


5.6.1 CRIANDO UMA NOVA BRANCH + MERGE FAST FORWARD

Ao criar um novo repositório no Git também é criada uma branch padrão chamada de main. É interessante que para o
desenvolvemento sejam utilizadas outras Branches por motivos de rastreabilidade e segurança. Para criar uma nova branch
siga os passos a seguir:
1. Para criar uma nova branch utilize o comando:
sensitive1 g i t branch d e v e l o p

2. É possı́vel renomear uma branch já existente com o comando:


sensitive1 g i t branch =m f e a t u r e 1

3. Também é possı́vel apagar uma branch com o comando:


sensitive1 g i t branch =d f e a t u r e 1

4. Exitem branches que podem ser locais ou remotas. Para visualizar quais branchs existem no repositorio digite o
comando:
sensitive1 g i t branch =a

5. Com o resultado do comando anterior é possı́vel nota um pequeno asterisco (*). Ele indica a branch atual, ou seja,
alterações realizadas serão commitadas na branch atual. Para mudar de branch execute o comando:
sensitive1 g i t checkout develop

6. A partir desse momento qualquer alteração realizada será atrelada à branch ativa.
7. Não é interessante deixar branches soltas no repositório. Para isso existe o comando merge. Ele junta o final de uma
branch a outra. Para realizar o merge deverá commitar todas as pendências. Com o diretorio livre, dê um checkout
para a branch que rececberá o merge.
sensitive1 g i t c h e c k o u t main

8. Já na Branch que receberá o merge utilize o código:


sensitive1 g i t merge d e v e l o p

9. Para subir um push em uma brnach diferente da main utilize o comando:


sensitive1 g i t push o r i g i n d e v e l o p

10. Para verificar o log das operações realizadas utilize o comando:


sensitive1 g i t l o g == o n e l i n e ==graph == d e c o r a t e

Os comando utilizados nessa parte farão com que a branch seja inserida na branch original, sem ficar um ”galho”por fora.

5.6.2 APLICANDO COMANDO MERGE NOT FAST FORWARD


Para rastrear o desenvolvimento de um recursos especı́fico é necessário utilizar merge que não seja fast forward.
1. Na branch que receberá o merge execute o comando:
sensitive1 g i t merge d e v e l o p ==no= f f

2. Caso uma mensagem apareça sobre um conflito e esteja utilizando o Git BASH pressione ”ESC”e em seguida ”:q!”.
Pressione ”Enter”.
3. Para verificar as operações insira o código:
sensitive1 g i t l o g == o n e l i n e ==graph == d e c o r a t e

Gabriel Cardoso Gaga’s Codex - Git Página 17


Gabriel Cardoso Gaga’s Codex - Git 18

5.7 REALIZANDO COMPARAÇÕES


5.7.1 WORKING DIRECTORY VS STAGING AREA
Quando há um arquivo modificado é possı́vel verificar as diferenças por meio do comando abaixo:
sensitive1 git diff

5.7.2 WORKING DIRECTORY VS REPOSITORY


O comando abaixo mostra a diferença da versão commit atual com o últmo commit no repositório.
sensitive1 g i t d i f f HEAD

5.7.3 STAGING AREA VS REPOSITORY


O comando abaixo mostra a diferença da versão staging area com o últmo commitno repositório.
sensitive1 g i t d i f f == s t a g e d HEAD

5.7.4 COMPARAÇÃO DE UM ARQUIVO ESPECÍFICO


O comando abaixo mostra a diferença limitando a um arquivo.
sensitive1 g i t d i f f == F i l e 4 . t x t

5.7.5 COMPARAÇÃO DE UM COMMIT COM O ÚLTIMO COMMIT


O comando abaixo mostra a diferença entre um commit especı́fico com o commit atual.
sensitive1 g i t d i f f a e 4 3 4 5 f HEAD
Outra forma de comparar o commit com o seu antecessor é:
sensitive1 g i t d i f f HEAD HEADˆ

5.7.6 COMPARAÇÃO COM FERRAMENTA GRÁFICA P4MERGE


Para realizar a comparação de uma maneira mais rápida e clara é possı́vel utilizar a ferramenta P4MERGE. Ela mostra os
trechos de códigos que estão deiferentes entre si. EX:

Figura 10: Tela do Git Bash para difftool

Gabriel Cardoso Gaga’s Codex - Git Página 18


Gabriel Cardoso Gaga’s Codex - Git 19

Figura 11: Tela do P4Merge evidenciando diferenças

5.8 APLICANDO REBASE


1. Crie uma nova branch chamada ”rebasebranch”:

sensitive1 g i t c h e c k o u t =b r e b a s e b r a n c h

2. Realize alguma alteração em um arquivo do repositório;


3. Aplique um commit:

sensitive1 g i t commit =m ” Arquivo a d i c i o n a d o para r e a l i z a r o Rebase . ”

4. Volte para a branch main:

sensitive1 g i t c h e c k o u t main

5. Realize a edição de outro arquivo;


6. Realize outro commit:

sensitive1 g i t commit =m ” Adicionando o u t r a a l t e r a c a o . ”

7. Mova para a branch criada ”rebasebranch”:

sensitive1 g i t checkout rebasebranch

8. Aplique o rebase:

sensitive1 g i t r e b a s e main

Gabriel Cardoso Gaga’s Codex - Git Página 19


Gabriel Cardoso Gaga’s Codex - Git 20

5.9 OPERANDO STASHES


5.9.1 APLICANDO STASH
1. Altere ou crie algum arquivo para que o working directory tenha alguma pendência. verifique a pendência com o
comando:
sensitive1 git status

2. Para aplicar o stash digite:


sensitive1 git stash

5.9.2 APLICANDO O STASH EM ARQUIVOS NÃO RASTREADOS


1. Para aplicar stash em todos os arquivos não commitados no diretório utilize o comando:
sensitive1 g i t s t a s h =u

5.9.3 LIMPANDO O STASH


1. Para limpar o stash utilize o comando:
sensitive1 g i t s t a s h drop

5.9.4 RESTAURANDO O STASH


1. Para voltar o arquivo que sofreu o stash utilize o comando:
sensitive1 g i t s t a s h apply

2. Também é possı́vel restaruar o stash por completo como o comando:


sensitive1 g i t s t a s h pop

5.9.5 APLICANDO O STASHES MULTIPLOS


1. Para aplicar múltiplos stashes utilize o comando git stash especificando o nome do stash, por exemplo:
sensitive1 g i t stash save ” simple changes ”

2. Em seguida provoque outra alteração em algum arquivo e insira outro stash:


sensitive1 g i t stash save ” another stash ”

3. Realize quantos stash preferir e ao concluir utilize o seguinte código para visualizar os stashes salvos:
sensitive1 git stash l i s t

4. Note que o último stash realizado fica na posição 0.

5.9.6 VISUALIZANDO UM STASH ESEPCÍFICO


1. Para visualizar um stash especı́fico utilize:
sensitive1 g i t s t a s h show stash@ {1}

5.9.7 RESTAURANDO UM STASH ESEPCÍFICO


1. Para restaurar um stash especı́fico utilize:
sensitive1 g i t s t a s h apply stash@ {1}

Gabriel Cardoso Gaga’s Codex - Git Página 20


Gabriel Cardoso Gaga’s Codex - Git 21

5.9.8 DELETANDO UM STASH ESEPCÍFICO


1. Para deletar um stash especı́fico utilize:
sensitive1 g i t s t a s h drop stash@ {1}

5.9.9 DELETANDO TODOS OS STASHES


1. Para deletar todos os stashes utilize:
sensitive1 git stash clear

5.9.10 APLICANDO STASH EM UMA BRANCH


1. Para aplicar um stash em uma branch utilize:
sensitive1 g i t s t a s h =u
sensitive2 g i t s t a s h branch nome da brach

5.10 OPERANDO TAGS


5.10.1 VISUALIZAR LISTA DE TAGS EXISTENTES
1. Para visualizar a lista de tags utilize:
sensitive1 g i t t a g == l i s t

5.10.2 VISUALIZANDO INFORMAÇÕES DE UMA TAG


1. Para visualizar informações de uma tag utilize:
sensitive1 g i t show Mytag

5.10.3 CRIANDO UMA LIGTHWEIGHT TAG


1. Para criar uma lightweight tag utilize:
sensitive1 g i t t a g Mytag

5.10.4 DELETANDO UMA LIGTHWEIGHT TAG


1. Para deletar uma lightweight tag utilize:
sensitive1 g i t t a g == d e l e t e Mytag

5.10.5 CRIANDO UMA ANNOTATED TAG


1. Para criar uma lightweight tag utilize:
sensitive1 g i t t a g =a Mytag =m ” Esta Tage s e r e f e r e a b l a b l a b l a . . . ”

5.10.6 COMPARANDO DIFERENÇAS ENTRE TAGS


1. Para comparar duas tags utilize:
sensitive1 g i t d i f f Mytag Mytag2

2. Caso prefira visualizar as diferenças com o P4Merge utilize:


sensitive1 g i t d i f f t o o l Mytag Mytag2

Gabriel Cardoso Gaga’s Codex - Git Página 21


Gabriel Cardoso Gaga’s Codex - Git 22

5.10.7 APLICANDO UMA TAG EM UM COMMIT ANTERIOR


1. Para adicionar uma tag a um commit anterior utilize:
sensitive1 g i t t a g =a Mytag hash =do=comit =a= r e c e b e r =a=t a g =m ” Texto de
r e f e r e n c i a da t a g ”

5.10.8 ATUALIZAR UMA TAG


1. Para atualizar uma tag já criada e associada a um commit utilize:
sensitive1 g i t t a g =a Mytag = f hash =do=commit=a= r e c e b e r =a=t a g =m ” Texto de
r e f e r e n c i a da Tag”

5.10.9 REALIZAR UM PUSH A PARTIR DE UMA TAG


1. Para realizar um Push a partir de uma tag utilize:
sensitive1 g i t push o r i g i n Mytag

5.10.10 REALIZAR PUSH DE TODAS AS TAG


1. Para realizar um Push de todas as tags utilize:
sensitive1 g i t push o r i g i n master == t a g s

5.10.11 DELETAR UMA TAG QUE ESTEJA NO GITHUB (REMOTE REPO)


1. Para deletar uma tag que esteja no Github utilize:
sensitive1 g i t push o r i g i n : Mytag

6 LISTA DE COMANDOS
6.1 GIT OPTIONS
1. Prints the Git suite version that the git program came from. This option is internally converted to git version ... and
accepts the same options as the git-version[1] command. If –help is also given, it takes precedence over –version.
sensitive1 =v
sensitive2 == v e r s i o n

2. Prints the synopsis and a list of the most commonly used commands. If the option –all or -a is given then all available
commands are printed. If a Git command is named this option will bring up the manual page for that command.
Other options are available to control how the manual page is displayed. See git-help[1] for more information, because
git –help ... is converted internally into git help...
sensitive1 =h
sensitive2 == h e l p

3. Run as if git was started in ¡path> instead of the current working directory. When multiple -C options are given, each
subsequent non-absolute -C ¡path> is interpreted relative to the preceding -C ¡path>. If ¡path> is present but empty,
e.g. -C , then the current working directory is left unchanged. This option affects options that expect path name like
–git-dir and –work-tree in that their interpretations of the path names would be made relative to the working directory
caused by the -C option. For example the following invocations are equivalent:

git –git-dir=a.git –work-tree=b -C c status


git –git-dir=c/a.git –work-tree=c/b status
sensitive1 =C <path $ >$

Gabriel Cardoso Gaga’s Codex - Git Página 22


Gabriel Cardoso Gaga’s Codex - Git 23

4. Pass a configuration parameter to the command. The value given will override values from configuration files. The
¡name> is expected in the same format as listed by git config (subkeys separated by dots).
Note that omitting the = in git -c foo.bar ... is allowed and sets foo.bar to the boolean true value (just like [foo]bar
would in a config file). Including the equals but with an empty value (like git -c foo.bar= ...) sets foo.bar to the empty
string which git config –type=bool will convert to false.
sensitive1 =c <name$>$=<va lue $ >$

5. Like -c ¡name>=¡value>, give configuration variable ¡name> a value, where ¡envvar> is the name of an environment
variable from which to retrieve the value. Unlike -c there is no shortcut for directly setting the value to an empty string,
instead the environment variable itself must be set to the empty string. It is an error if the ¡envvar> does not exist
in the environment. ¡envvar> may not contain an equals sign to avoid ambiguity with ¡name> containing one. This is
useful for cases where you want to pass transitory configuration options to git, but are doing so on OS’s where other
processes might be able to read your cmdline (e.g. /proc/self/cmdline), but not your environ (e.g. /proc/self/environ).
That behavior is the default on Linux, but may not be on your system. Note that this might add security for variables
such as http.extraHeader where the sensitive information is part of the value, but not e.g. url.¡base>.insteadOf where
the sensitive information can be part of the key.
sensitive1 == c o n f i g =env=<name>=<envvar>

6. Path to wherever your core Git programs are installed. This can also be controlled by setting the GIT EXEC PATH
environment variable. If no path is given, git will print the current setting and then exit.
sensitive1 ==exec =path[=<path >]

7. Print the path, without trailing slash, where Git’s HTML documentation is installed and exit.
sensitive1 ==html=path

8. Print the manpath (see man(1)) for the man pages for this version of Git and exit.
sensitive1 ==man=path

9. Print the path where the Info files documenting this version of Git are installed and exit.
sensitive1 == i n f o =path

10. Pipe all output into less (or if set, $PAGER) if standard output is a terminal. This overrides the pager.¡cmd>
configuration options.
sensitive1 =p
sensitive2 == p a g i n a t e

11. Do not pipe Git output into a pager.


sensitive1 =P
sensitive2 ==no=p a g e r

12. Set the path to the repository (”.git”directory). This can also be controlled by setting the GIT DIR environment
variable. It can be an absolute path or relative path to current working directory. Specifying the location of the
”.git”directory using this option (or GIT DIR environment variable) turns off the repository discovery that tries to find
a directory with ”.git”subdirectory (which is how the repository and the top-level of the working tree are discovered),
and tells Git that you are at the top level of the working tree. If you are not at the top-level directory of the working
tree, you should tell Git where the top-level of the working tree is, with the
sensitive1 == g i t = d i r=<path>

13. If you just want to run git as if it was started in ¡path> then use git -C ¡path>.
sensitive1 ==work= t r e e=<path> o p t i o n ( o r GIT\ WORK\ TREE environment
variable )

14. Set the path to the working tree. It can be an absolute path or a path relative to the current working directory. This
can also be controlled by setting the GIT WORK TREE environment variable and the core.worktree configuration
variable (see core.worktree in git-config[1] for a more detailed discussion).

Gabriel Cardoso Gaga’s Codex - Git Página 23


Gabriel Cardoso Gaga’s Codex - Git 24

sensitive1 ==work= t r e e=<path>

15. Set the Git namespace. See gitnamespaces[7] for more details. Equivalent to setting the GIT NAMESPACE environ-
ment variable.
sensitive1 ==namespace=<path>

16. Currently for internal use only. Set a prefix which gives a path from above a repository down to its root. One use is
to give submodules context about the superproject that invoked it.
sensitive1 ==super = p r e f i x=<path>

17. Treat the repository as a bare repository. If GIT DIR environment is not set, it is set to the current working directory.
sensitive1 == b a r e

18. Do not use replacement refs to replace Git objects. See git-replace[1] for more information.
sensitive1 ==no= r e p l a c e = o b j e c t s

19. Treat pathspecs literally (i.e. no globbing, no pathspec magic). This is equivalent to setting the GIT LITERAL PATHSPECS
environment variable to 1.
sensitive1 == l i t e r a l =p a t h s p e c s

20. Add ”glob”magic to all pathspec. This is equivalent to setting the GIT GLOB PATHSPECS environment variable to
1. Disabling globbing on individual pathspecs can be done using pathspec magic ”:(literal)”
sensitive1 ==glob =p a t h s p e c s

21. Add ”literal”magic to all pathspec. This is equivalent to setting the GIT NOGLOB PATHSPECS environment variable
to 1. Enabling globbing on individual pathspecs can be done using pathspec magic ”:(glob)”
sensitive1 ==noglob =p a t h s p e c s

22. Add ”icase”magic to all pathspec. This is equivalent to setting the GIT ICASE PATHSPECS environment variable to
1.
sensitive1 == i c a s e =p a t h s p e c s

23. Do not perform optional operations that require locks. This is equivalent to setting the GIT OPTIONAL LOCKS to
0.
sensitive1 ==no= o p t i o n a l = l o c k s

24. List commands by group. This is an internal/experimental option and may change or be removed in the future. Suppor-
ted groups are: builtins, parseopt (builtin commands that use parse-options), main (all commands in libexec directory),
others (all other commands in $PATH that have git- prefix), list-¡category> (see categories in command-list.txt), nohel-
pers (exclude helper commands), alias and config (retrieve command list from config variable completion.commands)
sensitive1 == l i s t =cmds=group [ , group . . . ]

6.1.1 MAIN PORCELAIN COMMANDS


Main porcelain commands

1. git-add[1]
Add file contents to the index
2. git-am[1]
Apply a series of patches from a mailbox

3. git-archive[1]
Create an archive of files from a named tree

Gabriel Cardoso Gaga’s Codex - Git Página 24


Gabriel Cardoso Gaga’s Codex - Git 25

4. git-bisect[1]
Use binary search to find the commit that introduced a bug
5. git-branch[1]
List, create, or delete branches
6. git-bundle[1]
Move objects and refs by archive
7. git-checkout[1]
Switch branches or restore working tree files
8. git-cherry-pick[1]
Apply the changes introduced by some existing commits
9. git-citool[1]
Graphical alternative to git-commit
10. git-clean[1]
Remove untracked files from the working tree
11. git-clone[1]
Clone a repository into a new directory
12. git-commit[1]
Record changes to the repository
13. git-describe[1]
Give an object a human readable name based on an available ref
14. git-diff[1]
Show changes between commits, commit and working tree, etc
15. git-fetch[1]
Download objects and refs from another repository
16. git-format-patch[1]
Prepare patches for e-mail submission
17. git-gc[1]
Cleanup unnecessary files and optimize the local repository
18. git-grep[1]
Print lines matching a pattern
19. git-gui[1]
A portable graphical interface to Git
20. git-init[1]
Create an empty Git repository or reinitialize an existing one
21. git-log[1]
Show commit logs
22. git-maintenance[1]
Run tasks to optimize Git repository data
23. git-merge[1]
Join two or more development histories together
24. git-mv[1]
Move or rename a file, a directory, or a symlink

Gabriel Cardoso Gaga’s Codex - Git Página 25


Gabriel Cardoso Gaga’s Codex - Git 26

25. git-notes[1]
Add or inspect object notes
26. git-pull[1]
Fetch from and integrate with another repository or a local branch

27. git-push[1]
Update remote refs along with associated objects
28. git-range-diff[1]
Compare two commit ranges (e.g. two versions of a branch)

29. git-rebase[1]
Reapply commits on top of another base tip
30. git-reset[1]
Reset current HEAD to the specified state

31. git-restore[1]
Restore working tree files
32. git-revert[1]
Revert some existing commits

33. git-rm[1]
Remove files from the working tree and from the index
34. git-shortlog[1]
Summarize git log output

35. git-show[1]
Show various types of objects
36. git-sparse-checkout[1]
Reduce your working tree to a subset of tracked files

37. git-stash[1]
Stash the changes in a dirty working directory away
38. git-status[1]
Show the working tree status

39. git-submodule[1]
Initialize, update or inspect submodules
40. git-switch[1]
Switch branches

41. git-tag[1]
Create, list, delete or verify a tag object signed with GPG
42. gitk[1]
The Git repository browser

Gabriel Cardoso Gaga’s Codex - Git Página 26


Gabriel Cardoso Gaga’s Codex - Git 27

6.1.2 ANCILLARY COMMANDS


Manipulators
1. git-config[1]
Get and set repository or global options
2. git-fast-export[1]
Git data exporter
3. git-fast-import[1]
Backend for fast Git data importers
4. git-filter-branch[1]
Rewrite branches
5. git-mergetool[1]
Run merge conflict resolution tools to resolve merge conflicts
6. git-pack-refs[1]
Pack heads and tags for efficient repository access
7. git-prune[1]
Prune all unreachable objects from the object database
8. git-reflog[1]
Manage reflog information
9. git-remote[1]
Manage set of tracked repositories
10. git-repack[1]
Pack unpacked objects in a repository
11. git-replace[1]
Create, list, delete refs to replace objects
Interrogators:
1. git-annotate[1]
Annotate file lines with commit information
2. git-blame[1]
Show what revision and author last modified each line of a file
3. git-bugreport[1]
Collect information for user to file a bug report
4. git-count-objects[1]
Count unpacked number of objects and their disk consumption
5. git-difftool[1]
Show changes using common diff tools
6. git-fsck[1]
Verifies the connectivity and validity of the objects in the database
7. git-help[1]
Display help information about Git
8. git-instaweb[1]
Instantly browse your working repository in gitweb

Gabriel Cardoso Gaga’s Codex - Git Página 27


Gabriel Cardoso Gaga’s Codex - Git 28

9. git-merge-tree[1]
Show three-way merge without touching index
10. git-rerere[1]
Reuse recorded resolution of conflicted merges

11. git-show-branch[1]
Show branches and their commits
12. git-verify-commit[1]
Check the GPG signature of commits

13. git-verify-tag[1]
Check the GPG signature of tags
14. git-whatchanged[1]
Show logs with difference each commit introduces

15. gitweb[1]
Git web interface (web frontend to Git repositories)

6.1.3 INTERACTING WITH OTHERS


These commands are to interact with foreign SCM and with other people via patch over e-mail.

1. git-archimport[1]
Import a GNU Arch repository into Git
2. git-cvsexportcommit[1]
Export a single commit to a CVS checkout

3. git-cvsimport[1]
Salvage your data out of another SCM people love to hate
4. git-cvsserver[1]
A CVS server emulator for Git

5. git-imap-send[1]
Send a collection of patches from stdin to an IMAP folder
6. git-p4[1]
Import from and submit to Perforce repositories

7. git-quiltimport[1]
Applies a quilt patchset onto the current branch
8. git-request-pull[1]
Generates a summary of pending changes

9. git-send-email[1]
Send a collection of patches as emails
10. git-svn[1]
Bidirectional operation between a Subversion repository and Git

Gabriel Cardoso Gaga’s Codex - Git Página 28


Gabriel Cardoso Gaga’s Codex - Git 29

6.1.4 RESET, RESTORE AND REVERT


There are three commands with similar names: git reset, git restore and git revert.
1. git-revert[1] is about making a new commit that reverts the changes made by other commits.

2. git-restore[1] is about restoring files in the working tree from either the index or another commit. This command does
not update your branch. The command can also be used to restore files in the index from another commit.
3. git-reset[1] is about updating your branch, moving the tip in order to add or remove commits from the branch. This
operation changes the commit history.
git reset can also be used to restore the index, overlapping with git restore.

6.2 LOW-LEVEL COMMANDS (PLUMBING)


Although Git includes its own porcelain layer, its low-level commands are sufficient to support development of alternative
porcelains. Developers of such porcelains might start by reading about git-update-index[1] and git-read-tree[1].
The interface (input, output, set of options and the semantics) to these low-level commands are meant to be a lot more
stable than Porcelain level commands, because these commands are primarily for scripted use. The interface to Porcelain
commands on the other hand are subject to change in order to improve the end user experience.
The following description divides the low-level commands into commands that manipulate objects (in the repository,
index, and working tree), commands that interrogate and compare objects, and commands that move objects and references
between repositories.

6.2.1 MANIPULATION COMMANDS


1. git-apply[1]
Apply a patch to files and/or to the index
2. git-checkout-index[1]
Copy files from the index to the working tree
3. git-commit-graph[1]
Write and verify Git commit-graph files
4. git-commit-tree[1]
Create a new commit object
5. git-hash-object[1]
Compute object ID and optionally creates a blob from a file
6. git-index-pack[1]
Build pack index file for an existing packed archive
7. git-merge-file[1]
Run a three-way file merge
8. git-merge-index[1]
Run a merge for files needing merging
9. git-mktag[1]
Creates a tag object with extra validation
10. git-mktree[1]
Build a tree-object from ls-tree formatted text
11. git-multi-pack-index[1]
Write and verify multi-pack-indexes
12. git-pack-objects[1]
Create a packed archive of objects

Gabriel Cardoso Gaga’s Codex - Git Página 29


Gabriel Cardoso Gaga’s Codex - Git 30

13. git-prune-packed[1]
Remove extra objects that are already in pack files
14. git-read-tree[1]
Reads tree information into the index
15. git-symbolic-ref[1]
Read, modify and delete symbolic refs
16. git-unpack-objects[1]
Unpack objects from a packed archive
17. git-update-index[1]
Register file contents in the working tree to the index
18. git-update-ref[1]
Update the object name stored in a ref safely
19. git-write-tree[1]
Create a tree object from the current index

6.3 INTERROGATION COMMANDS


1. git-cat-file[1]
Provide content or type and size information for repository objects
2. git-cherry[1]
Find commits yet to be applied to upstream
3. git-diff-files[1]
Compares files in the working tree and the index
4. git-diff-index[1]
Compare a tree to the working tree or index
5. git-diff-tree[1]
Compares the content and mode of blobs found via two tree objects
6. git-for-each-ref[1]
Output information on each ref
7. git-for-each-repo[1]
Run a Git command on a list of repositories
8. git-get-tar-commit-id[1]
Extract commit ID from an archive created using git-archive
9. git-ls-files[1]
Show information about files in the index and the working tree
10. git-ls-remote[1]
List references in a remote repository
11. git-ls-tree[1]
List the contents of a tree object
12. git-merge-base[1]
Find as good common ancestors as possible for a merge
13. git-name-rev[1]
Find symbolic names for given revs

Gabriel Cardoso Gaga’s Codex - Git Página 30


Gabriel Cardoso Gaga’s Codex - Git 31

14. git-pack-redundant[1]
Find redundant pack files
15. git-rev-list[1]
Lists commit objects in reverse chronological order
16. git-rev-parse[1]
Pick out and massage parameters
17. git-show-index[1]
Show packed archive index
18. git-show-ref[1]
List references in a local repository
19. git-unpack-file[1]
Creates a temporary file with a blob’s contents
20. git-var[1]
Show a Git logical variable
21. git-verify-pack[1]
Validate packed Git archive files

In general, the interrogate commands do not touch the files in the working tree.

6.3.1 SYNCING REPOSITORIES


1. git-daemon[1]
A really simple server for Git repositories
2. git-fetch-pack[1]
Receive missing objects from another repository
3. git-http-backend[1]
Server side implementation of Git over HTTP
4. git-send-pack[1]
Push objects over Git protocol to another repository
5. git-update-server-info[1]
Update auxiliary info file to help dumb servers

The following are helper commands used by the above; end users typically do not use them directly.
1. git-http-fetch[1]
Download from a remote Git repository via HTTP
2. git-http-push[1]
Push objects over HTTP/DAV to another repository
3. git-receive-pack[1]
Receive what is pushed into the repository
4. git-shell[1]
Restricted login shell for Git-only SSH access
5. git-upload-archive[1]
Send archive back to git-archive
6. git-upload-pack[1]
Send objects packed back to git-fetch-pack

Gabriel Cardoso Gaga’s Codex - Git Página 31


Gabriel Cardoso Gaga’s Codex - Git 32

6.3.2 INTERNAL HELPER COMMANDS


These are internal helper commands used by other commands; end users typically do not use them directly.
1. git-check-attr[1]
Display gitattributes information
2. git-check-ignore[1]
Debug gitignore / exclude files
3. git-check-mailmap[1]
Show canonical names and email addresses of contacts
4. git-check-ref-format[1]
Ensures that a reference name is well formed
5. git-column[1]
Display data in columns
6. git-credential[1]
Retrieve and store user credentials
7. git-credential-cache[1]
Helper to temporarily store passwords in memory
8. git-credential-store[1]
Helper to store credentials on disk
9. git-fmt-merge-msg[1]
Produce a merge commit message
10. git-hook[1]
Run git hooks
11. git-interpret-trailers[1]
Add or parse structured information in commit messages
12. git-mailinfo[1]
Extracts patch and authorship from a single e-mail message
13. git-mailsplit[1]
Simple UNIX mbox splitter program
14. git-merge-one-file[1]
The standard helper program to use with git-merge-index
15. git-patch-id[1]
Compute unique ID for a patch
16. git-sh-i18n[1]
Git’s i18n setup code for shell scripts
17. git-sh-setup[1]
Common Git shell script setup code
18. git-stripspace[1]
Remove unnecessary whitespace

Gabriel Cardoso Gaga’s Codex - Git Página 32


Gabriel Cardoso Gaga’s Codex - Git 33

6.4 GUIDES
The following documentation pages are guides about Git concepts.
1. gitattributes[5]
Defining attributes per path
2. gitcli[7]
Git command-line interface and conventions
3. gitcore-tutorial[7]
A Git core tutorial for developers
4. gitcredentials[7]
Providing usernames and passwords to Git
5. gitcvs-migration[7]
Git for CVS users
6. gitdiffcore[7]
Tweaking diff output
7. giteveryday[7]
A useful minimum set of commands for Everyday Git
8. gitfaq[7]
Frequently asked questions about using Git
9. gitglossary[7]
A Git Glossary
10. githooks[5]
Hooks used by Git
11. gitignore[5]
Specifies intentionally untracked files to ignore
12. gitmailmap[5]
Map author/committer names and/or E-Mail addresses
13. gitmodules[5]
Defining submodule properties
14. gitnamespaces[7]
Git namespaces
15. gitremote-helpers[7]
Helper programs to interact with remote repositories
16. gitrepository-layout[5]
Git Repository Layout
17. gitrevisions[7]
Specifying revisions and ranges for Git
18. gitsubmodules[7]
Mounting one repository inside another
19. gittutorial[7]
A tutorial introduction to Git
20. gittutorial-2[7]
A tutorial introduction to Git: part two
21. gitworkflows[7]
An overview of recommended workflows with Git

Gabriel Cardoso Gaga’s Codex - Git Página 33


Gabriel Cardoso Gaga’s Codex - Git 34

6.5 IDENTIFIER TERMINOLOGY


1. <object>
Indicates the object name for any type of object.

2. <blob>
Indicates a blob object name.
3. <tree>
Indicates a tree object name.

4. <commit>
Indicates a commit object name.
5. <tree-ish>
Indicates a tree, commit or tag object name. A command that takes a <tree-ish> argument ultimately wants to
operate on a <tree> object but automatically dereferences <commit> and <tag> objects that point at a <tree>.
6. <commit-ish>
Indicates a commit or tag object name. A command that takes a <commit-ish> argument ultimately wants to operate
on a <commit> object but automatically dereferences <tag> objects that point at a <commit>.
7. <type>
Indicates that an object type is required. Currently one of: blob, tree, commit, or tag.
8. <file>
Indicates a filename - almost always relative to the root of the tree structure GIT INDEX FILE describes.

6.6 SYMBOLIC IDENTIFIERS


Any Git command accepting any <object> can also use the following symbolic notation:
ˆ HEAD
indicates the head of the current branch.
ˆ <tag>
a valid tag name (i.e. a refs/tags/<tag> reference).
ˆ <head>
a valid head name (i.e. a refs/heads/<head> reference).
For a more complete list of ways to spell object names, see ”SPECIFYING REVISIONS”section in gitrevisions[7].

6.7 ENVIRONMENT VARIABLES


6.7.1 THE GIT REPOSITORY
1. GIT INDEX FILE
This environment allows the specification of an alternate index file. If not specified, the default of $GIT DIR/index is
used.

2. GIT INDEX VERSION


This environment variable allows the specification of an index version for new repositories. It won’t affect existing
index files. By default index file version 2 or 3 is used. See git-update-index[1] for more information.
3. GIT OBJECT DIRECTORY
If the object storage directory is specified via this environment variable then the sha1 directories are created underneath
- otherwise the default $GIT DIR/objects directory is used.

Gabriel Cardoso Gaga’s Codex - Git Página 34


Gabriel Cardoso Gaga’s Codex - Git 35

4. GIT ALTERNATE OBJECT DIRECTORIES


Due to the immutable nature of Git objects, old objects can be archived into shared, read-only directories. This variable
specifies a ”:”separated (on Windows ”;”separated) list of Git object directories which can be used to search for Git
objects. New objects will not be written to these directories.
Entries that begin with ”(double-quote) will be interpreted as C-style quoted paths, removing leading and trailing
double-quotes and respecting backslash escapes. E.g., the value ”path-with--̈and-:-in-it”:vanilla-path has two paths:
path-with--and-:-in-it and vanilla-path.
5. GIT DIR
If the GIT DIR environment variable is set then it specifies a path to use instead of the default .git for the base of the
repository. The –git-dir command-line option also sets this value.
6. GIT WORK TREE
Set the path to the root of the working tree. This can also be controlled by the –work-tree command-line option and
the core.worktree configuration variable.
7. GIT NAMESPACE
Set the Git namespace; see gitnamespaces[7] for details. The –namespace command-line option also sets this value.
8. GIT CEILING DIRECTORIES
This should be a colon-separated list of absolute paths. If set, it is a list of directories that Git should not chdir up into
while looking for a repository directory (useful for excluding slow-loading network directories). It will not exclude the
current working directory or a GIT DIR set on the command line or in the environment. Normally, Git has to read the
entries in this list and resolve any symlink that might be present in order to compare them with the current directory.
However, if even this access is slow, you can add an empty entry to the list to tell Git that the subsequent entries are not
symlinks and needn’t be resolved; e.g., GIT CEILING DIRECTORIES=/maybe/symlink::/very/slow/non/symlink.
9. GIT DISCOVERY ACROSS FILESYSTEM
When run in a directory that does not have ”.git”repository directory, Git tries to find such a directory in the parent
directories to find the top of the working tree, but by default it does not cross filesystem boundaries. This environment
variable can be set to true to tell Git not to stop at filesystem boundaries. Like GIT CEILING DIRECTORIES, this
will not affect an explicit repository directory set via GIT DIR or on the command line.
10. GIT COMMON DIR
If this variable is set to a path, non-worktree files that are normally in $GIT DIR will be taken from this path
instead. Worktree-specific files such as HEAD or index are taken from $GIT DIR. See gitrepository-layout[5] and
git-worktree[1] for details. This variable has lower precedence than other path variables such as GIT INDEX FILE,
GIT OBJECT DIRECTORY]
11. GIT DEFAULT HASH
If this variable is set, the default hash algorithm for new repositories will be set to this value. This value is currently
ignored when cloning; the setting of the remote repository is used instead. The default is ”sha1”. THIS VARIABLE
IS EXPERIMENTAL! See –object-format in git-init[1].

6.7.2 GIT COMMITS


1. GIT AUTHOR NAME
The human-readable name used in the author identity when creating commit or tag objects, or when writing reflogs.
Overrides the user.name and author.name configuration settings.
2. GIT AUTHOR EMAIL
The email address used in the author identity when creating commit or tag objects, or when writing reflogs. Overrides
the user.email and author.email configuration settings.
3. GIT AUTHOR DATE
The date used for the author identity when creating commit or tag objects, or when writing reflogs. See git-commit[1]
for valid formats.
4. GIT COMMITTER NAME
The human-readable name used in the committer identity when creating commit or tag objects, or when writing reflogs.
Overrides the user.name and committer.name configuration settings.

Gabriel Cardoso Gaga’s Codex - Git Página 35


Gabriel Cardoso Gaga’s Codex - Git 36

5. GIT COMMITTER EMAIL


The email address used in the author identity when creating commit or tag objects, or when writing reflogs. Overrides
the user.email and committer.email configuration settings.
6. GIT COMMITTER DATE
The date used for the committer identity when creating commit or tag objects, or when writing reflogs. See git-
commit[1] for valid formats. EMAIL
The email address used in the author and committer identities if no other relevant environment variable or configuration
setting has been set.

6.7.3 GIT DIFFS


1. GIT DIFF OPTS
Only valid setting is --unified=??”or -u??”to set the number of context lines shown when a unified diff is created. This
takes precedence over any -U”or --unified”option value passed on the Git diff command line.
2. GIT EXTERNAL DIFF
When the environment variable GIT EXTERNAL DIFF is set, the program named by it is called to generate diffs, and
Git does not use its builtin diff machinery. For a path that is added, removed, or modified, GIT EXTERNAL DIFF is
called with 7 parameters:
sensitive1 path old = f i l e old =hex old =mode new= f i l e new=hex new=mode

where: <old—new>-file
are files GIT EXTERNAL DIFF can use to read the contents of <old—new>, <old—new>-hex
are the 40-hexdigit SHA-1 hashes, <old—new>-mode
are the octal representation of the file modes.
The file parameters can point at the user’s working file (e.g. new-file in ”git-diff-files”), /dev/null (e.g. old-file when
a new file is added), or a temporary file (e.g. old-file in the index). GIT EXTERNAL DIFF should not worry about
unlinking the temporary file — it is removed when GIT EXTERNAL DIFF exits.
For a path that is unmerged, GIT EXTERNAL DIFF is called with 1 parameter, <path>.
For each path GIT EXTERNAL DIFF is called, two environment variables, GIT DIFF PATH COUNTER and GIT DIFF PAT
are set.
3. GIT DIFF PATH COUNTER
A 1-based counter incremented by one for every path.
4. GIT DIFF PATH TOTAL
The total number of paths.

6.7.4 OTHER
1. GIT MERGE VERBOSITY
A number controlling the amount of output shown by the recursive merge strategy. Overrides merge.verbosity. See
git-merge[1]
2. GIT PAGER
This environment variable overrides $PAGER. If it is set to an empty string or to the value ”cat”, Git will not launch
a pager. See also the core.pager option in git-config[1].
3. GIT PROGRESS DELAY
A number controlling how many seconds to delay before showing optional progress indicators. Defaults to 2.
4. GIT EDITOR
This environment variable overrides $EDITOR and $VISUAL. It is used by several Git commands when, on interactive
mode, an editor is to be launched. See also git-var[1] and the core.editor option in git-config[1].
5. GIT SEQUENCE EDITOR
This environment variable overrides the configured Git editor when editing the todo list of an interactive rebase. See
also git-rebase[1] and the sequence.editor option in git-config[1].

Gabriel Cardoso Gaga’s Codex - Git Página 36


Gabriel Cardoso Gaga’s Codex - Git 37

6. GIT SSH
GIT SSH COMMAND

If either of these environment variables is set then git fetch and git push will use the specified command instead of ssh
when they need to connect to a remote system. The command-line parameters passed to the configured command are
determined by the ssh variant. See ssh.variant option in git-config[1] for details.
$GIT SSH COMMAND takes precedence over $GIT SSH, and is interpreted by the shell, which allows additional
arguments to be included. $GIT SSH on the other hand must be just the path to a program (which can be a wrapper
shell script, if additional arguments are needed).
Usually it is easier to configure any desired options through your personal .ssh/config file. Please consult your ssh
documentation for further details.
7. GIT SSH VARIANT
If this environment variable is set, it overrides Git’s autodetection whether GIT SSH/GIT SSH COMMAND/core.sshCommand
refer to OpenSSH, plink or tortoiseplink. This variable overrides the config setting ssh.variant that serves the same
purpose.

8. GIT ASKPASS
If this environment variable is set, then Git commands which need to acquire passwords or passphrases (e.g. for
HTTP or IMAP authentication) will call this program with a suitable prompt as command-line argument and read
the password from its STDOUT. See also the core.askPass option in git-config[1].

9. GIT TERMINAL PROMPT


If this environment variable is set to 0, git will not prompt on the terminal (e.g., when asking for HTTP authentication).
10. GIT CONFIG GLOBAL
GIT CONFIG SYSTEM

Take the configuration from the given files instead from global or system-level configuration files. If GIT CONFIG SYSTEM
is set, the system config file defined at build time (usually /etc/gitconfig) will not be read. Likewise, if GIT CONFIG GLOBAL
is set, neither $HOME/.gitconfig nor $XDG CONFIG HOME/git/config will be read. Can be set to /dev/null to skip
reading configuration files of the respective level.
11. GIT CONFIG NOSYSTEM
Whether to skip reading settings from the system-wide $(prefix)/etc/gitconfig file. This environment variable can be
used along with $HOME and $XDG CONFIG HOME to create a predictable environment for a picky script, or you
can set it temporarily to avoid using a buggy /etc/gitconfig file while waiting for someone with sufficient permissions
to fix it.
12. GIT FLUSH
If this environment variable is set to ”1”, then commands such as git blame (in incremental mode), git rev-list, git log,
git check-attr and git check-ignore will force a flush of the output stream after each record have been flushed. If this
variable is set to ”0”, the output of these commands will be done using completely buffered I/O. If this environment
variable is not set, Git will choose buffered or record-oriented flushing based on whether stdout appears to be redirected
to a file or not.

13. GIT TRACE


Enables general trace messages, e.g. alias expansion, built-in command execution and external command execution.
If this variable is set to ”1”, ”2”or ”true”(comparison is case insensitive), trace messages will be printed to stderr.
If the variable is set to an integer value greater than 2 and lower than 10 (strictly) then Git will interpret this value as
an open file descriptor and will try to write the trace messages into this file descriptor.
Alternatively, if the variable is set to an absolute path (starting with a / character), Git will interpret this as a file
path and will try to append the trace messages to it.
Unsetting the variable, or setting it to empty, ”0”or ”false”(case insensitive) disables trace messages.
14. GIT TRACE FSMONITOR
Enables trace messages for the filesystem monitor extension. See GIT TRACE for available trace output options.

Gabriel Cardoso Gaga’s Codex - Git Página 37


Gabriel Cardoso Gaga’s Codex - Git 38

15. GIT TRACE PACK ACCESS


Enables trace messages for all accesses to any packs. For each access, the pack file name and an offset in the pack
is recorded. This may be helpful for troubleshooting some pack-related performance problems. See GIT TRACE for
available trace output options.

16. GIT TRACE PACKET


Enables trace messages for all packets coming in or out of a given program. This can help with debugging object negoti-
ation or other protocol issues. Tracing is turned off at a packet starting with ”PACK”(but see GIT TRACE PACKFILE
below). See GIT TRACE for available trace output options.
17. GIT TRACE PACKFILE
Enables tracing of packfiles sent or received by a given program. Unlike other trace output, this trace is verbatim: no he-
aders, and no quoting of binary data. You almost certainly want to direct into a file (e.g., GIT TRACE PACKFILE=/tmp/my.p
rather than displaying it on the terminal or mixing it with other trace output.
Note that this is currently only implemented for the client side of clones and fetches.

18. GIT TRACE PERFORMANCE


Enables performance related trace messages, e.g. total execution time of each Git command. See GIT TRACE for
available trace output options.
19. GIT TRACE REFS
Enables trace messages for operations on the ref database. See GIT TRACE for available trace output options.

20. GIT TRACE SETUP


Enables trace messages printing the .git, working tree and current working directory after Git has completed its setup
phase. See GIT TRACE for available trace output options.
21. GIT TRACE SHALLOW
Enables trace messages that can help debugging fetching / cloning of shallow repositories. See GIT TRACE for available
trace output options.
22. GIT TRACE CURL
Enables a curl full trace dump of all incoming and outgoing data, including descriptive information, of the git transport
protocol. This is similar to doing curl –trace-ascii on the command line. See GIT TRACE for available trace output
options.
23. GIT TRACE CURL NO DATA
When a curl trace is enabled (see GIT TRACE CURL above), do not dump data (that is, only dump info lines and
headers).

24. GIT TRACE2


Enables more detailed trace messages from the ”trace2”library. Output from GIT TRACE2 is a simple text-based
format for human readability.
If this variable is set to ”1”, ”2”or ”true”(comparison is case insensitive), trace messages will be printed to stderr.
If the variable is set to an integer value greater than 2 and lower than 10 (strictly) then Git will interpret this value as
an open file descriptor and will try to write the trace messages into this file descriptor.
Alternatively, if the variable is set to an absolute path (starting with a / character), Git will interpret this as a file
path and will try to append the trace messages to it. If the path already exists and is a directory, the trace messages
will be written to files (one per process) in that directory, named according to the last component of the SID and an
optional counter (to avoid filename collisions).
In addition, if the variable is set to af unix:[<socket type>:]<absolute-pathname>, Git will try to open the path as a
Unix Domain Socket. The socket type can be either stream or dgram.
Unsetting the variable, or setting it to empty, ”0”or ”false”(case insensitive) disables trace messages.
See Trace2 documentation for full details.
25. GIT TRACE2 EVENT
This setting writes a JSON-based format that is suited for machine interpretation. See GIT TRACE2 for available
trace output options and Trace2 documentation for full details.

Gabriel Cardoso Gaga’s Codex - Git Página 38


Gabriel Cardoso Gaga’s Codex - Git 39

26. GIT TRACE2 PERF


In addition to the text-based messages available in GIT TRACE2, this setting writes a column-based format for
understanding nesting regions. See GIT TRACE2 for available trace output options and Trace2 documentation for full
details.

27. GIT TRACE REDACT


By default, when tracing is activated, Git redacts the values of cookies, the ”Authorization:”header, the ”Proxy-
Authorization:”header and packfile URIs. Set this variable to 0 to prevent this redaction.
28. GIT LITERAL PATHSPECS
Setting this variable to 1 will cause Git to treat all pathspecs literally, rather than as glob patterns. For example,
running GIT LITERAL PATHSPECS=1 git log – ’*.c’ will search for commits that touch the path *.c, not any paths
that the glob *.c matches. You might want this if you are feeding literal paths to Git (e.g., paths previously given to
you by git ls-tree, –raw diff output, etc).
29. GIT GLOB PATHSPECS
Setting this variable to 1 will cause Git to treat all pathspecs as glob patterns (aka ”glob”magic).
30. GIT NOGLOB PATHSPECS
Setting this variable to 1 will cause Git to treat all pathspecs as literal (aka ”literal”magic).
31. GIT ICASE PATHSPECS
Setting this variable to 1 will cause Git to treat all pathspecs as case-insensitive.
32. GIT REFLOG ACTION
When a ref is updated, reflog entries are created to keep track of the reason why the ref was updated (which is typically
the name of the high-level command that updated the ref), in addition to the old and new values of the ref. A scripted
Porcelain command can use set reflog action helper function in git-sh-setup to set its name to this variable when it is
invoked as the top level command by the end user, to be recorded in the body of the reflog.
33. GIT REF PARANOIA
If set to 0, ignore broken or badly named refs when iterating over lists of refs. Normally Git will try to include any such
refs, which may cause some operations to fail. This is usually preferable, as potentially destructive operations (e.g.,
git-prune[1]) are better off aborting rather than ignoring broken refs (and thus considering the history they point to as
not worth saving). The default value is 1 (i.e., be paranoid about detecting and aborting all operations). You should
not normally need to set this to 0, but it may be useful when trying to salvage data from a corrupted repository.
34. GIT ALLOW PROTOCOL
If set to a colon-separated list of protocols, behave as if protocol.allow is set to never, and each of the listed protocols
has protocol.<name>.allow set to always (overriding any existing configuration). See the description of protocol.allow
in git-config[1] for more details.
35. GIT PROTOCOL FROM USER
Set to 0 to prevent protocols used by fetch/push/clone which are configured to the user state. This is useful to restrict
recursive submodule initialization from an untrusted repository or for programs which feed potentially-untrusted URLS
to git commands. See git-config[1] for more details.

36. GIT PROTOCOL


For internal use only. Used in handshaking the wire protocol. Contains a colon : separated list of keys with optional
values key[=value]. Presence of unknown keys and values must be ignored.
Note that servers may need to be configured to allow this variable to pass over some transports. It will be propagated
automatically when accessing local repositories (i.e., file:// or a filesystem path), as well as over the git:// protocol. For
git-over-http, it should work automatically in most configurations, but see the discussion in git-http-backend[1]. For
git-over-ssh, the ssh server may need to be configured to allow clients to pass this variable (e.g., by using AcceptEnv
GIT PROTOCOL with OpenSSH).
This configuration is optional. If the variable is not propagated, then clients will fall back to the original ”v0”protocol
(but may miss out on some performance improvements or features). This variable currently only affects clones and
fetches; it is not yet used for pushes (but may be in the future).

Gabriel Cardoso Gaga’s Codex - Git Página 39


Gabriel Cardoso Gaga’s Codex - Git 40

37. GIT OPTIONAL LOCKS


If set to 0, Git will complete any requested operation without performing any optional sub-operations that require
taking a lock. For example, this will prevent git status from refreshing the index as a side effect. This is useful
for processes running in the background which do not want to cause lock contention with other operations on the
repository. Defaults to 1.
38. GIT REDIRECT STDIN
39. GIT REDIRECT STDOUT
40. GIT REDIRECT STDERR
Windows-only: allow redirecting the standard input/output/error handles to paths specified by the environment va-
riables. This is particularly useful in multi-threaded applications where the canonical way to pass standard handles
via CreateProcess() is not an option because it would require the handles to be marked inheritable (and consequently
every spawned process would inherit them, possibly blocking regular Git operations). The primary intended use case
is to use named pipes for communication (e.g. //./pipe/my-git-stdin-123).
Two special values are supported: off will simply close the corresponding standard handle, and if GIT REDIRECT STDERR
is 2
>
&1, standard error will be redirected to the same handle as standard output.
41. GIT PRINT SHA1 ELLIPSIS (deprecated)
If set to yes, print an ellipsis following an (abbreviated) SHA-1 value. This affects indications of detached HEADs
(git-checkout[1]) and the raw diff output (git-diff[1]). Printing an ellipsis in the cases mentioned is no longer considered
adequate and support for it is likely to be removed in the foreseeable future (along with the variable).

Gabriel Cardoso Gaga’s Codex - Git Página 40


Gabriel Cardoso Gaga’s Codex - Git 41

7 MATERIAL DE REFERÊNCIA
Documentação de referência:
https://git-scm.com/docs
Documentação sobre versionamento e readme
https://agupubs.onlinelibrary.wiley.com/doi/full/10.1029/2021EA001797

Gabriel Cardoso Gaga’s Codex - Git Página 41

Você também pode gostar