DEV Community

Cover image for Fluxo completo do GIT para trabalhar
Brayan Monteiro
Brayan Monteiro

Posted on • Edited on

1 1

Fluxo completo do GIT para trabalhar

📌 1. Instalação e Configuração Inicial

Se for uma máquina nova, instale o Git:

🔹 Windows: Baixe aqui e instale.

🔹 Linux (Debian/Ubuntu):

sudo apt update && sudo apt install git -y
Enter fullscreen mode Exit fullscreen mode

🔹 Linux (Fedora/RHEL):

sudo dnf install git -y
Enter fullscreen mode Exit fullscreen mode

Depois de instalar, configure seu usuário:

git config --global user.name "Seu Nome"
git config --global user.email "seu@email.com"
Enter fullscreen mode Exit fullscreen mode

Verifique se ficou certo:

git config --list
Enter fullscreen mode Exit fullscreen mode

🔑 2. Autenticação no GitLab

O GitLab pode exigir autenticação via token de acesso pessoal (PAT) em vez de senha.

Para configurar:

1️⃣ Gerar um token no GitLab:

  • Vá em Configurações > Acessos Tokens no GitLab
  • Crie um token com permissão de leitura/gravação no repositório

2️⃣ Autenticar usando o token ao clonar ou enviar commits:

git clone https://oauth2:<TOKEN>@gitlab.com/usuario/repo.git
Enter fullscreen mode Exit fullscreen mode

ou configure o SSH para evitar login manual.

📥 3. Clonar um Repositório e Criar uma Branch de Desenvolvimento

🔹 Baixar um projeto do GitLab:

git clone https://gitlab.com/usuario/repositorio.git
Enter fullscreen mode Exit fullscreen mode

🔹 Entrar na pasta do repositório:

cd repositorio
Enter fullscreen mode Exit fullscreen mode

🔹 Listar branches disponíveis:

git branch -r
Enter fullscreen mode Exit fullscreen mode

🔹 Criar uma branch nova para desenvolvimento:

git checkout -b minha-branch
Enter fullscreen mode Exit fullscreen mode

🔹 Se a branch já existe no remoto:

git checkout -b minha-branch origin/minha-branch
Enter fullscreen mode Exit fullscreen mode

✏️ 4. Fazer Mudanças e Commitar

Após modificar arquivos, siga este fluxo:

🔹 Verificar o que mudou:

git status
Enter fullscreen mode Exit fullscreen mode

🔹 Adicionar os arquivos ao commit:

git add .
Enter fullscreen mode Exit fullscreen mode

🔹 Criar um commit com mensagem:

git commit -m "Descrição clara da mudança"
Enter fullscreen mode Exit fullscreen mode

🔹 Enviar as mudanças para o repositório remoto:

git push origin minha-branch
Enter fullscreen mode Exit fullscreen mode

🔹 Se for o primeiro push da branch para o remoto:

git push --set-upstream origin minha-branch
Enter fullscreen mode Exit fullscreen mode

📤 5. Atualizar o Código Antes de Trabalhar

Antes de começar a desenvolver, sempre atualize seu código:

🔹 Baixar as últimas mudanças da branch principal:

git checkout main  # Ou master
git pull origin main
Enter fullscreen mode Exit fullscreen mode

🔹 Atualizar sua branch com a última versão:

git checkout minha-branch
git merge main  # Ou rebase: git rebase main
Enter fullscreen mode Exit fullscreen mode

🔄 6. Resolver Conflitos e Corrigir Erros

Se houver conflitos ao fazer merge/rebase:

🔹 Ver arquivos com conflito:

git status
Enter fullscreen mode Exit fullscreen mode

🔹 Editar os arquivos manualmente, resolver o conflito e adicionar novamente:

git add arquivo-com-conflito
git commit -m "Resolvido conflito no arquivo X"
Enter fullscreen mode Exit fullscreen mode

🔄 7. Criar e Restaurar Commits

🔹 Se precisar desfazer mudanças antes de commitar:

git checkout -- arquivo.txt  # Restaura um arquivo específico
git reset --hard HEAD        # Restaura tudo (⚠️ perda de mudanças)
Enter fullscreen mode Exit fullscreen mode

🔹 Se precisar desfazer um commit já enviado:

git revert <ID-do-commit>
git push origin minha-branch
Enter fullscreen mode Exit fullscreen mode

📌 8. Revisão Final Antes de Enviar para Produção

🔹 Mesclar a branch de desenvolvimento na branch principal:

git checkout main
git merge minha-branch
Enter fullscreen mode Exit fullscreen mode

🔹 Enviar para produção (se aplicável):

git push origin main
Enter fullscreen mode Exit fullscreen mode

Fluxo para navegar entre as branchs: como Alternar Entre Branches no Git Sem Clonar o Repositório Novamente

Quando trabalhamos em projetos com Git, é comum precisarmos alternar entre diferentes branches sem perder o progresso atual. Neste artigo, vamos mostrar um fluxo eficiente para trocar de branch sem precisar clonar o repositório novamente.


🎯 Cenário: Você já clonou o repositório e precisa alternar de branch

Imagine que você já tem um repositório clonado e está atualmente na branch feature-login. Agora, deseja trabalhar nas branches feature-dashboard e feature-relatorio. Como fazer isso sem perder as mudanças?

📝 Passo 1: Verificar em Qual Branch Você Está

Antes de trocar de branch, veja em qual você está atualmente:

git branch
Enter fullscreen mode Exit fullscreen mode

A branch atual será marcada com um *.

Se houver mudanças não commitadas e você não quiser perdê-las ao trocar de branch, faça um stash para guardá-las temporariamente:

git stash
Enter fullscreen mode Exit fullscreen mode

🔀 Passo 2: Listar Todas as Branches Disponíveis

Para ver todas as branches remotas disponíveis, use:

git branch -r
Enter fullscreen mode Exit fullscreen mode

Exemplo de saída:

  origin/feature-login
  origin/feature-dashboard
  origin/feature-relatorio
  origin/develop
  origin/main
Enter fullscreen mode Exit fullscreen mode

🚀 Passo 3: Alternar Para Outra Branch

Agora, escolha a branch que deseja trabalhar. Para trocar para feature-dashboard, execute:

git checkout -b feature-dashboard origin/feature-dashboard
Enter fullscreen mode Exit fullscreen mode

Isso cria uma cópia local da branch remota e muda para ela.

Se quiser ir para a feature-relatorio, basta repetir o processo:

git checkout -b feature-relatorio origin/feature-relatorio
Enter fullscreen mode Exit fullscreen mode

🔄 Passo 4: Atualizar a Branch com o Código Mais Recente

Depois de mudar para a branch desejada, atualize o código para garantir que está com a versão mais recente:

git pull origin feature-dashboard
Enter fullscreen mode Exit fullscreen mode

ou

git pull origin feature-relatorio
Enter fullscreen mode Exit fullscreen mode

Isso sincroniza sua branch local com as últimas atualizações do repositório remoto.

🔄 Passo 5: Alternar Entre as Branches Sempre Que Precisar

Caso precise voltar para a branch anterior, use:

git checkout feature-login
Enter fullscreen mode Exit fullscreen mode

Se você tinha usado git stash para salvar suas mudanças antes de trocar de branch, recupere-as com:

git stash pop
Enter fullscreen mode Exit fullscreen mode

🏁 Conclusão

Agora você já sabe como alternar entre branches no Git sem precisar clonar o repositório novamente! Esse fluxo ajuda a manter o ambiente organizado e evita trabalho duplicado.

Se tiver dúvidas ou sugestões, deixe nos comentários! 🚀

Image of Timescale

📊 Benchmarking Databases for Real-Time Analytics Applications

Benchmarking Timescale, Clickhouse, Postgres, MySQL, MongoDB, and DuckDB for real-time analytics. Introducing RTABench 🚀

Read full post →

Top comments (0)

Image of Timescale

PostgreSQL for Agentic AI — Build Autonomous Apps on One Stack 1️⃣

pgai turns PostgreSQL into an AI-native database for building RAG pipelines and intelligent agents. Run vector search, embeddings, and LLMs—all in SQL

Build Today

👋 Kindness is contagious

If you found this post useful, consider leaving a ❤️ or a nice comment!

Got it