Guia completo de Git para controle de versão e colaboração
📖 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
Código, Projetos
GitHub, GitLab
CI/CD, Deploy
GitOps, IaC
📊 Status e Histórico
Use quando: Precisa verificar estado do repositório, histórico de mudanças ou commits específicos
📋Status
git status -s# Status curto
git status --porcelain# Status para scripts
git status --ignored# Incluir ignorados
git status --branch# Info da branch
git status --show-stash# Mostra stashes
📋Histórico Avançado
git log --oneline --graph --all --decorate# Visualização completa
git log --stat# Com estatísticas
git log --patch# Com diff completo
git log --since="2 weeks ago"# Por período
git log --author="nome"# Por autor
git log --grep="fix"# Por mensagem
git log -S "função"# Por código
git log --follow arquivo.txt# Seguir renomeações
git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset'# Log colorido
git log --oneline --decorate --graph# Visualização compacta
git log --reverse# Ordem cronológica inversa
📋Visualizar Mudanças
git show HEAD# Último commit
git show HEAD~2# 2 commits atrás
git show --name-only HEAD# Apenas nomes
git show --stat HEAD# Com estatísticas
🌿 Branches Avançadas
Use quando: Trabalhando com múltiplos recursos, correções ou ambientes
📋Criar e Trocar
git checkout -b feature/nova-funcionalidade# Criar e trocar
git switch -c feature/nova-funcionalidade# Comando moderno
📋Listar Branches
git branch -a# Todas (local + remote)
git branch -r# Apenas remotas
git branch -v# Com último commit
git branch --merged# Já mergeadas
git branch --no-merged# Não mergeadas
📋Deletar Branches
git branch -d feature-branch# Delete seguro
git branch -D feature-branch# Force delete
git push origin --delete feature-branch# Delete remota
📋Renomear Branch
git branch -m old-name new-name# Renomear atual
git branch -M old-name new-name# Force rename
git branch --show-current# Mostra branch atual
git branch --contains abc123# Branches com commit
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
git merge feature-branch# Merge normal
git merge --no-ff feature-branch# Sempre criar merge commit
git merge --squash feature-branch# Squash commits
📋Rebase Interativo
git rebase -i HEAD~3# Últimos 3 commits
git rebase -i main# Desde main
git rebase --continue# Continuar após conflitos
git rebase --abort# Cancelar rebase
📋Cherry-pick
git cherry-pick abc123# Aplicar commit específico
git cherry-pick abc123..def456# Range de commits
git cherry-pick --no-commit abc123# Sem criar commit
git cherry-pick -x abc123# Adiciona crédito
git cherry-pick --signoff abc123# Adiciona sign-off
git cherry-pick --abort# Cancela cherry-pick
🔍 Busca e Investigação
Use quando: Debugging, investigando bugs ou rastreando mudanças
📋Buscar no Código
git grep "função"# No working tree
git grep "função" HEAD~5# Em commit específico
git grep -n "função"# Com números de linha
git grep -i "função"# Case insensitive
📋Blame e Histórico
git blame arquivo.txt# Quem modificou cada linha
git blame -L 10,20 arquivo.txt# Linhas específicas
git log -p arquivo.txt# Histórico com patches
git log --follow arquivo.txt# Seguir renomeações
📋Bisect para Bugs
git bisect start# Iniciar bisect
git bisect bad HEAD# Commit atual tem bug
git bisect good v1.0.0# Versão boa conhecida
git bisect run npm test# Automatizar com testes
git bisect reset# Finalizar bisect
git bisect visualize# Visualiza grafo
git bisect log# Mostra log bisect
git bisect replay arquivo.log# Repete bisect
🏷️ Tags e Releases
Use quando: Marcando versões, releases ou pontos importantes no projeto
📋Criar Tags
git tag v1.0.0# Tag simples
git tag -a v1.0.0 -m "Release 1.0.0"# Tag anotada
git tag -a v1.0.0 abc123 -m "Tag commit específico"# Em commit específico
📋Listar e Gerenciar
git tag# Listar todas
git tag -l "v1.*"# Filtrar tags
git show v1.0.0# Ver detalhes
git tag -d v1.0.0# Deletar tag local
git push origin --delete v1.0.0# Deletar tag remota
📋Push Tags
git push origin v1.0.0# Tag específica
git push origin --tags# Todas as tags
git tag -v v1.0.0# Verifica assinatura
git tag -s v1.0.0 -m "Release"# Tag assinada
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
git stash# Stash mudanças
git stash push -m "WIP: feature X"# Com mensagem
git stash push -- arquivo.txt# Arquivo específico
git stash push --include-untracked# Incluir não rastreados
📋Gerenciar Stashes
git stash list# Listar stashes
git stash show stash@{0}# Ver mudanças
git stash show -p stash@{0}# Ver patch completo
git stash apply stash@{0}# Aplicar sem remover
git stash pop stash@{0}# Aplicar e remover
git stash drop stash@{0}# Remover stash
git stash clear# Limpar todos
📋Stash Avançado
git stash branch nova-branch stash@{0}# Criar branch do stash
git stash clear# Limpa todos stashes
git stash save "WIP: feature"# Stash com mensagem
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!)
git reset --soft HEAD~1# Desfaz commit, mantém staged
git reset --mixed HEAD~1# Desfaz commit e staging
git reset --hard HEAD~1# APAGA TUDO! Cuidado!
📋Restore (comando moderno)
git restore arquivo.txt# Restaurar working tree
git restore --staged arquivo.txt# Unstage arquivo
git restore --source=HEAD~1 arquivo.txt# Restaurar de commit específico
📋Reflog (histórico de referências)
git reflog# Ver histórico de HEAD
git reflog show main# Histórico de branch
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
git remote -v# Listar remotes
git remote add upstream https://...# Adicionar remote
git remote set-url origin https://...# Alterar URL
git remote remove upstream# Remover remote
📋Fetch e Pull Avançado
git fetch --all# Fetch de todos os remotes
git fetch --prune# Remove refs deletadas
git pull --rebase# Pull com rebase
git pull --ff-only# Apenas fast-forward
📋Push Avançado
git push -u origin feature-branch# Set upstream
git push --force-with-lease# Force push seguro
git push origin :feature-branch# Delete remote branch
git push --all origin# Push todas branches
git push --mirror origin# Espelha repositório
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 ☕