Git: Uma explicação detalhada sobre os comandos `push` do…
Um “push” é o processo de enviar um commit local para um repositório remoto. Por meio do push, os membros da equipe podem compartilhar código, sincronizar alterações e colaborar no desenvolvimento. Compreender as diversas opções e considerações relacionadas ao push é essencial para a colaboração em equipe.
1. Conceitos básicos sobre notificações push
(1) O que é uma notificação push?
Um push é o processo de enviar commits de um repositório local para um repositório remoto:
- Envio de commit: Enviar um novo commit local para o repositório remoto
- Atualizar ramificação: Atualizar o ponteiro da ramificação remota
- Código de sincronização: Permita que os membros da sua equipe vejam suas alterações
- Fazer backup do código: Faça backup do código em um repositório remoto
graph LR
A[Local Warehouse<br/>Local Repository] -->|git push| B[Remote Repository<br/>Remote Repository]
B --> C[Team Members<br/>Team Members]
C -->|git pull| D[Other Local Repositories]
style A fill:#fff3cd
style B fill:#d4edda
style C fill:#c3e6cb
(2) Pré-requisitos para notificações push
Antes de enviar uma notificação push, certifique-se de:
- Há novos commits localmente (que não estão no remoto)
- O branch local é baseado no branch remoto (sem fork)
- Acesso de gravação a um repositório remoto
- A conexão de rede está funcionando corretamente
(3) Direção do impulso
O envio é uma operação unidirecional: local → remoto
- O envio não afeta o repositório local
- Um push atualizará o branch remoto
- Após o envio, os membros da equipe podem baixar as atualizações
2. Operações básicas de envio
(1) Enviar para um branch remoto
▶ Exemplo: Notificação push básica
# Push the current branch tooriginthe corresponding branch
git push
# Output:
# fatal: The current branch feature has no upstream branch.
# To push the current branch and set the remote as upstream, use
# git push --set-upstream origin feature
# Push and configure the upstream branch
git push -u origin feature
# Or
git push --set-upstream origin feature
# Output:
# Enumerating objects: 5, done.
# Counting objects: 100% (5/5), done.
# Writing objects: 100% (3/3), 285 bytes | 285.00 KiB/s, done.
# Total 3 (delta 1), reused 0 (delta 0), pack-reused 0
# remote: Resolving deltas: 100% (1/1), completed with 1 local object.
# remote:
# remote: Create a pull request for 'feature' on GitHub by visiting:
# remote: https://github.com/user/repo/pull/new/feature
# To https://github.com/user/repo.git
# * [new branch] feature -> feature
# Branch 'feature' set up to track remote branch 'feature' from 'origin'.
(2) Enviar para um branch específico
▶ Exemplo: Enviar para um branch específico
# PushmainBranch toorigin
git push origin main
# Push a local branch to a remote branch with a different name
git push origin local-branch:remote-branch
# Push the current branch to the remote repositorymainBranch
git push origin HEAD:main
# Push all local branches
git push --all origin
# Output:
# To https://github.com/user/repo.git
# * [new branch] develop -> develop
# * [new branch] feature -> feature
# * [new branch] main -> main
(3) Verificação pós-envio
▶ Exemplo: Verificação dos resultados do push
# View Remote Branches
git branch -r
# Output:
# origin/HEAD -> origin/main
# origin/main
# origin/feature
# View the upstream settings for a local branch
git branch -vv
# Output:
# * main a1b2c3d [origin/main] feat: Add Feature
# feature d4e5f6g [origin/feature] WIP: New Features
# Check the status of the remote repository
git remote show origin
3. Etiquetas de empurrar
(1) Enviar tags para o repositório remoto
▶ Exemplo: Tags de push
# Create a tag
git tag v1.0.0
# Push a Single Tag
git push origin v1.0.0
# Output:
# To https://github.com/user/repo.git
# * [new tag] v1.0.0 -> v1.0.0
# Push All Tags
git push --tags
# Or
git push origin --tags
# Send tags along with the push notification
git push --follow-tags
# Push only lightweight tags
git push --follow-tags origin main
(2) Excluir uma tag remota
▶ Exemplo: Excluindo uma tag
# Delete Local Tags
git tag -d v1.0.0
# Delete Remote Tag
git push origin --delete v1.0.0
# Or userefspecGrammar
git push origin :refs/tags/v1.0.0
# Output:
# To https://github.com/user/repo.git
# - [deleted] v1.0.0
(3) Estratégia de promoção de tags
graph TB
A[Create a tag] --> B{Tag Type}
B -->|Lightweight Tags| C[No automatic push notifications]
B -->|Footnote Label| D[Recommended Posts]
C --> E[Manual Push]
D --> F[git push --tags]
style D fill:#d4edda
style F fill:#c3e6cb
4. Notificações push forçadas
(1) Quando é necessário um push forçado?
O force push é usado para modificar o histórico de commits de um commit enviado anteriormente:
- Modifiquei o último commit (--amend)
- Reescrevi a história usando
rebase - Commits agrupados
- Corrigimos um commit incorreto
(2) Usando --force
▶ Exemplo: Envio forçado
# Modify the last commit
git commit --amend -m "Revised commit message"
# Regular push notifications will fail
git push origin main
# Output:
# ! [rejected] main -> main (non-fast-forward)
# error: failed to push some refs to 'https://github.com/user/repo.git'
# Mandatory Push Notifications
git push --force
# Or
git push -f
# Output:
# + a1b2c3d...d4e5f6g main -> main (forced update)
(3) Usando --force-with-lease (Recomendado)
▶ Exemplo: Envio forçado por motivos de segurança
# --force-with-lease Safer
# If there are new commits pushed by others on the remote repository,Will reject the push notification
git push --force-with-lease
# Output:
# + a1b2c3d...d4e5f6g main -> main (forced update)
# If there are new commits on the remote
git push --force-with-lease
# Output:
# ! [rejected] main -> main (stale info)
# error: failed to push some refs to 'https://github.com/user/repo.git'
(4) Riscos das notificações push obrigatórias
graph TB
A[Mandatory Push Notifications] --> B{There is a new commit on the remote repository?}
B -->|Yes| C[Overwrite Another User's Submission<br/>Data Loss]
B -->|No| D[Security Updates]
C --> E[Teamwork Issues]
D --> F[Normal operation]
style C fill:#f8d7da
style D fill:#d4edda
⚠️ Aviso importante:
- Os envios forçados podem sobrescrever os commits dos membros da equipe
- Antes de executar um comando de força, verifique o status do controle remoto
- Use
--force-with-leaseprimeiro - Use os envios forçados com cautela ao colaborar em equipe
5. Explicação detalhada das opções de envio
(1) Opções comuns de envio
| Opção | Descrição | Caso de uso |
|---|---|---|
-u |
Configurar um branch upstream | Enviar um branch pela primeira vez |
-f |
Force Push | Enviar após modificar o histórico |
--force-with-lease |
Atualização obrigatória de segurança | Métodos recomendados para atualização obrigatória |
--all |
Enviar todos os ramos | Envio em lote |
--tags |
Enviar todas as tags | Versão de lançamento |
--dry-run |
Simular envio | Visualizar conteúdo do envio |
--verbose |
Saída detalhada | Envio para depuração |
▶ Exemplo: Como usar a opção “Push”
# Simulated Push Notification(Do not push)
git push --dry-run
# Output:
# To https://github.com/user/repo.git
# * [new branch] feature -> feature
# Detailed Output
git push --verbose
# Push and display progress
git push --progress
# Skip the hook during a push
git push --no-verify
(2) Configuração de envio
▶ Exemplo: Configurando o comportamento de notificação push
# Set the Default Push Policy
git config --global push.default simple
# push.default options:
# nothing - Do not push,Must be explicitly specified
# current - Push the current branch to the remote branch with the same name
# upstream - Push the current branch to its upstream branch
# simple - Similarupstream,But the branch names must be the same(Default)
# matching - Push all matching branches
# Configure Automatic Upstream Setup
git config --global push.autoSetupRemote true
# Right now, directlygit pushIt will automatically configure the upstream connection.
git push
(3) Ganchos de pressão
▶ Exemplo: Gancho de empurrar
# pre-pushHooks are executed before a push
# .git/hooks/pre-push
#!/bin/sh
# Run tests before deployment
npm test
if [ $? -ne 0 ]; then
echo "Tests failed, aborting push"
exit 1
fi
# Skip Hook Push
git push --no-verify
6. Cenários e melhores práticas para notificações push
(1) Como lidar com notificações push rejeitadas
▶ Exemplo: Como lidar com rejeições de push
# Push Rejected
git push origin main
# Output:
# ! [rejected] main -> main (fetch first)
# error: failed to push some refs to 'https://github.com/user/repo.git'
# hint: Updates were rejected because the remote contains work that you do
# hint: not have locally. This is usually caused by another repository pushing
# hint: to the same ref. You may want to first integrate the remote changes
# hint: (e.g., 'git pull ...') before pushing again.
# Solution1:Pull First, Then Push
git pull --rebase origin main
git push origin main
# Solution2:Push after merging
git pull origin main
git push origin main
# Solution3:Mandatory Push Notifications(Use with caution)
git push --force-with-lease origin main
(2) Fluxo de trabalho de envio
sequenceDiagram
participant Developer
participant Local Warehouse
participant Remote Repository
Developer->>Local Warehouse: git add & commit
Developer->>Remote Repository: git fetch
Developer->>Local Warehouse: git merge/rebase
Developer->>Remote Repository: git push
Remote Repository->>Developer: Push successful
(3) Melhores práticas para notificações push
▶ Exemplo: Melhores práticas para notificações push
# 1. Fetch the latest code before pushing.
git fetch origin
git rebase origin/main
# 2. Make sure your submission is complete
git status
git log origin/main..HEAD
# 3. Push to a feature branch
git push -u origin feature/user-auth
# 4. Create Pull Request (on GitHub)
# 5. Delete the remote branch after merging
git push origin --delete feature/user-auth
❓ Perguntas Frequentes
P: O que devo fazer se minha notificação push for rejeitada?
R: Normalmente, um push é rejeitado porque há novos commits no repositório remoto. Primeiro, use
git pullougit fetch + git merge/rebasepara sincronizar as atualizações remotas e, em seguida, resolva quaisquer conflitos antes de fazer o push.
P: Quando é necessário um push forçado?
R: É necessário realizar um “force push” ao modificar o histórico de commits de um repositório que já tenha sido enviado, como ao usar
--amendpara modificar um commit, ao usarrebasepara reescrever o histórico ou ao agrupar commits. No entanto, use essa opção com cautela; dê prioridade ao uso de--force-with-leaseem vez disso.
P: Qual é a diferença entre --force e --force-with-lease?
R: A opção --force sobrescreve incondicionalmente o branch remoto, o que pode resultar na perda dos commits de outras pessoas. A opção --force-with-lease verifica se há novos commits no remoto; caso haja, ela recusa o push, tornando o processo mais seguro.
P: Como faço para enviar um novo branch?
R: Use
git push -u origin <branch-name>para enviar o novo branch e definir o branch upstream. Depois disso, você pode usargit pushpara enviar diretamente.
P: Qual é a diferença entre um push tag e um push branch?
R: Use
git push origin <branch>para enviar o branch e usegit push origin <tag>ougit push --tagspara enviar todas as tags. As tags não são enviadas automaticamente junto com o branch.
📖 Resumo
- Um push é o processo de enviar um commit local para um repositório remoto.
- Envio básico:
git push origin <branch>Enviar para o branch remoto - Configure o upstream: use a opção
-upara definir o branch upstream; depois, você poderá fazer o push diretamente - Enviar tags:
--tagsEnviar todas as tags ou enviar uma única tag - Force Push:
--forceSubstituição forçada,--force-with-leaseMais seguro - Melhores práticas para o envio: faça o pull primeiro, depois o push; use o Force Push com cautela
📝 Exercícios
-
Exercício básico: Crie um repositório local e adicione um repositório remoto; faça um commit e envie-o para o repositório remoto para experimentar todo o processo de envio, incluindo a configuração de um branch upstream.
-
Exercício avançado: Simule um cenário em que um push seja rejeitado: crie um novo commit no repositório remoto, crie um novo commit localmente, tente fazer o push e veja se ele é rejeitado; em seguida, resolva o problema usando
pullourebaseantes de tentar o push novamente. -
Desafio: Experimente um push forçado: use
--amendpara modificar um commit que já tenha sido enviado, depois use--force-with-leasepara forçar o envio e compreenda os princípios e riscos de um push forçado.