Git: Comparação de diferenças no Git e análise de alterações

Comparar diferenças é uma ferramenta importante para compreender as alterações no código. Ao comparar as diferenças entre versões diferentes, é possível ver claramente o que foi alterado, por que foi alterado e o escopo das alterações.

1. Noções básicas sobre a comparação de diferenças

(1) As três áreas do Git

O Git possui três áreas importantes, e compreendê-las é fundamental para dominar as comparações (diffs):

100%
graph TB
    A[Workspace<br/>Working Directory] -->|git add| B[Buffer<br/>Staging Area]
    B -->|git commit| C[Repository<br/>Repository]
    
    A -.->|git diff| B
    B -.->|git diff --staged| C
    A -.->|git diff HEAD| C
    
    style A fill:#fff3cd
    style B fill:#d4edda
    style C fill:#c3e6cb

(2) Cenários para comparar diferenças

(3) Visão geral do comando diff

git diff Usado para exibir diferenças. Uso básico:

BASH
git diff [options] [<commit>] [--] [<path>...]

2. Comparando as três regiões

(1) Diretório de trabalho x diretório temporário

Compare as diferenças entre o diretório de trabalho e a área de preparação — ou seja, as alterações não preparadas.

▶ Exemplo: Visualizando alterações não registradas

BASH
# Edit File
echo "new line" >> README.md

# View Workspace Changes(Relative to the temporary storage area)
git diff

# Output:
# diff --git a/README.md b/README.md
# index abc1234..def5678 100644
# --- a/README.md
# +++ b/README.md
# @@ -1,3 +1,4 @@
#  # My Project
#  
#  ## Features
# +new line

# View a Specific File
git diff README.md

# View Multiple Files
git diff file1.js file2.js

(2) Área de preparação x Repositório

Compare as diferenças entre a área de preparação e o repositório — ou seja, as alterações que foram preparadas, mas ainda não foram confirmadas.

▶ Exemplo: Visualizar alterações preparadas

BASH
# Add or modify to the staging area
git add README.md

# View changes in the staging area(Compared to the latest submission)
git diff --staged

# Or use the old syntax
git diff --cached

# Output:
# diff --git a/README.md b/README.md
# index abc1234..def5678 100644
# --- a/README.md
# +++ b/README.md
# @@ -1,3 +1,4 @@
#  # My Project
#  
#  ## Features
# +new line

(3) Diretório de trabalho x Repositório

Compare as diferenças entre o diretório de trabalho e o repositório — ou seja, todas as alterações não confirmadas.

▶ Exemplo: Visualizar todas as alterações não salvas

BASH
# View the workspace relative toHEADthe differences
git diff HEAD

# View the differences between the workspace and a specific commit
git diff a1b2c3d

# View the differences in the workspace compared to the last commit
git diff HEAD^

# The output includes all changes, both staged and unstaged.

3. Interpretando o resultado da diferença

(1) Formato de saída do diff

▶ Exemplo: Entendendo a saída do comando diff

BASH
git diff

# Output Format Description:
# diff --git a/file.js b/file.js     <- GitDifferential Head
# index abc1234..def5678 100644      <- File Mode
# --- a/file.js                      <- Original Document(-Indicates deletion)
# +++ b/file.js                      <- New Document(+Indicates addition)
# @@ -1,3 +1,4 @@                     <- Change Location (hunk header)
#  # My Project                      <- Context Line(Starts with a space)
#  
#  ## Features                       <- Context Line
# +new line                          <- Add a row(+Introduction)
# -old line                          <- Delete Row(-Introduction)

(2) Formato do cabeçalho Hunk

formato do cabeçalho hunk: @@ -a,b +c,d @@

TEXT 📖 Somente leitura
@@ -10,5 +10,7 @@ function login() {

Isso significa que as 5 linhas que começam na linha 10 do arquivo original passaram a ser 7 linhas que começam na linha 10 do novo arquivo.

(3) Informações estatísticas

▶ Exemplo: Visualização de um resumo das estatísticas

BASH
# Display Statistics
git diff --stat

# Output:
#  README.md | 1 +
#  file1.js  | 5 ++---
#  file2.js  | 3 +++
#  3 files changed, 5 insertions(+), 3 deletions(-)

# Show brief statistics
git diff --shortstat

# Output:
# 3 files changed, 5 insertions(+), 3 deletions(-)

# Display Numerical Statistics
git diff --numstat

# Output:
# 1       0       README.md
# 2       3       file1.js
# 3       0       file2.js

4. Comparando diferentes versões

(1) Compare os dois commits

▶ Exemplo: Comparação de envios

BASH
# Compare the two commits
git diff a1b2c3d d4e5f6g

# Compare a commit to the current workspace
git diff a1b2c3d

# Compare a commit to the staging area
git diff --staged a1b2c3d

# Compare Adjacent Commits
git diff HEAD^ HEAD

# View the changes introduced by a specific commit
git show a1b2c3d

# Equivalent to
git diff a1b2c3d^ a1b2c3d

(2) Comparar ramificações

▶ Exemplo: Comparação de ramificações

BASH
# Compare Two Branches
git diff main feature

# ViewfeatureBranch relative tomainChanges to
git diff main...feature

# ViewmainBranch relative tofeatureChanges to
git diff feature...main

# Compare a specific file across branches
git diff main feature -- file.js

# View changes made after the branch was forked
git diff $(git merge-base main feature) feature

(3) Tags de comparação

▶ Exemplo: Comparação de versões

BASH
# Compare the Two Versions
git diff v1.0.0 v2.0.0

# View the changes in a specific version
git diff v1.0.0 HEAD

# View the release notes
git diff v1.0.0 v2.0.0 --stat

# Output:
#  src/auth.js   | 25 +++++++++++++++++++++++++
#  src/user.js   | 10 +++++-----
#  package.json  |  2 +-
#  3 files changed, 32 insertions(+), 5 deletions(-)

5. Explicação detalhada da opção diff

(1) Opções comuns

Opção Descrição Finalidade
--staged Área de preparação x Repositório Visualizar alterações preparadas
--stat Ver estatísticas Ver e editar estatísticas
--shortstat Estatísticas resumidas Ver todas as alterações
--name-only Mostrar apenas os nomes dos arquivos Exibir lista de arquivos modificados
--name-status Exibir status Ver status de modificação do arquivo
-w Ignorar espaços em branco Ignorar diferenças entre espaços e tabulações

▶ Exemplo: Como usar a opção diff

BASH
# Show only the names of modified files
git diff --name-only

# Output:
# README.md
# file1.js
# file2.js

# Display File Modification Status
git diff --name-status

# Output:
# M  README.md     <- Edit
# A  file1.js      <- New
# D  file2.js      <- Delete
# R  old.js new.js <- Rename

# Ignore differences in whitespace characters
git diff -w

# Ignore all spaces
git diff -w --ignore-blank-lines

# Show differences at the word level
git diff --word-diff

# Highlight in color
git diff --color-words

(2) Controle de contexto

▶ Exemplo: Controlando o número de linhas no contexto

BASH
# Reduce the number of context lines
git diff -U1

# The output displays only1Line Context:
# @@ -10,3 +10,4 @@ function login() {
#   const user = authenticate();
# +  if (!user) return;
#   return user;

# Do not display context
git diff -U0

# Increase the number of context lines
git diff -U10

(3) Restrições de trajetória

▶ Exemplo: Limitando o intervalo de comparação

BASH
# Compare only specific files
git diff -- file.js

# Compare only specific directories
git diff -- src/

# Exclude certain files
git diff -- . ':!*.test.js'

# Compare only a specific type of file
git diff -- '*.js'

6. Aplicações na vida real

(1) Verificação prévia ao envio

▶ Exemplo: Verifique cuidadosamente antes de enviar

BASH
# 1. View Uncommitted Changes
git diff

# 2. View Staged Changes
git diff --staged

# 3. View Statistics on All Changes
git diff HEAD --stat

# 4. Submit after verifying that everything is correct
git commit -m "feat: Add a New Feature"

(2) Revisão de código

▶ Exemplo: Revisão do código de outra pessoa

BASH
# View the changes in a specific commit
git show a1b2c3d

# View statistics for a specific commit
git show --stat a1b2c3d

# View the list of files modified in a specific commit
git show --name-only a1b2c3d

# Compare the differences between the two branches
git diff main...feature

# ViewPull Requestthe differences
git diff origin/main...origin/feature

(3) Análise de conflitos

▶ Exemplo: Análise de conflitos de mesclagem

BASH
# View the content to be merged
git diff main...feature

# View common ancestors up tofeatureChanges to
git diff $(git merge-base main feature) feature

# View files that may be in conflict
git diff --name-only main...feature

# View the specific details of the conflict
git diff main feature -- file.js

(4) Confirmação da reversão da versão

▶ Exemplo: Confirmação do conteúdo da reversão

BASH
# View content that would be lost if you undo the action
git diff HEAD HEAD~1

# View rollback statistics
git diff HEAD HEAD~1 --stat

# View the revision history for a specific file
git diff HEAD HEAD~1 -- file.js

# Execute the rollback after confirmation
git reset --hard HEAD~1

❓ Perguntas Frequentes

P: Qual é a diferença entre git diff, git diff --staged e git diff HEAD?

R: git diff Comparar o diretório de trabalho com a área de preparação (alterações não preparadas); git diff --staged Comparar a área de preparação com o repositório (alterações preparadas); git diff HEAD Comparar o diretório de trabalho com o repositório (todas as alterações não enviadas).

P: Como posso visualizar apenas os nomes dos arquivos modificados sem ver seu conteúdo real?

R: Use git diff --name-only para exibir apenas os nomes dos arquivos ou use git diff --stat para exibir os nomes dos arquivos e as estatísticas de modificação.

P: O que significam os símbolos “+” e “-” na saída do diff?

R: As linhas que começam com “+” indicam conteúdo novo, as que começam com “-” indicam conteúdo excluído e as que começam com um espaço são o texto original (inalterado).

P: Como faço para comparar as diferenças entre dois branches?

R: Use git diff main feature para comparar dois ramos e use git diff main...feature para visualizar as alterações no ramo de recurso em relação ao ramo principal (a partir do ponto de bifurcação).

P: Como faço para ignorar as diferenças de espaçamento?

R: Use git diff -w para ignorar as diferenças entre espaços e tabulações, e use git diff --ignore-space-at-eol para ignorar as diferenças nos espaços finais.


📖 Resumo


📝 Exercícios

  1. Exercício básico: Crie um repositório Git. Após modificar um arquivo, use git diff para visualizar as alterações não preparadas. Após preparar as alterações, use git diff --staged para visualizar as alterações preparadas.

  2. Exercício avançado: Crie dois ramos, faça alterações no mesmo arquivo em ramos diferentes, use o git diff para comparar as diferenças entre os dois ramos e analise os conflitos que possam surgir.

  3. Desafio: Use as diversas opções do git diff (como --stat, --name-status, -w, etc.) para analisar as alterações feitas em um projeto real e gerar um relatório completo de alterações.

Web-Tutorial.com

Equipe Técnica Web-Tutorial

Uma plataforma de tutoriais mantida por diversos desenvolvedores. Cada tutorial é escrito e revisado por profissionais da área correspondente. Trabalhamos para manter nosso conteúdo preciso e confiável — se encontrar algum problema, avise-nos.

100%