Tig (Interface em Modo Texto para Git) Folha de Dicas
Instalação
| Plataforma | Comando |
|---|
| Ubuntu/Debian | sudo apt update && sudo apt install tig |
| Fedora/RHEL | sudo dnf install tig |
| Arch Linux | sudo pacman -S tig |
| macOS (Homebrew) | brew install tig |
| macOS (MacPorts) | sudo port install tig |
| Windows (Git Bash) | Incluído com Git para Windows |
| Windows (WSL) | sudo apt install tig |
| Windows (Scoop) | scoop install tig |
| From Source | git clone https://github.com/jonas/tig.git && cd tig && make && sudo make install |
Verificar Instalação: tig --version | |
Comandos Básicos
| Comando | Descrição |
|---|
tig | Abrir visualização principal mostrando histórico de commits no repositório atual |
tig status | Show working directory status (like git status) |
tig blame <file> | Mostrar autoria linha por linha para um arquivo |
tig <file> | Mostrar histórico de commits para um arquivo específico |
tig show <commit> | Exibir detalhes de um commit específico |
tig refs | Mostrar todos os branches e tags |
tig stash | Exibir todas as alterações guardadas |
tig log | Mostrar visualização do log de commits |
tig diff | Mostrar alterações não preparadas no diretório de trabalho |
tig grep <pattern> | Procurar padrão no repositório |
tig <branch> | Mostrar commits de um branch específico |
tig --all | Mostrar commits de todos os branches |
tig --help | Exibir informações de ajuda |
tig --version | Mostrar informações da versão do tig |
Teclas de Navegação (Dentro do Tig)
| Chave | Descrição |
|---|
j / ↓ | Mova para baixo uma linha |
k / ↑ | Mover uma linha para cima |
h / ← | Role para a esquerda |
l / → | Role para a direita |
PgUp / b | Página acima |
PgDn / Space | Rolar para baixo |
Home | Ir para a primeira linha |
End | Pular para a última linha |
Enter | Abrir/selecionar item (dependente de contexto) |
Tab | Mudar para próxima visualização |
q | Fechar visualização atual |
Q | Fechar todas as visualizações e sair |
R | Recarregar/atualizar visualização atual |
O | Maximizar visualização atual |
h | Mostrar ajuda e associações de teclas |
Teclas de Busca e Filtro
| Chave | Descrição |
|---|
/ | Buscar para frente |
? | Buscar para trás |
n | Encontrar próxima correspondência |
N | Encontrar correspondência anterior |
[ | Ir para o chunk de diferença anterior |
] | Pular para o próximo bloco de diferenças |
{ | Saltar para arquivo anterior no diff |
} | Pular para o próximo arquivo na diff |
Comandos Avançados
| Comando | Descrição |
|---|
tig --author="Name" | Filtrar commits por autor específico |
tig --since="2 weeks ago" | Mostrar commits de uma data relativa |
tig --after="2024-01-01" --before="2024-12-31" | Mostrar commits dentro de um intervalo de data |
tig --grep="pattern" | Mostrar commits com padrão na mensagem |
tig --merges | Mostrar apenas commits de merge |
tig --no-merges | Excluir commits de merge |
tig main..feature | Mostrar commits na feature que não estão no main |
tig main...feature | Mostrar commits que diferem entre branches |
tig --follow -- <file> | Rastrear histórico de arquivo através de renomeações |
tig -S"function_name" | Busca por Pickaxe: commits alterando ocorrências |
tig -G"regex" | Mostrar commits onde diff corresponde a regex |
tig -n 100 | Limitar aos últimos 100 commits |
tig -- '*.py' | Mostrar commits que afetam apenas arquivos Python |
tig reflog | Navegar por entradas do Git reflog |
tig show <commit>:<path> | Exibir conteúdo do arquivo em commit específico |
tig blame +<line> <file> | Abrir visualização de blame na linha específica |
Operações Interativas (Dentro do Tig)
| Chave | Visualizar | Descrição |
|---|
u | status | Adicionar/remover arquivo ou trecho do stage |
1 | status | Adicionar/remover linha única do stage |
! | status | Reverter arquivo ou trecho |
C | status | Fazer commit das alterações preparadas |
C | principal/registro | Cherry-pick commit |
e | principal/registro | Editar mensagem de commit (se HEAD) |
! | principal/registro | Reverter commit |
@ | principal/registro | Mover para commit (checkout) |
C | refs | Criar novo branch |
d | refs | Excluir branch |
m | refs | Mesclar branch |
! | qualquer | Executar comando externo |
: | qualquer | Execute git command (e.g., :!git reset) |
Configuração
O Tig lê configurações a partir destes locais (em ordem de prioridade):
$XDG_CONFIG_HOME/tig/config``~/.config/tig/config(tipicamente ~/.tigrc)`$GIT_DIR/tigrc“/etc/tigrc````bash
Create user config directory and file
mkdir -p ~/.config/tig
touch ~/.config/tig/config
Or use traditional location
touch ~/.tigrc
# Customize interface colors
color cursor white blue bold
color title-focus white blue bold
color title-blur white black bold
# Diff colors
color diff-header yellow default
color diff-chunk magenta default
color diff-add green default
color diff-del red default
# Status colors
color stat-staged green default
color stat-unstaged red default
color stat-untracked yellow default
```(específico do repositório)```bash
# Configure main view columns
set main-view = id:yes date:default author:full commit-title:yes,graph:yes,refs:yes
# Set commit ID width
set id-width = 10
# Enable line numbers in blame view
set blame-view = date:default author:full id:yes,color line-number:yes,interval=1 text
# Line number display interval
set line-number-interval = 5
# Horizontal scrolling percentage
set horizontal-scroll = 33%
# Tab size for display
set tab-size = 4
# Truncation indicator
set truncation-delimiter = ~
``````bash
# Number of context lines in diffs
set diff-context = 3
# Ignore whitespace (options: no, all, some, at-eol)
set ignore-space = some
# Use patience diff algorithm
set diff-options = --patience
# Show untracked files in status view
set status-show-untracked-files = yes
```(em todo o sistema)
### Criando Arquivo de Configuração
```bash
# Bind 'C' in main view to cherry-pick
bind main C !git cherry-pick %(commit)
# Bind 'P' in status view to push
bind status P !git push
# Bind 'F' to fetch in main view
bind main F !git fetch
# Bind 'S' to create stash
bind status S !git stash save "%(prompt Enter stash message: )"
# Bind 'A' to amend commit
bind status A !git commit --amend
# Open commit in browser (GitHub)
bind main B !@hub browse -- commit/%(commit)
```
### Personalização de Cores
```bash
# Wrap long lines
set wrap-lines = yes
# Show changes in status view
set status-show-untracked-dirs = yes
# Refresh interval (seconds)
set refresh-mode = auto
set refresh-interval = 1
# Mouse support
set mouse = yes
# Editor for commit messages
set editor-line-number = yes
```
### Configurações de Visualização
```bash
# Open repository
tig
# Navigate to commit (use j/k)
# Press Enter to see full diff
# Press Tab to switch between views
# Press q to go back
# Review specific branch
tig feature-branch
# Compare branches
tig main..feature-branch
```### Caso de Uso 2: Descobrindo Quando um Bug Foi Introduzido
```bash
# Search for specific code change
tig -S"problematic_function"
# Or search commit messages
tig --grep="bug\|fix" -i
# View blame for specific file
tig blame src/buggy-file.js
# Navigate to suspicious line
# Press Enter to see the commit
# Press Tab to see full commit details
```### Caso de Uso 3: Staging e Commit Interativos
```bash
# Open status view
tig status
# Navigate to files (j/k)
# Press 'u' to stage/unstage files
# Press '1' to stage individual lines
# Press 'C' to commit when ready
# Write commit message and save
```### Caso de Uso 4: Explorando o Histórico do Projeto
```bash
# View all commits with graph
tig --all
# Filter by author and date
tig --author="John Doe" --since="1 month ago"
# View commits affecting specific files
tig -- src/core/*.py
# Follow file through renames
tig --follow -- src/renamed-file.js
```### Caso de Uso 5: Gerenciamento de Branches
```bash
# View all branches and tags
tig refs
# Navigate to branch
# Press 'C' to create new branch
# Press 'd' to delete branch
# Press 'm' to merge branch
# Press Enter to view branch commits
```## Boas Práticas
- **Aprenda atalhos de teclado**: Tig é projetado para navegação por teclado. Memorize `j/k`para movimentação, `Enter`para aprofundar, e `q`para voltar para uma navegação eficiente.
- **Use comandos específicos de visualização**: Diferentes visualizações têm operações diferentes. Pressione `h`em qualquer visualização para ver as associações de teclas disponíveis naquele contexto.
- **Personalize sua configuração**: Crie um arquivo `~/.config/tig/config`para personalizar cores, associações e configurações de visualização para corresponder ao seu fluxo de trabalho e preferências.
- **Combine com comandos Git**: Use tig para visualização e comandos Git para operações. Tig complementa Git em vez de substituí-lo.
- **Use filtros para repositórios grandes**: Em repositórios com milhares de commits, use `--author`, `--since`, `--grep`, ou filtros de arquivo para restringir resultados.
- **Aproveite a visualização de status**: Use `tig status`como uma alternativa interativa ao `git add -p`para controle granular de staging.
- **Explore com Tab**: Use `Tab`para alternar entre visualizações relacionadas e ver diferentes perspectivas dos mesmos dados (commit → diff → tree).
- **Configure configs específicos de repositório**: Crie `.git/tigrc`em repositórios que precisam de configurações especiais sem afetar sua configuração global.
## Resolução de Problemas
| Problema | Solução |
|-------|----------|
| Tig not found after installation | Ensure tig is in your PATH: `which tig`. Restart terminal or run `source ~/.bashrc` |
| Colors not displaying correctly | Check terminal supports 256 colors. Set `TERM=xterm-256color` or configure colors in `~/.tigrc` |
| Slow performance in large repos | Use filters to limit commits: `tig -n 1000` or `tig --since="1 month ago"`. Consider `set refresh-mode = manual` |
| UTF-8 characters display incorrectly | Set locale: `export LC_ALL=en_US.UTF-8` and `export LANG=en_US.UTF-8` in shell config |
| Mouse not working | Enable in config: `set mouse = yes`. Ensure terminal supports mouse events |
| Can't edit commits or stage files | Ensure you have write permissions and are in a valid Git repository. Check `git status` works |
| Custom key bindings not working | Verify syntax in config file. Check for conflicts with default bindings. Reload with `R` |
| Tig crashes on startup | Check Git repository is valid: `git status`. Update tig to latest version. Remove custom config temporarily |
| Diff view shows binary files | Add to `.gitattributes`: `*.bin -diff`. Or set `set diff-options = --no-binary` |
| Line numbers not showing | Enable in config: `set line-number-interval = 1` and ensure view supports line numbers |
## Cartão de Referência Rápida```
LAUNCHING TIG NAVIGATION OPERATIONS
tig j/k ↓/↑ Move u Stage/unstage
tig status h/l ←/→ Scroll C Commit/cherry-pick
tig blame <file> PgUp/PgDn Page ! Revert/execute
tig <branch> Enter Select e Edit
tig --all Tab Next view @ Checkout
q/Q Quit R Refresh
SEARCH VIEWS FILTERS
/ Search forward tig Main --author="Name"
? Search backward tig status Status --since="date"
n Next match tig refs Branches --grep="pattern"
N Previous match tig blame Blame --no-merges
[ Prev chunk tig stash Stash -- '*.ext'
] Next chunk tig diff Diff
```