Cheatsheet

← Voltar para página principal
Git Cheatsheet

Guia completo de Git para controle de versão e colaboração

🔀 O que é Git?

📖 Definição

Git é um sistema de controle de versão distribuído criado por Linus Torvalds. Permite rastrear mudanças no código, colaborar em projetos e manter histórico completo de desenvolvimento.

💪 Por que aprender?

• Controle de versão distribuído
• Branching e merging
• Histórico completo
• Colaboração em equipe
• Integração com plataformas remotas

🚀 O que você pode fazer?

• Desenvolvimento de software
• Controle de versão de código
• Colaboração em projetos
• Deploy e CI/CD
• Gerenciamento de configurações

💡 Onde você vai usar:
💻 Desenvolvimento
Código, Projetos
🌐 Colaboração
GitHub, GitLab
DevOps
CI/CD, Deploy
🤖 Modern
GitOps, IaC
Filtro ativo:Todos
Total: 8 categoriasBásico: 2Intermediário: 4Avançado: 2

📊 Status e Histórico

Use quando: Precisa verificar estado do repositório, histórico de mudanças ou commits específicos

📋Status

Básico
git status -s

# Status curto

Básico
git status --porcelain

# Status para scripts

Básico
git status --ignored

# Incluir ignorados

Básico
git status --branch

# Info da branch

Básico
git status --show-stash

# Mostra stashes

📋Histórico Avançado

Básico
git log --oneline --graph --all --decorate

# Visualização completa

Básico
git log --stat

# Com estatísticas

Básico
git log --patch

# Com diff completo

Básico
git log --since="2 weeks ago"

# Por período

Básico
git log --author="nome"

# Por autor

Básico
git log --grep="fix"

# Por mensagem

Básico
git log -S "função"

# Por código

Básico
git log --follow arquivo.txt

# Seguir renomeações

Básico
git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset'

# Log colorido

Básico
git log --oneline --decorate --graph

# Visualização compacta

Básico
git log --reverse

# Ordem cronológica inversa

📋Visualizar Mudanças

Básico
git show HEAD

# Último commit

Básico
git show HEAD~2

# 2 commits atrás

Básico
git show --name-only HEAD

# Apenas nomes

Básico
git show --stat HEAD

# Com estatísticas

🌿 Branches Avançadas

Use quando: Trabalhando com múltiplos recursos, correções ou ambientes

📋Criar e Trocar

Básico
git checkout -b feature/nova-funcionalidade

# Criar e trocar

Básico
git switch -c feature/nova-funcionalidade

# Comando moderno

📋Listar Branches

Básico
git branch -a

# Todas (local + remote)

Básico
git branch -r

# Apenas remotas

Básico
git branch -v

# Com último commit

Básico
git branch --merged

# Já mergeadas

Básico
git branch --no-merged

# Não mergeadas

📋Deletar Branches

Básico
git branch -d feature-branch

# Delete seguro

Básico
git branch -D feature-branch

# Force delete

Básico
git push origin --delete feature-branch

# Delete remota

📋Renomear Branch

Básico
git branch -m old-name new-name

# Renomear atual

Básico
git branch -M old-name new-name

# Force rename

Básico
git branch --show-current

# Mostra branch atual

Básico
git branch --contains abc123

# Branches com commit

Básico
git branch --sort=-committerdate

# Ordena por data

🔄 Merge e Rebase

Use quando: Integrando mudanças, reorganizando histórico ou aplicando commits específicos

📋Merge Strategies

Intermediário
git merge feature-branch

# Merge normal

Intermediário
git merge --no-ff feature-branch

# Sempre criar merge commit

Intermediário
git merge --squash feature-branch

# Squash commits

📋Rebase Interativo

Intermediário
git rebase -i HEAD~3

# Últimos 3 commits

Intermediário
git rebase -i main

# Desde main

Intermediário
git rebase --continue

# Continuar após conflitos

Intermediário
git rebase --abort

# Cancelar rebase

📋Cherry-pick

Intermediário
git cherry-pick abc123

# Aplicar commit específico

Intermediário
git cherry-pick abc123..def456

# Range de commits

Intermediário
git cherry-pick --no-commit abc123

# Sem criar commit

Intermediário
git cherry-pick -x abc123

# Adiciona crédito

Intermediário
git cherry-pick --signoff abc123

# Adiciona sign-off

Intermediário
git cherry-pick --abort

# Cancela cherry-pick

🔍 Busca e Investigação

Use quando: Debugging, investigando bugs ou rastreando mudanças

📋Buscar no Código

Intermediário
git grep "função"

# No working tree

Intermediário
git grep "função" HEAD~5

# Em commit específico

Intermediário
git grep -n "função"

# Com números de linha

Intermediário
git grep -i "função"

# Case insensitive

📋Blame e Histórico

Intermediário
git blame arquivo.txt

# Quem modificou cada linha

Intermediário
git blame -L 10,20 arquivo.txt

# Linhas específicas

Intermediário
git log -p arquivo.txt

# Histórico com patches

Intermediário
git log --follow arquivo.txt

# Seguir renomeações

📋Bisect para Bugs

Intermediário
git bisect start

# Iniciar bisect

Intermediário
git bisect bad HEAD

# Commit atual tem bug

Intermediário
git bisect good v1.0.0

# Versão boa conhecida

Intermediário
git bisect run npm test

# Automatizar com testes

Intermediário
git bisect reset

# Finalizar bisect

Intermediário
git bisect visualize

# Visualiza grafo

Intermediário
git bisect log

# Mostra log bisect

Intermediário
git bisect replay arquivo.log

# Repete bisect

🏷️ Tags e Releases

Use quando: Marcando versões, releases ou pontos importantes no projeto

📋Criar Tags

Intermediário
git tag v1.0.0

# Tag simples

Intermediário
git tag -a v1.0.0 -m "Release 1.0.0"

# Tag anotada

Intermediário
git tag -a v1.0.0 abc123 -m "Tag commit específico"

# Em commit específico

📋Listar e Gerenciar

Intermediário
git tag

# Listar todas

Intermediário
git tag -l "v1.*"

# Filtrar tags

Intermediário
git show v1.0.0

# Ver detalhes

Intermediário
git tag -d v1.0.0

# Deletar tag local

Intermediário
git push origin --delete v1.0.0

# Deletar tag remota

📋Push Tags

Intermediário
git push origin v1.0.0

# Tag específica

Intermediário
git push origin --tags

# Todas as tags

Intermediário
git tag -v v1.0.0

# Verifica assinatura

Intermediário
git tag -s v1.0.0 -m "Release"

# Tag assinada

Intermediário
git tag -f v1.0.0

# Força tag

📦 Stash Avançado

Use quando: Precisa mudar de branch rapidamente sem commitar mudanças

📋Stash Básico

Intermediário
git stash

# Stash mudanças

Intermediário
git stash push -m "WIP: feature X"

# Com mensagem

Intermediário
git stash push -- arquivo.txt

# Arquivo específico

Intermediário
git stash push --include-untracked

# Incluir não rastreados

📋Gerenciar Stashes

Intermediário
git stash list

# Listar stashes

Intermediário
git stash show stash@{0}

# Ver mudanças

Intermediário
git stash show -p stash@{0}

# Ver patch completo

Intermediário
git stash apply stash@{0}

# Aplicar sem remover

Intermediário
git stash pop stash@{0}

# Aplicar e remover

Intermediário
git stash drop stash@{0}

# Remover stash

Intermediário
git stash clear

# Limpar todos

📋Stash Avançado

Intermediário
git stash branch nova-branch stash@{0}

# Criar branch do stash

Intermediário
git stash clear

# Limpa todos stashes

Intermediário
git stash save "WIP: feature"

# Stash com mensagem

Intermediário
git stash --keep-index

# Stash só não staged

↩️ Reset e Restore

Use quando: Precisa desfazer mudanças, recuperar commits ou limpar working directory

⚠️ ⚠️ ATENÇÃO: O comando git reset --hard é irreversível e perderá todas as mudanças não commitadas. Use com extrema cautela!

💡 💡 DICA: O reflog é um salva-vidas! Mesmo após um reset --hard, você pode recuperar commits perdidos usando o reflog.

📋Reset (cuidado!)

Avançado
git reset --soft HEAD~1

# Desfaz commit, mantém staged

Avançado
git reset --mixed HEAD~1

# Desfaz commit e staging

Avançado
git reset --hard HEAD~1

# APAGA TUDO! Cuidado!

📋Restore (comando moderno)

Avançado
git restore arquivo.txt

# Restaurar working tree

Avançado
git restore --staged arquivo.txt

# Unstage arquivo

Avançado
git restore --source=HEAD~1 arquivo.txt

# Restaurar de commit específico

📋Reflog (histórico de referências)

Avançado
git reflog

# Ver histórico de HEAD

Avançado
git reflog show main

# Histórico de branch

Avançado
git reset --hard HEAD@{2}

# Voltar usando reflog

☁️ Remote e Colaboração

Use quando: Trabalhando em equipe, sincronizando com repositórios remotos ou gerenciando contribuições

📋Gerenciar Remotes

Avançado
git remote -v

# Listar remotes

Avançado
git remote add upstream https://...

# Adicionar remote

Avançado
git remote set-url origin https://...

# Alterar URL

Avançado
git remote remove upstream

# Remover remote

📋Fetch e Pull Avançado

Avançado
git fetch --all

# Fetch de todos os remotes

Avançado
git fetch --prune

# Remove refs deletadas

Avançado
git pull --rebase

# Pull com rebase

Avançado
git pull --ff-only

# Apenas fast-forward

📋Push Avançado

Avançado
git push -u origin feature-branch

# Set upstream

Avançado
git push --force-with-lease

# Force push seguro

Avançado
git push origin :feature-branch

# Delete remote branch

Avançado
git push --all origin

# Push todas branches

Avançado
git push --mirror origin

# Espelha repositório

Avançado
git push --tags --follow-tags

# Push com tags

🤝 Contribuindo

Encontrou um erro? Quer melhorar um cheatsheet? Tem uma sugestão? Adoraríamos suas contribuições! Abra uma issue ou submeta um PR.

Gostou do projeto? Apoie o desenvolvimento com um café e ajude a manter tudo open source ☕