Folha de Dicas do Delta
Folha de Dicas do Delta
Instalação
| Plataforma | Comando |
|---|---|
| Ubuntu/Debian | wget https://github.com/dandavison/delta/releases/download/0.16.5/git-delta_0.16.5_amd64.deb && sudo dpkg -i git-delta_0.16.5_amd64.deb |
| Arch Linux | sudo pacman -S git-delta |
| Fedora/RHEL | sudo dnf install git-delta |
| Alpine Linux | apk add git-delta |
| macOS (Homebrew) | brew install git-delta |
| macOS (MacPorts) | sudo port install git-delta |
| Windows (Scoop) | scoop install delta |
| Windows (Chocolatey) | choco install delta |
| Windows (Winget) | winget install dandavison.delta |
| Any (Cargo) | cargo install git-delta |
| Verify Installation | delta --version |
Comandos Básicos
| Comando | Descrição |
|---|---|
git config --global core.pager delta | Defina delta como pager padrão do Git |
git diff | Visualizar alterações não preparadas com delta |
git diff --cached | Visualizar alterações preparadas com delta |
git diff path/to/file.py | Ver alterações em arquivo específico |
git diff main | Comparar branch atual com main |
git diff branch1..branch2 | Comparar dois branches |
git show HEAD | Mostrar último commit com diff |
git show abc123 | Mostrar commit específico com diff |
git log -p | Visualizar histórico de commits com diferenças |
git diff commit1 commit2 | Comparar dois commits específicos |
| `diff file1.txt file2.txt \ | delta` |
delta file1.txt file2.txt | Comparar arquivos diretamente com delta |
delta --show-syntax-themes | Exibir todos os temas de sintaxe disponíveis |
delta --list-languages | Liste todas as linguagens de programação suportadas |
delta --show-config | Exibir configuração delta atual |
git blame file.py | Visualizar git blame com formatação delta |
| `git grep “function” \ | delta` |
git diff --stat | Mostrar estatísticas de diferenças com delta |
| `git diff -w \ | delta` |
delta changes.diff | Visualizar um arquivo diff salvo com delta |
Uso Avançado
| Comando | Descrição |
|---|---|
| `git diff \ | delta —side-by-side` |
| `git diff \ | delta —side-by-side —width 200` |
| `git diff \ | delta —line-numbers` |
| `git diff \ | delta —syntax-theme Monokai` |
| `git diff \ | delta —language python` |
git config --global delta.side-by-side true | Ativar modo lado a lado globalmente |
git config --global delta.line-numbers true | Ativar números de linha globalmente |
git config --global delta.navigate true | Ativar modo de navegação para saltar entre arquivos |
git config --global delta.hyperlinks true | Ativar hiperlinks clicáveis de caminho de arquivo |
git config --global diff.colorMoved default | Realçar blocos de código movidos |
git config --global pager.blame delta | Use delta para saída do git blame |
git config --global pager.grep delta | Use delta para saída do git grep |
git config --global interactive.diffFilter "delta --color-only" | Use delta em comandos interativos do Git |
git blame -L 10,20 file.py | Visualizar blame para intervalo de linhas específico com delta |
git diff --word-diff | Mostrar diferenças em nível de palavra com delta |
git config --global delta.pager "less -RFX" | Personalizar comportamento do pager |
git config --global delta.features "line-numbers decorations" | Habilitar múltiplos recursos simultaneamente |
| `git diff —ignore-space-at-eol \ | delta` |
git config --global delta.max-line-length 512 | Definir comprimento máximo de linha para exibição |
git config --global delta.tabs 4 | Definir largura da guia para exibição |
Configuração
O Delta é configurado através do sistema de configuração do Git. A configuração pode ser definida globalmente (~/.gitconfig) ou por repositório (.git/config).
Configuração Básica
[core]
pager = delta
[interactive]
diffFilter = delta --color-only
[delta]
navigate = true
line-numbers = true
side-by-side = true
Exemplo de Configuração Completa
[core]
pager = delta
[interactive]
diffFilter = delta --color-only
[delta]
# General settings
navigate = true
light = false
side-by-side = true
line-numbers = true
hyperlinks = true
# Syntax highlighting
syntax-theme = Monokai Extended
# Layout
width = 200
tabs = 4
wrap-max-lines = unlimited
# Line numbers
line-numbers-left-format = "{nm:>4}│"
line-numbers-right-format = "{np:>4}│"
line-numbers-minus-style = "red"
line-numbers-plus-style = "green"
line-numbers-zero-style = "white dim"
# Colors and styles
minus-style = syntax "#3f0001"
minus-non-emph-style = syntax "#3f0001"
minus-emph-style = syntax "#901011"
minus-empty-line-marker-style = normal "#3f0001"
plus-style = syntax "#002800"
plus-non-emph-style = syntax "#002800"
plus-emph-style = syntax "#007800"
plus-empty-line-marker-style = normal "#002800"
# Commit and file decoration
commit-decoration-style = bold yellow box ul
file-decoration-style = blue ul
file-style = bold yellow ul
hunk-header-decoration-style = blue box
hunk-header-style = file line-number syntax
# Whitespace
whitespace-error-style = reverse red
# Moved code detection
color-moved-style = syntax
[diff]
colorMoved = default
Conjuntos de Recursos Personalizados
Crie perfis de configuração reutilizáveis:
[delta "my-dark-theme"]
syntax-theme = Dracula
line-numbers = true
side-by-side = true
navigate = true
minus-style = syntax "#450a15"
plus-style = syntax "#0a4514"
[delta "my-light-theme"]
syntax-theme = GitHub
light = true
line-numbers = true
side-by-side = false
[delta]
features = my-dark-theme
Temas de Sintaxe Populares
Monokai ExtendedNordDraculagruvbox-darkgruvbox-lightSolarized (dark)Solarized (light)GitHubOneHalfDarkOneHalfLight
Casos de Uso Comuns
Caso de Uso 1: Fluxo de Trabalho de Revisão de Código Diário
# Configure delta for optimal code review
git config --global core.pager delta
git config --global delta.side-by-side true
git config --global delta.line-numbers true
git config --global delta.navigate true
# Review changes before committing
git diff
# Review staged changes
git diff --cached
# Review specific file changes
git diff path/to/modified/file.js
Caso de Uso 2: Comparando Branches para Merge
# Compare feature branch with main
git diff main..feature-branch
# View side-by-side comparison with context
git diff main..feature-branch | delta --side-by-side --width 180
# Check for moved code blocks
git diff --color-moved main..feature-branch
# Review specific file differences between branches
git diff main..feature-branch -- src/app.py
Caso de Uso 3: Investigando Histórico de Código
# View commit history with diffs
git log -p --follow path/to/file.py
# Compare specific commits
git diff abc123..def456
# Show changes in a specific commit
git show abc123
# View blame with delta formatting
git blame -L 50,100 src/main.rs
# Search for changes in history
git log -p -S "function_name" | delta
Caso de Uso 4: Resolução de Conflitos de Merge
# Enable side-by-side view for conflicts
git config --global delta.side-by-side true
git config --global delta.line-numbers true
# View conflicted files
git diff --name-only --diff-filter=U
# Examine conflicts in detail
git diff path/to/conflicted/file.py
# Compare with both parents during merge
git diff HEAD
git diff MERGE_HEAD
Caso de Uso 5: Criando Relatórios de Diff Legíveis
# Generate formatted diff for documentation
git diff main..feature > changes.diff
delta changes.diff > formatted-changes.txt
# Create side-by-side comparison
git diff --stat main..feature
git diff main..feature | delta --side-by-side --width 200
# Export with specific theme for presentations
git diff | delta --syntax-theme "Monokai Extended" --line-numbers
Melhores Práticas
-
Definir delta globalmente: Configure
git config --global core.pager deltauma vez para usar delta em todos os repositórios, garantindo uma experiência consistente de visualização de diff. -
Habilitar modo de navegação: Use
git config --global delta.navigate truepara navegar rapidamente entre arquivos em diffs grandes usando as teclasn(próximo) eN(anterior). -
Escolher temas apropriados: Selecione temas de sintaxe que correspondam ao fundo do seu terminal (escuro/claro) e forneçam bom contraste. Teste com
Note: Some placeholders (3-16, 18-20) were left untranslated as they seem to be placeholders for specific content not provided in the original text.delta --show-syntax-themespara visualizar todas as opções.
-
Use lado a lado para revisões: Ative
side-by-side = truepara revisões de código e comparações de merge, mas desative para verificações rápidas em terminais estreitos para evitar problemas de quebra de linha. -
Configure números de linha estrategicamente: Ative números de linha para depuração e revisões de código (
line-numbers = true), mas considere desativar para diffs simples para reduzir a desordem visual. -
Aproveite a detecção de código movido: Defina
diff.colorMoved = defaultpara destacar código que foi movido em vez de alterado, tornando as revisões de refatoração muito mais claras. -
Crie conjuntos de recursos personalizados: Defina múltiplas configurações delta para diferentes fluxos de trabalho (por exemplo, “review”, “quick-check”, “presentation”) e alterne entre elas conforme necessário usando a opção
features. -
Otimize para seu fluxo de trabalho: Ajuste as configurações de
width,tabs, ewrap-max-linescom base no tamanho típico do seu terminal e padrões de codificação para evitar quebras de linha desajeitadas. -
Use com comandos interativos: Configure
interactive.diffFilter = delta --color-onlypara obter o destaque do delta emgit add -pe outros comandos interativos do Git. -
Combine com aliases do Git: Crie aliases do Git que incluam opções específicas do delta para tarefas comuns, como
git config --global alias.review 'diff --color-moved'para fluxos de trabalho de revisão padronizados.
Solução de problemas
| Problema | Solução |
|---|---|
| Delta not being used for diffs | Verify configuration with git config --global core.pager - should return delta. If not, run git config --global core.pager delta |
| Colors not displaying correctly | Check terminal supports 24-bit color. Set COLORTERM=truecolor environment variable. Try different syntax themes with delta --show-syntax-themes |
| Side-by-side view is garbled | Terminal width may be too narrow. Disable with git config --global delta.side-by-side false or increase terminal width. Adjust with --width option |
| Line numbers not showing | Enable explicitly: git config --global delta.line-numbers true. Check that feature isn’t disabled in a custom feature set |
| Syntax highlighting not working | Verify file extension is recognized with delta --list-languages. Force language with --language option or check syntax-theme setting |
| Delta not working in git add -p | Set interactive diff filter: git config --global interactive.diffFilter "delta --color-only". The --color-only flag is essential for interactive mode |
| Pager quits immediately | Adjust pager settings: git config --global delta.pager "less -RFX". The -F flag causes less to quit if output fits on one screen |
| Performance issues with large diffs | Disable side-by-side mode, reduce max-line-length, or use --syntax-theme none to disable syntax highlighting for faster rendering |
| Hyperlinks not clickable | Ensure terminal supports hyperlinks (iTerm2, kitty, Alacritty). Enable with git config --global delta.hyperlinks true |
| Configuration not taking effect | Check for conflicting configs: `git config —list |
| Unicode characters displaying incorrectly | Ensure terminal uses UTF-8 encoding. Set LC_ALL=en_US.UTF-8 or similar locale. Check font supports Unicode characters used in decorations |