Git: Um guia detalhado sobre o gerenciamento de…
Os repositórios remotos são a base da colaboração em equipe. Por meio deles, os membros da equipe podem compartilhar código, sincronizar alterações e colaborar no desenvolvimento. O Git oferece suporte a vários repositórios remotos, permitindo uma configuração flexível de diferentes modelos de colaboração.
1. Noções básicas sobre repositórios remotos
(1) O que é um repositório remoto?
Um repositório remoto é um repositório de controle de versão hospedado em um servidor web, utilizado para:
- Compartilhamento de código: Os membros da equipe podem acessar e modificar o código
- Desenvolvimento colaborativo: Várias pessoas podem trabalhar no mesmo projeto ao mesmo tempo
- Backup de código: O código local pode ser enviado para um backup remoto
- Integração contínua: aciona compilações e testes automatizados
graph TB
subgraph Local
A[DeveloperALocal Warehouse]
B[DeveloperBLocal Warehouse]
C[DeveloperCLocal Warehouse]
end
subgraph Remote
D[Remote Repository<br/>GitHub/GitLab]
end
A <-->|push/pull| D
B <-->|push/pull| D
C <-->|push/pull| D
style D fill:#d4edda
(2) Tipos de repositórios remotos
Plataformas comuns de hospedagem de repositórios remotos:
- GitHub: A maior comunidade de código aberto, com repositórios acessíveis ao público
- GitLab: Pode ser hospedado localmente e oferece uma ampla gama de recursos
- Bitbucket: Um produto da Atlassian que oferece repositórios privados gratuitos
- Gitee: Uma plataforma nacional com alta velocidade de acesso
- Servidor auto-hospedado: Controle total, ideal para empresas
(3) Nome do repositório remoto
Por padrão, o Git usa dois nomes:
- origin: Nome padrão do repositório remoto (definido automaticamente ao clonar)
- upstream: Repositório upstream (utilizado no fluxo de trabalho de fork)
2. Visualizando um repositório remoto
(1) Visualizar o nome do repositório remoto
▶ Exemplo: Listar repositórios remotos
# View the name of the remote repository
git remote
# Output:
# origin
# View All Remote Repositories(IncludingURL)
git remote -v
# Output:
# origin https://github.com/user/repo.git (fetch)
# origin https://github.com/user/repo.git (push)
# upstream https://github.com/original/repo.git (fetch)
# upstream https://github.com/original/repo.git (push)
(2) Visualizar detalhes do repositório remoto
▶ Exemplo: Ver detalhes
# VieworiginDetails
git remote show origin
# Output:
# * remote origin
# Fetch URL: https://github.com/user/repo.git
# Push URL: https://github.com/user/repo.git
# HEAD branch: main
# Remote branches:
# main tracked
# develop tracked
# feature new (next fetch will store in remotes/origin)
# Local branches configured for 'git pull':
# main merges with remote main
# develop merges with remote develop
# Local refs configured for 'git push':
# main pushes to main (up to date)
# develop pushes to develop (local out of date)
(3) Visualização de ramificações remotas
▶ Exemplo: Listar ramificações remotas
# View Remote Branches
git branch -r
# Output:
# origin/HEAD -> origin/main
# origin/main
# origin/develop
# origin/feature
# View All Branches(Local+Remote)
git branch -a
# Output:
# * main
# develop
# remotes/origin/HEAD -> origin/main
# remotes/origin/main
# remotes/origin/develop
# remotes/origin/feature
3. Adicionar um repositório remoto
(1) Adicionar um novo repositório remoto
▶ Exemplo: Adicionando um repositório remoto
# Add a Remote Repository
git remote add origin https://github.com/user/repo.git
# Add a second remote repository
git remote add upstream https://github.com/original/repo.git
# Add a named remote repository
git remote add backup git@backup-server.com:repo.git
# Verification: Added successfully
git remote -v
# Output:
# origin https://github.com/user/repo.git (fetch)
# origin https://github.com/user/repo.git (push)
# upstream https://github.com/original/repo.git (fetch)
# upstream https://github.com/original/repo.git (push)
# backup git@backup-server.com:repo.git (fetch)
# backup git@backup-server.com:repo.git (push)
(2) Utilização de URLs diferentes para busca e envio
▶ Exemplo: Configurando diferentes URLs
# Add a Remote Repository: different URLs for fetch and push
git remote add origin https://github.com/user/repo.git
git remote set-url --push origin git@github.com:user/repo.git
# View Configuration
git remote -v
# Output:
# origin https://github.com/user/repo.git (fetch)
# origin git@github.com:user/repo.git (push)
# Common config: fetch via HTTPS, push via SSH
(3) Adicionar automaticamente “origin” ao clonar
▶ Exemplo: Clonando um repositório
# Automatically add when cloning a repositoryorigin
git clone https://github.com/user/repo.git
# View Remote Repositories
git remote -v
# Output:
# origin https://github.com/user/repo.git (fetch)
# origin https://github.com/user/repo.git (push)
# Specify a different name when cloning
git clone -o myremote https://github.com/user/repo.git
git remote -v
# Output:
# myremote https://github.com/user/repo.git (fetch)
# myremote https://github.com/user/repo.git (push)
4. Modificando o repositório remoto
(1) Renomeando um repositório remoto
▶ Exemplo: Renomeação
# Rename a Remote Repository
git remote rename origin github
# Verification
git remote -v
# Output:
# github https://github.com/user/repo.git (fetch)
# github https://github.com/user/repo.git (push)
(2) Modificar a URL do repositório remoto
▶ Exemplo: Modificando uma URL
# Modify a Remote RepositoryURL
git remote set-url origin https://github.com/newuser/newrepo.git
# Editfetch URL
git remote set-url --delete origin https://github.com/user/repo.git
git remote set-url --add origin https://github.com/newuser/newrepo.git
# Editpush URL
git remote set-url --push origin git@github.com:user/repo.git
# Verify Changes
git remote -v
(3) Adicionar e excluir URLs
▶ Exemplo: Gerenciamento de várias URLs
# Addfetch URL
git remote set-url --add origin https://backup.com/repo.git
# Addpush URL
git remote set-url --add --push origin https://backup.com/repo.git
# DeleteURL
git remote set-url --delete origin https://backup.com/repo.git
# View AllURL
git remote -v
5. Exclusão de um repositório remoto
(1) Remover uma referência a um repositório remoto
▶ Exemplo: Excluindo um repositório remoto
# Delete a remote repository reference(Does not affect the remote repository itself)
git remote remove upstream
# Or userm
git remote rm backup
# Confirm Deletion
git remote
# Output:
# origin
(2) Limpar referências a ramos remotos expirados
▶ Exemplo: Limpeza de um branch remoto
# Delete a remote branch(Branches on a remote repository)
git push origin --delete feature
# Clean up references to remote branches that have been deleted locally
git fetch -p
# Or
git remote prune origin
# View the branches that need to be cleaned up
git remote prune origin --dry-run
# Output:
# * origin/feature would be pruned
6. Operações avançadas em repositórios remotos
(1) Configuração do fluxo de trabalho do fork
▶ Exemplo: Configurando um fluxo de trabalho de bifurcação
# 1. ForkFrom the original repository to your account
# 2. Clone YourselfFork
git clone https://github.com/yourname/repo.git
# 3. Add the original repository asupstream
git remote add upstream https://github.com/original/repo.git
# 4. View Remote Repositories
git remote -v
# Output:
# origin https://github.com/yourname/repo.git (fetch)
# origin https://github.com/yourname/repo.git (push)
# upstream https://github.com/original/repo.git (fetch)
# upstream https://github.com/original/repo.git (push)
# 5. Synchronize with upstream updates
git fetch upstream
git merge upstream/main
# 6. Push to your ownFork
git push origin main
(2) Fluxo de trabalho para vários repositórios remotos
graph TB
A[Local Warehouse] -->|push| B[GitHub<br/>origin]
A -->|push| C[GitLab<br/>gitlab]
A -->|push| D[Backup Server<br/>backup]
B -->|pull| A
C -->|pull| A
style A fill:#fff3cd
style B fill:#d4edda
style C fill:#c3e6cb
style D fill:#cce5ff
▶ Exemplo: Configurando vários repositórios remotos
# Add Multiple Remote Repositories
git remote add origin https://github.com/user/repo.git
git remote add gitlab https://gitlab.com/user/repo.git
git remote add backup git@backup-server.com:repo.git
# Push to all remote repositories
git push origin main
git push gitlab main
git push backup main
# Or addremote.pushDefaultLayout
git config remote.pushDefault origin
# AddpushurlAutomatically Push to Multiple Repositories
git remote set-url --add --push origin https://github.com/user/repo.git
git remote set-url --add --push origin https://gitlab.com/user/repo.git
# Nowpush originIt will be pushed to both repositories at the same time
git push origin main
(3) Visualizar atualizações no repositório remoto
▶ Exemplo: Visualização de atualizações remotas
# Get Remote Updates(Do not merge)
git fetch origin
# View the latest status of a remote branch
git branch -r
# View RemotemainBranch Commits
git log origin/main
# Compare the differences between local and remote
git diff main origin/main
# View details of a remote branch
git show origin/feature
7. Configurando repositórios remotos
(1) Configurar as definições do repositório remoto
▶ Exemplo: Parâmetros de configuração
# View Remote Repository Configuration
git config --local --list | grep remote
# Output:
# remote.origin.url=https://github.com/user/repo.git
# remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
# LayoutfetchStrategy
git config remote.origin.fetch "+refs/heads/*:refs/remotes/origin/*"
# Layoutpush URL
git config remote.origin.pushurl git@github.com:user/repo.git
# Configure the default push branch
git config branch.main.remote origin
git config branch.main.merge refs/heads/main
(2) SSH x HTTPS
▶ Exemplo: Alternância entre protocolos
# UsageHTTPS
git remote set-url origin https://github.com/user/repo.git
# UsageSSH(Recommendations)
git remote set-url origin git@github.com:user/repo.git
# UsageGitAgreement
git remote set-url origin git://github.com/user/repo.git
# HTTPSYou must enter your password each time,Or use credential storage
git config --global credential.helper store
# SSHA key needs to be configured
ssh-keygen -t ed25519 -C "your_email@example.com"
# Add the public key toGitHub/GitLab
❓ Perguntas Frequentes
P: Qual é a diferença entre “origem” e “a montante”?
R: “origin” é o repositório do qual você fez o fork, e “upstream” é o repositório original. No fluxo de trabalho de fork, você faz o pull das atualizações do “upstream”, faz o push delas para o “origin” e, em seguida, cria uma solicitação de pull.
P: Como faço para enviar para vários repositórios remotos ao mesmo tempo?
R: Use
git remote set-url --add --pushpara adicionar várias URLs de envio, de modo que um único envio seja enviado para todas as URLs configuradas. Como alternativa, você pode enviar manualmente para cada repositório remoto.
P: A exclusão de uma referência a um repositório remoto afeta o repositório remoto?
R: Não.
git remote removeIsso apenas exclui a configuração de referência local; não afeta o repositório remoto em si. O repositório remoto ainda existe; apenas não é mais rastreado localmente.
P: O que é melhor, HTTPS ou SSH?
R: O SSH é mais prático; depois de configurar uma chave, você não precisa digitar uma senha todas as vezes. O HTTPS é mais simples — não exige a configuração de uma chave —, mas é preciso digitar uma senha ou usar um gerenciador de credenciais. Recomendamos o uso do SSH.
P: Como faço para visualizar os detalhes de um repositório remoto?
R: Use
git remote show <name>para visualizar informações detalhadas, incluindo a URL, os branches rastreados, as regras de pull/push configuradas e muito mais.
📖 Resumo
- Os repositórios remotos são a base da colaboração em equipe, permitindo o compartilhamento e a sincronização de código
- Visualizar controle remoto:
git remoteexibe o nome,-vexibe a URL - Adicionar repositório remoto:
git remote add <name> <url>Adicionar um novo repositório remoto - Editar remoto:
set-urlEditar URL,renameRenomear - Excluir controle remoto:
git remote removeExcluir referência - Fluxo de trabalho de fork: “origin” é o fork e “upstream” é o repositório original
- Vários repositórios remotos: é possível configurar vários repositórios remotos para permitir backups e sincronização entre várias plataformas.
📝 Exercícios
-
Exercício básico: Criar um repositório local, adicionar um repositório remoto do GitHub, visualizar as informações do repositório remoto, modificar a URL do repositório remoto e praticar operações básicas de gerenciamento de repositórios remotos.
-
Exercício avançado: Simule um fluxo de trabalho de fork: adicione dois repositórios remotos,
origineupstream; faça o pull das atualizações deupstream; faça o push delas paraorigin; e compreenda o modelo de colaboração do fluxo de trabalho de fork. -
Desafio: Configurar envios automáticos para vários repositórios remotos: Configurar várias URLs de envio para um único repositório remoto, de modo que um único envio seja enviado simultaneamente para o GitHub, o GitLab e um servidor de backup.