Guia rápido do Git

Comandos essenciais do Git para controle de versão – ramificação, commit, mesclagem e colaboração.

Configuração e Instalação

Configure o Git e defina sua identidade

# Defina seu nome e e‑mail
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"

# Verifique sua configuração
git config --list

# Defina o nome do branch padrão
git config --global init.defaultBranch main
Configuração inicial
# Defina o editor padrão
git config --global core.editor "code --wait"

# Habilite a saída colorida
git config --global color.ui auto

# Configure o helper de credenciais (Windows)
git config --global credential.helper wincred
Configuração adicional

Criando Repositórios

Inicialize ou clone repositórios Git

# Inicializa um novo repositório
git init

# Inicializa com nome de branch específico
git init -b main

# Clone um repositório existente
git clone https://github.com/user/repo.git

# Clone em um diretório específico
git clone https://github.com/user/repo.git my-folder
Inicialização do repositório

Fluxo de Trabalho Básico

Comandos comuns para uso diário do Git

# Verifique o status do repositório
git status

# Adicione arquivos à área de stage
git add file.txt
git add .                 # Adicione todos os arquivos
git add *.js              # Adicione todos os arquivos JavaScript

# Commit as alterações
git commit -m "Commit message"
git commit -am "Message"  # Adicione e commit arquivos rastreados

# Visualize o histórico de commits
git log
git log --oneline         # Visão compacta
git log --graph           # Exibe o gráfico de branches
Comandos diários

Ramificação e Mesclagem

Crie e gerencie branches

# Liste os branches
git branch                # Branches locais
git branch -a             # Todos os branches (locais + remotos)

# Crie um novo branch
git branch feature-branch

# Troque para um branch
git checkout feature-branch
git switch feature-branch  # Alternativa moderna

# Crie e troque para um novo branch
git checkout -b feature-branch
git switch -c feature-branch
Gerenciamento de branches
# Mescle um branch no branch atual
git merge feature-branch

# Exclua um branch
git branch -d feature-branch    # Exclusão segura
git branch -D feature-branch    # Exclusão forçada

# Renomeie um branch
git branch -m old-name new-name
Mesclagem e limpeza

Repositórios Remotos

Trabalhe com repositórios remotos

# Liste os repositórios remotos
git remote -v

# Adicione um repositório remoto
git remote add origin https://github.com/user/repo.git

# Busque alterações do remoto
git fetch origin

# Puxe alterações do remoto
git pull origin main

# Envie alterações para o remoto
git push origin main
git push -u origin main   # Defina upstream e envie
Operações remotas
# Remova um remoto
git remote remove origin

# Renomeie um remoto
git remote rename old-name new-name

# Altere a URL do remoto
git remote set-url origin https://github.com/user/new-repo.git
Gerenciamento remoto

Desfazendo Alterações

Reverta ou redefina alterações

# Descarte alterações no diretório de trabalho
git restore file.txt
git checkout -- file.txt  # Forma antiga

# Remova arquivos da área de stage
git restore --staged file.txt
git reset HEAD file.txt   # Forma antiga

# Corrija o último commit
git commit --amend -m "New message"

# Reverte um commit (cria um novo commit)
git revert <commit-hash>
Operações de desfazer
# Reset para o commit anterior (cuidado!)
git reset --soft HEAD~1   # Mantém alterações staged
git reset --mixed HEAD~1  # Mantém alterações unstaged
git reset --hard HEAD~1   # Descarta todas as alterações

# Reset para um commit específico
git reset --hard <commit-hash>
Operações de reset

Armazenamento Temporário

Salve alterações temporariamente

# Armazene as alterações atuais
git stash
git stash save "Work in progress"

# Liste os stashes
git stash list

# Aplique o stash
git stash apply           # Mantém o stash
git stash pop             # Aplique e remova o stash

# Aplique um stash específico
git stash apply stash@{0}

# Exclua o stash
git stash drop stash@{0}
git stash clear           # Exclua todos os stashes
Gerenciamento de stash

Visualizando Alterações

Inspecione diferenças e histórico

# Mostre alterações não staged
git diff

# Mostre alterações staged
git diff --staged
git diff --cached

# Mostre alterações entre commits
git diff commit1 commit2

# Mostre alterações em um arquivo específico
git diff file.txt
Comandos de diff
# Mostre detalhes do commit
git show <commit-hash>

# Mostre o arquivo em um commit específico
git show <commit-hash>:file.txt

# Mostre quem fez alterações em um arquivo
git blame file.txt
Comandos de inspeção

Etiquetagem

Crie e gerencie tags de versão

# Liste as tags
git tag

# Crie uma tag leve
git tag v1.0.0

# Crie uma tag anotada
git tag -a v1.0.0 -m "Version 1.0.0"

# Tag um commit específico
git tag -a v1.0.0 <commit-hash> -m "Message"

# Envie tags para o remoto
git push origin v1.0.0
git push origin --tags    # Envie todas as tags

# Exclua a tag
git tag -d v1.0.0
git push origin --delete v1.0.0
Operações de tags

Comandos Úteis

Comandos Git adicionais úteis

# Limpe arquivos não rastreados
git clean -n              # Execução simulada
git clean -f              # Remova arquivos
git clean -fd             # Remova arquivos e diretórios

# Pesquise no repositório
git grep "search term"

# Mostre quem fez alterações em um arquivo
git log --follow file.txt

# Crie um alias
git config --global alias.st status
git config --global alias.co checkout
Utilitários úteis
# Ignorar alterações de arquivo
git update-index --assume-unchanged file.txt

# Rastrear alterações de arquivo novamente
git update-index --no-assume-unchanged file.txt

# Mostrar arquivos rastreados
git ls-files
Rastreamento de arquivos
Guia rápido do Git