Git: Um guia detalhado sobre pull requests no Git e…

Um “pull” é o processo de recuperar atualizações de um repositório remoto e mesclá-las a um branch local. O pull permite que os membros da equipe sincronizem suas alterações e mantenham seu código local em sincronia com o repositório remoto. Compreender a diferença entre “pull” e “fetch” é fundamental para a colaboração em equipe.

1. Conceitos básicos do modelo “pull”

(1) O que é um “pull”?

Um pull é uma combinação de duas operações:

  1. fetch: Baixar atualizações de um repositório remoto
  2. merge: Mesclar o branch remoto com o branch atual
100%
graph TB
    A[Remote Repository<br/>Remote] -->|git fetch| B[Remote Branch Replica<br/>origin/main]
    B -->|git merge| C[Current Branch<br/>main]
    
    A -.->|git pull = fetch + merge| C
    
    style A fill:#d4edda
    style B fill:#fff3cd
    style C fill:#c3e6cb

6. Detalhado: pull x fetch

Ação Descrição Impacto
pull buscar + mesclar modificar o branch atual
fetch Baixar apenas atualizações Não modificar o branch atual

(3) O objetivo do puxão


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

(1) Fazer o pull do branch atual

▶ Exemplo: Baixando atualizações

BASH
# Pull updates from the current branch
git pull

# Output:
# remote: Enumerating objects: 5, done.
# remote: Counting objects: 100% (5/5), done.
# remote: Compressing objects: 100% (3/3), done.
# remote: Total 3 (delta 1), reused 0 (delta 0), pack-reused 0
# Unpacking objects: 100% (3/3), 285 bytes | 285.00 KiB/s, done.
# From https://github.com/user/repo
#    a1b2c3d..d4e5f6g  main        -> origin/main
# Updating a1b2c3d..d4e5f6g
# Fast-forward
#  file.js | 1 +
#  1 file changed, 1 insertion(+)

(2) Fazer o pull do branch especificado

▶ Exemplo: Baixando um branch específico

BASH
# Pull a specified remote branch
git pull origin main

# Pull a remote branch into a local branch with a different name
git pull origin remote-branch:local-branch

# Pull updates from all remote branches
git pull --all

# Pull and view details
git pull --verbose

(3) Inspeção pré-extrusão

▶ Exemplo: Verificação pré-puxada

BASH
# View differences between local and remote versions
git fetch
git diff main origin/main

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

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

# View the files to be pulled
git diff --name-only main origin/main

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

# Confirm before pulling
git pull

3. Estratégia de pull

(1) Puxar usando merge (padrão)

▶ Exemplo: mesclar pull

BASH
# Use by defaultmergePull
git pull

# Equivalent to
git fetch
git merge origin/main

# A merge commit will be created after the pull.(If there is a fork)
git log --oneline --graph

# Output:
# *   a1b2c3d Merge branch 'main' of https://github.com/user/repo
# |\
# | * d4e5f6g (origin/main) Remote commit
# * | h7i8j9k Local commit
# |/
# * k9l0m1n Base commit

(2) Fazer o pull usando rebase

▶ Exemplo: Rebase de uma solicitação de pull

BASH
# UsagerebasePull
git pull --rebase

# Output:
# remote: Enumerating objects: 5, done.
# From https://github.com/user/repo
#    a1b2c3d..d4e5f6g  main        -> origin/main
# First, rewinding head to replay your work on top of it...
# Fast-forwarded main to d4e5f6g.

# View History(Linear,No merged commits)
git log --oneline --graph

# Output:
# * h7i8j9k Local commit
# * d4e5f6g (origin/main) Remote commit
# * k9l0m1n Base commit

(3) Merge x Rebase Pull

100%
graph TB
    subgraph mergePull
        A1[Local Commit] --> M1[Merge Commit]
        B1[Remote Commit] --> M1
    end
    
    subgraph rebasePull
        A2[Remote Commit] --> B2[Local Commit<br/>after rebase]
    end
    
    style M1 fill:#fff3cd
    style B2 fill:#d4edda

Pull para fusão:

Rebase:


4. Resolução de conflitos em pull requests

(1) Ocorrem conflitos durante uma operação de pull

▶ Exemplo: Conflitos de pull

BASH
# The same file was modified both locally and remotely
git pull

# Output:
# remote: Enumerating objects: 5, done.
# From https://github.com/user/repo
#    a1b2c3d..d4e5f6g  main        -> origin/main
# Auto-merging file.js
# CONFLICT (content): Merge conflict in file.js
# Automatic merge failed; fix conflicts and then commit the result.

(2) Resolução de conflitos de pull

▶ Exemplo: Resolução de conflitos

BASH
# View Conflict Status
git status

# Output:
# You have unmerged paths.
#   (fix conflicts and run "git commit")
# 
# Unmerged paths:
#   (use "git add <file>..." to mark resolution)
#   both modified:   file.js

# View Conflict Details
cat file.js

# Output:
# <<<<<<< HEAD
# Local Changes
# =======
# Remote Content Editing
# >>>>>>> d4e5f6g

# Editing Files to Resolve Conflicts
# Keep the necessary content

# Mark the conflict as resolved
git add file.js

# Complete the merger
git commit

# Push to Remote
git push

(3) Cancelar a retirada

▶ Exemplo: Cancelar um pull

BASH
# Pull conflict,I want to cancel
git merge --abort

# Or
git reset --merge

# RegardingrebasePull
git rebase --abort

5. Explicação detalhada das opções de pull

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

Opção Descrição Caso de uso
--rebase Fazer pull usando rebase Manter um histórico linear
--no-rebase Fazer pull usando merge Manter o histórico completo
--ff-only Apenas mesclagens fast-forward Garantir que não haja bifurcações
--force Forçar pull Substituir alterações locais
--all Baixar tudo remotamente Atualizar tudo remotamente
--dry-run Simular busca Visualizar conteúdo buscado

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

BASH
# Only fast-forward merges are allowed
git pull --ff-only

# Output(If you can't fast-forward):
# fatal: Not possible to fast-forward, aborting.

# Simulated Pull
git pull --dry-run

# Pull all remote repositories
git pull --all

# Set the Default Pull Method
git config pull.rebase true  # Use by defaultrebase
git config pull.rebase false # Use by defaultmerge
git config pull.ff only      # Fast-forward only

(2) Fazer o pull de um repositório remoto específico

▶ Exemplo: Baixando de um servidor remoto específico

BASH
# Pullorigin
git pull origin

# Pullupstream
git pull upstream main

# Pull a specific branch
git pull origin feature

# Pull and Set Upstream
git pull --set-upstream origin feature

6. Comparação detalhada: pull x fetch

(1) Usando fetch

▶ Exemplo: Como usar o fetch

BASH
# Get Remote Updates(Do not merge)
git fetch origin

# Output:
# remote: Enumerating objects: 5, done.
# From https://github.com/user/repo
#    a1b2c3d..d4e5f6g  main        -> origin/main
#  * [new branch]      feature     -> origin/feature

# View Remote Branches
git branch -r

# Output:
#   origin/main
#   origin/feature

# View Remote Updates
git log origin/main

# Compare Differences
git diff main origin/main

# Manual Merge
git merge origin/main

# Orrebase
git rebase origin/main

(2) Quando usar fetch

100%
graph TB
    A[Need to check for remote updates] --> B[Usagefetch]
    B --> C[View Differences]
    C --> D{Merge or Not?}
    D -->|Yes| E[Manualmerge/rebase]
    D -->|No| F[Keep the current state]
    
    style B fill:#d4edda
    style E fill:#c3e6cb

Quando usar o fetch:

Quando usar pull:

(3) fetch + merge x pull

▶ Exemplo: Comparando os dois métodos

BASH
# Method1:Directlypull
git pull origin main

# Method2:fetch + merge(Safer)
git fetch origin
git diff main origin/main  # View Differences
git merge origin/main      # Merge after confirmation

# Method3:fetch + rebase
git fetch origin
git diff main origin/main
git rebase origin/main

7. Melhores práticas para pull requests

(1) Fluxo de trabalho diário de pull

▶ Exemplo: Fluxo de trabalho recomendado

BASH
# 1. Pull the latest code before starting work
git checkout main
git pull --rebase origin main

# 2. Create a feature branch
git checkout -b feature/new-feature

# 3. Develop and Submit
git add .
git commit -m "feat: Add a New Feature"

# 4. Fetch updates again before pushing
git fetch origin
git rebase origin/main

# 5. Push
git push origin feature/new-feature

(2) Melhores práticas para resolver conflitos de pull

▶ Exemplo: Processo de resolução de conflitos

BASH
# Pull conflict
git pull

# 1. View Conflicting Files
git status

# 2. Using Tools to Resolve Conflicts
git mergetool

# 3. Or edit the file manually

# 4. Test Code
npm test

# 5. Mark the conflict as resolved
git add .

# 6. Complete the merger
git commit

# 7. Push
git push

(3) Manter os ramos sincronizados

▶ Exemplo: Sincronização programada

BASH
# Regularly Synchronize Remote Updates
git fetch origin

# View the status of all branches
git branch -vv

# Output:
# * main    a1b2c3d [origin/main: behind 3] feat: Add Feature
#   develop d4e5f6g [origin/develop: ahead 2] Fix: FixBug
#   feature h7i8j9k [origin/feature] WIP: New Features

# Synchronize a Branch That Is Behind
git checkout main
git pull

# Or sync all branches
git pull --all

❓ Perguntas Frequentes

P: Qual é a diferença entre pull e fetch?

R: git pull = git fetch + git merge baixará as atualizações e as incorporará ao branch atual. git fetch apenas baixa as atualizações sem modificar o branch atual, o que é mais seguro.

P: Quando se deve usar --rebase para puxar?

R: Use isso quando quiser manter o histórico de commits linear e evitar commits de mesclagem. Um rebase reordena os commits locais para que apareçam acima dos commits remotos, resultando em um histórico mais claro.

P: O que devo fazer se ocorrer um conflito durante uma sincronização?

R: Para resolver conflitos em um arquivo, use git add para marcar o conflito como resolvido e, em seguida, git commit para concluir a fusão. Se você não quiser resolver o conflito, pode usar git merge --abort para cancelar a integração.

P: Como faço para ver quais novos commits estão no remoto?

R: Primeiro, use git fetch para baixar a atualização; depois, use git log HEAD..origin/main para visualizar os novos commits remotos ou use git diff HEAD origin/main para visualizar as diferenças.

P: O que devo fazer se receber um erro de “históricos não relacionados” ao fazer o pull?

R: Isso significa que os repositórios local e remoto não têm histórico em comum (por exemplo, foram inicializados separadamente). O uso de git pull --allow-unrelated-histories permite mesclar históricos não relacionados.


📖 Resumo


📝 Exercícios

  1. Exercício básico: Crie um commit no seu repositório local e envie-o para o repositório remoto. Em seguida, clone o repositório para outro local, faça alterações e envie-as. Volte ao repositório original e faça o pull das atualizações para experimentar o processo completo de pull.

  2. Exercício avançado: Compare um pull com merge com um pull com rebase: crie commits nos repositórios local e remoto, execute um pull usando cada um dos métodos e observe as diferenças no histórico do gráfico.

  3. Desafio: Simule um cenário de conflito ao fazer o pull: faça alterações no mesmo local do mesmo arquivo, tanto localmente quanto remotamente; ao fazer o pull, ocorre um conflito; resolva manualmente o conflito e conclua a fusão.

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%