Git: Um guia detalhado sobre clonagem no Git e atualizações…

"Fetch" é uma operação que baixa atualizações de um repositório remoto sem mesclá-las automaticamente. Em comparação com o "pull", o "fetch" é mais seguro e controlável, permitindo que você analise as atualizações primeiro antes de decidir se deseja mesclá-las. Entender como usar o "fetch" é fundamental para a colaboração em equipe.

1. Compreensão dos conceitos básicos

(1) O que é aquisição?

"Fetch" é uma operação que baixa atualizações de um repositório remoto, mas não modifica o branch atual:

100%
graph TB
    A[Remote Repository<br/>Remote] -->|git fetch| B[Remote Branch Replica<br/>origin/main]
    B --> C{View Updates}
    C -->|Satisfied| D[git merge]
    C -->|Not satisfied| E[Leave it as is]
    D --> F[Current Branch<br/>main]
    
    style A fill:#d4edda
    style B fill:#fff3cd
    style F fill:#c3e6cb

(2) fetch x pull

Recurso buscar puxar
Baixar atualização
Fusão automática
Alterar o branch atual
Segurança Alta Média
Controlabilidade Alta Baixa

(3) O objetivo da recuperação


2. Operações básicas de recuperação

(1) Receber todas as atualizações

▶ Exemplo: Receber atualizações

BASH
# Get updates from all remote repositories
git fetch

# Output:
# remote: Enumerating objects: 8, done.
# remote: Counting objects: 100% (8/8), done.
# remote: Compressing objects: 100% (5/5), done.
# remote: Total 5 (delta 3), reused 0 (delta 0), pack-reused 0
# Unpacking objects: 100% (5/5), 1.23 KiB | 1.23 MiB/s, done.
# From https://github.com/user/repo
#    a1b2c3d..d4e5f6g  main        -> origin/main
#  * [new branch]      feature     -> origin/feature
#  * [new tag]         v1.0.0      -> v1.0.0

(2) Recuperar um controle remoto específico

▶ Exemplo: Como recuperar um controle remoto específico

BASH
# GetoriginUpdates
git fetch origin

# GetupstreamUpdates
git fetch upstream

# Get all remote repositories
git fetch --all

# Output:
# Fetching origin
# Fetching upstream
# Fetching backup

(3) Recuperar um branch específico

▶ Exemplo: Como recuperar um branch específico

BASH
# Get a Specific Branch
git fetch origin main

# Retrieve Multiple Branches
git fetch origin main develop

# Fetch a remote branch with a different name locally
git fetch origin main:local-main

# Retrieve and Create a Local Branch
git fetch origin feature:feature

3. Visualize as atualizações que você recebeu

(1) Visualizar ramificações remotas

▶ Exemplo: Visualizando um branch remoto

BASH
# Get Updates
git fetch origin

# View Remote Branches
git branch -r

# Output:
#   origin/HEAD -> origin/main
#   origin/main
#   origin/develop
#   origin/feature

# View All Branches
git branch -a

# Output:
# * main
#   develop
#   remotes/origin/HEAD -> origin/main
#   remotes/origin/main
#   remotes/origin/develop
#   remotes/origin/feature

(2) Visualizar o conteúdo da atualização remota

▶ Exemplo: Visualizar detalhes da atualização

BASH
# View the latest commit on a remote branch
git log origin/main

# Output:
# commit d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2
# Author: Zhang San <zhangsan@example.com>
# Date:   Mon Jan 1 10:00:00 2026 +0800
#
#     feat: Add a New Feature

# View new commits on the remote repository(Not available locally)
git log main..origin/main

# Output:
# d4e5f6g (origin/main) feat: Add a New Feature
# h7i8j9k fix: FixBug

# View commits that exist locally but not remotely
git log origin/main..main

# View Bidirectional Differences
git log main...origin/main

(3) Comparando o local e o remoto

▶ Exemplo: Comparando diferenças

BASH
# Compare the differences between local and remote
git diff main origin/main

# View Difference Statistics
git diff --stat main origin/main

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

# View the list of modified files
git diff --name-only main origin/main

# Output:
# src/auth.js
# src/user.js

# View detailed file status
git diff --name-status main origin/main

# Output:
# M  src/auth.js
# M  src/user.js

4. Incorporar as atualizações recuperadas

(1) Incorporar atualizações remotas

▶ Exemplo: Atualização por mesclagem

BASH
# Get Updates
git fetch origin

# View Updates
git log main..origin/main

# Merge Remote Updates
git merge origin/main

# Output:
# Updating a1b2c3d..d4e5f6g
# Fast-forward
#  src/auth.js | 10 ++++++++++
#  1 file changed, 10 insertions(+)

(2) Fusão usando rebase

▶ Exemplo: Atualização por rebase

BASH
# Get Updates
git fetch origin

# UsagerebaseMerge
git rebase origin/main

# Output:
# First, rewinding head to replay your work on top of it...
# Fast-forwarded main to d4e5f6g.

# If there is a conflict
# CONFLICT (content): Merge conflict in file.js
# After Resolving the Conflict
git add file.js
git rebase --continue

(3) Fusão seletiva

▶ Exemplo: Selecionar um commit específico

BASH
# Get Updates
git fetch origin

# View new commits on the remote repository
git log main..origin/main --oneline

# Output:
# d4e5f6g feat: Add FeatureC
# h7i8j9k fix: FixBug
# k9l0m1n feat: Add FeatureB

# Merge only a specific commit
git cherry-pick h7i8j9k

# Or merge multiple commits
git cherry-pick k9l0m1n d4e5f6g

5. Recuperar tags

(1) Recuperar tags remotas

▶ Exemplo: Como recuperar uma tag

BASH
# Get Updates(Including tags)
git fetch origin

# Output:
#  * [new tag]         v1.0.0      -> v1.0.0
#  * [new tag]         v1.1.0      -> v1.1.0

# View All Tags
git tag

# Output:
# v1.0.0
# v1.1.0

# View tag details
git show v1.0.0

(2) Recuperar uma tag específica

▶ Exemplo: Como recuperar uma tag específica

BASH
# Get a specific tag
git fetch origin refs/tags/v1.0.0:refs/tags/v1.0.0

# Get all tags
git fetch --tags

# Delete Local Tags(Remotely Deleted)
git fetch --prune-tags

# Or
git fetch -p --prune-tags

6. Explicação detalhada das opções

(1) Opções comuns de recuperação

Opção Descrição Caso de uso
--all Buscar todos os controles remotos Atualizar todos os controles remotos
-p Limpar referências obsoletas Ramificação remota excluída
--tags Obter todas as tags Sincronizar tags
--prune-tags Limpar tags expiradas As tags foram excluídas
--dry-run Simular recuperação Visualizar o conteúdo recuperado
--verbose Saída detalhada Depuração

▶ Exemplo: Como usar a opção “Get”

BASH
# Clean up expired remote branch references
git fetch -p

# Output:
# From https://github.com/user/repo
#  x [deleted]         (none)     -> origin/old-feature

# Delete Expired Tags
git fetch --prune-tags

# Simulated Acquisition
git fetch --dry-run

# Detailed Output
git fetch --verbose

# Gain Insight(Shallow Cloning)
git fetch --depth=1

# Get a single branch
git fetch --single-branch

(2) Limpar referências expiradas

▶ Exemplo: Limpeza de referências remotas

BASH
# View the branches that need to be cleaned up
git remote prune origin --dry-run

# Output:
# * origin/deleted-branch would be pruned

# Perform Cleanup
git remote prune origin

# Or usefetch -p
git fetch -p

# Output:
# From https://github.com/user/repo
#  x [deleted]         (none)     -> origin/deleted-branch

7. O fluxo de trabalho de busca

(1) Fluxo de trabalho de atualizações de segurança

100%
sequenceDiagram
    participant Developer
    participant Local Warehouse
    participant Remote Branch
    participant Remote Repository
    
    Developer->>Remote Repository: git fetch origin
    Remote Repository->>Remote Branch: Updateorigin/main
    Developer->>Remote Branch: git log main..origin/main
    Developer->>Remote Branch: git diff main origin/main
    Developer->>Local Warehouse: git merge origin/main

(2) Cenários de aplicação no mundo real

▶ Exemplo: fluxo de trabalho de busca

BASH
# Scene1:Check for Updates Before Starting Work
git fetch origin
git log main..origin/main --oneline

# Output:
# d4e5f6g feat: New Features
# h7i8j9k fix: BugFix

# View Specific Changes
git diff main origin/main

# Decide whether to merge
git merge origin/main

# Scene2:There is unsubmitted work,Get it first, then decide
git fetch origin
git status

# Output:
# On branch main
# Your branch is behind 'origin/main' by 2 commits.

# View Updates
git log HEAD..origin/main

# Save the current work
git stash

# Merge Updates
git merge origin/main

# Return to Work
git stash pop

# Scene3:ForkWorkflow
git fetch upstream
git log main..upstream/main
git merge upstream/main
git push origin main

(3) Script de sincronização periódica

▶ Exemplo: Script de sincronização automática

BASH
#!/bin/bash
# sync.sh - Regularly Synchronize Remote Updates

# Get all remote updates
git fetch --all

# Check the status of each branch
for branch in $(git branch --format='%(refname:short)'); do
    upstream=$(git rev-parse --abbrev-ref $branch@{upstream} 2>/dev/null)
    if [ -n "$upstream" ]; then
        behind=$(git rev-list --count $branch..$upstream 2>/dev/null)
        ahead=$(git rev-list --count $upstream..$branch 2>/dev/null)
        if [ "$behind" -gt 0 ] || [ "$ahead" -gt 0 ]; then
            echo "$branch: behind $behind, ahead $ahead"
        fi
    fi
done

# Ask if it's synced
read -p "Sync main branch? (y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    git checkout main
    git merge origin/main
fi

❓ Perguntas Frequentes

P: Devo usar fetch ou pull?

R: Recomendamos usar o fetch. O fetch é mais seguro, pois permite que você analise as alterações antes de decidir se deseja mesclá-las. O pull mescla automaticamente, o que pode resultar em conflitos inesperados. É melhor adquirir o hábito de usar o fetch antes de mesclar.

P: O fetch modifica o código local?

R: Não. O fetch apenas baixa atualizações para referências de branches remotos (como origin/main); ele não modifica o branch atual nem o diretório de trabalho. É necessário fazer a fusão ou o rebase manualmente para modificar o código local.

P: Como posso ver o que o Fetch baixou?

R: Use git log HEAD..origin/main para visualizar os novos commits no remoto, git diff HEAD origin/main para visualizar as diferenças e git diff --stat HEAD origin/main para visualizar as estatísticas.

P: Como faço para fazer a integração após um fetch?

R: Use git merge origin/main para mesclar atualizações remotas ou use git rebase origin/main para realizar uma mesclagem com rebase. Recomendamos o uso do rebase para manter um histórico linear.

P: Como faço para limpar as referências a ramos remotos excluídos?

R: Use git fetch -p ou git remote prune origin para limpar as referências a branches remotos expirados em sua máquina local. Isso não afeta o repositório remoto; limpa apenas as referências locais.


📖 Resumo


📝 Exercícios

  1. Exercício básico: Crie um novo commit no repositório remoto, use fetch localmente para recuperar as atualizações, visualize o novo commit e as diferenças no repositório remoto e, em seguida, faça a mesclagem manualmente.

  2. Exercício avançado: Simule um fluxo de trabalho de bifurcação: adicione dois repositórios remotos, origin e upstream; baixe as atualizações de upstream; analise as diferenças; faça a fusão seletiva delas no seu repositório local; e, em seguida, envie para origin.

  3. Desafio: Escreva um script que busque periodicamente todos os repositórios remotos, verifique as diferenças entre cada branch e o repositório remoto, gere um relatório de sincronização e indique quais branches precisam ser sincronizados.

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%