DevOps••10 min read•8 views

Beginner's Git Guide: Working With Branches

Do you often have code conflicts when working as a team? Learn basic Git Branch commands, Git Flow, and version management best practices to keep your repository safe.

Hello! Welcome to the team. I noticed you're already getting used to the basic routines of git add, git commit, and git push. When you're working on a college project or side-project alone, push the code directly to the main branch (usually main or master) does feel fast and practical. No one protested, no code collided.

But, let's talk about the reality in the industrial world. When you work on a professional software team—whether it's building a large-scale POS system, ane-commerceplatform, or anenterpriseapplication—you'll never work alone. There will be frontend developers working on interfaces with React.js, backend engineers optimizing APIs with Go, and DevOps which sets up the deployment. If everyone pushed half-baked code straight to main, our repository would be destroyed in a matter of hours. Applications in production will be full of bugs, and we'll spend more time figuring out whose code is breaking the system than building new features.

This is where Git Branching comes in as a life saver. Consider this article an exclusive mentoring session from me to you. Grab your coffee, open your terminal, and let's dissect how the pros manage their code versions.

1. Branching Philosophy: The "Multiverse" Concept in Code

Before we memorize terminal commands, you have to understand its mindset. Imagine that our Git repository is a timeline (timeline). Our main timeline is named main. The first and most sacred golden rule in the world of software engineering is: The main branch must always be stable, clean, and ready to go.deploy to production at any time.

Then, how do we create new features without dirtying main? We create a branch (branch).

Using branch is like creating a parallel universe (multiverse). When you create a new branch from main, you copy the entire state of the source code at that second into your own isolated workspace. In this parallel universe, you're free to experiment, delete important files, install new libraries, or overhaul the database architecture. Whatever you do in your branch, it won't have the slightest impact on your branch main or branch, until you explicitly merge them (merge).

This isolation is what allows teams consisting of dozens of engineers to work simultaneously (concurrently) on the same code base without killing each other.

2. Basic Git Branch Commands: Everyday Weapon

As an engineer, the terminal is your home. Let's go over the commands you'll be typing hundreds of times every week.

View Existing Branches

To see which branch you are on, use the command:

Bash
git branch
Git will list your local branchs. Active Branch will be marked with a star (*) and is usually green. If you want to see all branch including those on remote servers (such as GitHub/GitLab), add flag -a:

Bash
git branch -a

Create a New Branch

Let's say you are tasked with creating a landing page. You should not write it in main. Create a new branch:

Bash
git branch feature/landing-page
This command only creates a new branch, but does not move you there. You are still at main.

Switching Dimensions (Checkout / Switch)

To move to the branch you just created, in older versions of Git we used checkout:

Bash
git checkout feature/landing-page
However, because checkout has a dual function (it can also be used to restore a changed file), the latest version of Git introduces a more specific and secure command, namely switch:

Bash
git switch feature/landing-page
Pro Tip from a Senior: You can summarize the process of "creating and moving branch" in one efficient command. This is the one I use most often:

Bash
git checkout -b feature/landing-page
# OR in new versions of Git:
git switch -c feature/landing-page

Deleting Branch

Once your feature is complete and merged into main, it will just be visual garbage. Get into the habit of cleaning diligently:

Bash
git branch -d feature/landing-page
If Git refuses to delete because it thinks there are unmerged changes (but you're sure you want to remove them), use the capital D to force delete:

Bash
git branch -D feature/landing-page

3. Real World Scenario 1: Feature Branch Life Cycle

Let's simulate real work. You get a task ticket (for example in Jira or Trello): "Add a student data table component using React and Tailwind CSS."

This is the workflow step by step that you have to follow:

Step 1: Sync with Latest Reality
Before creating a new branch, make sure you start from the most recent main version. Don't let yourself create branch from last month's code.

Bash
git switch main
git pull origin main
Step 2: Create a New Branch
Use descriptive naming. The industry standard format is usually [type]/[feature-name].

Bash
git switch -c feature/student-data-table
Step 3: Writing Code (Parallel Phase)
Now you are in your isolated room. You start by installing new dependencies, writing React components, styling styling with Tailwind, and connecting to the API. After a long day of work, the feature is complete.

Step 4: Commit Periodically
Jangan melakukan satu commit raksasa di akhir minggu. Lakukan commit kecil dan logis.

Bash
git add .
git commit -m "feat: add table structure for student data"
git commit -m "style: implement Tailwind classes for responsive table"
git commit -m "integrate: connect table to backend API endpoints"
Langkah 5: Publish ke Remote Repository
Teman kerjamu (atau saya, sebagai peninjau kodemu) tidak bisa melihat branch lokal di laptopmu. Kamu harus mendorongnya ke server.

Bash
git push -u origin feature/student-data-table
Flag -u (singkatan dari --set-upstream) memberi tahu Git untuk menautkan branch lokalmu dengan branch yang baru dibuat di server. Untuk push selanjutnya di branch ini, kamu cukup mengetik git push.

Langkah 6: Pull Request (PR)
Di perusahaan, kamu tidak melakukan merge sendiri ke main secara diam-diam. Kamu membuka Pull Request di GitHub/GitLab. Di sinilah Code Review terjadi. Saya atau engineer lain akan melihat kodemu, memberikan komentar ("Tolong optimalkan query database-nya", atau "Beri jarak margin yang lebih besar di komponen ini"), dan setelah semuanya disetujui (Approved), barulah branch tersebut di-merge ke main.

4. Skenario Dunia Nyata 2: Bencana di Production (Hotfix)

Skenario ini pasti akan kamu alami. Kamu sedang asyik bereksperimen di branch feature/new-dashboard. Tiba-tiba, manajer proyek panik: "Ada bug kritikal di production! Endpoint API untuk login menggunakan Go mengalami crash!"

Sebagai engineer, kamu harus segera memperbaikinya. Tapi masalahnya, branch kerjamu saat ini sedang berantakan, kodenya setengah jadi dan error. Kamu tidak mungkin membawa kode setengah jadi ini ke main. Apa yang harus dilakukan?

Langkah 1: Selamatkan Pekerjaan Saat Ini (Stash)
Simpan sementara kodemu yang belum selesai tanpa perlu melakukan commit.

Bash
git stash
Sekarang, ruang kerjamu bersih kembali seperti semula.

Langkah 2: Pindah ke Main dan Tarik Data Terbaru

Bash
git switch main
git pull origin main
Langkah 3: Buat Branch Khusus Perbaikan Cepat (Hotfix)
Kita tidak menggunakan awalan feature/, melainkan hotfix/ karena ini darurat.

Bash
git switch -c hotfix/api-login-crash
Langkah 4: Perbaiki Bug
Kamu menelusuri logic Go di backend, menemukan bahwa ada null pointer exception, dan memperbaikinya.

Bash
git add .
git commit -m "fix: resolve null pointer in login handler"
git push -u origin hotfix/api-login-crash
Kamu segera membuat Pull Request, tim langsung me-review, dan di-merge ke main lalu di-deploy ke production. Krisis teratasi!

Langkah 5: Kembali ke Pekerjaan Semula
Setelah dipuji pimpinan, saatnya kembali ke realitasmu yang tertunda.

Bash
git switch feature/new-dashboard
git stash pop
Perintah git stash pop akan mengembalikan kode React setengah jadimu persis seperti sebelum kekacauan terjadi. Kamu bisa melanjutkan pekerjaan seolah-olah tidak terjadi apa-apa. Ajaib, bukan?

5. Standar Industri: Git Flow Branching Model

Di tim berskala besar, sekadar punya main dan branch fitur tidaklah cukup. Kita butuh tata kelola yang lebih ketat. Salah satu model yang paling terkenal adalah Git Flow.

Dalam model Git Flow yang ketat, kita memiliki beberapa "jalur utama" yang hidup selamanya, dan "jalur sementara" yang akan dihapus:

  • master / main: Hanya berisi kode yang sedang berjalan di production. Sangat suci.
  • develop: Cabang tempat berkumpulnya semua fitur baru yang sudah selesai. Ini adalah branch utama untuk proses integrasi.
  • feature/*: Dicabangkan dari develop. Digunakan untuk membuat fitur baru. Setelah selesai, di-merge kembali ke develop.
  • release/*: Ketika develop sudah punya cukup fitur untuk versi baru (misal versi 2.0), kita membuat branch release. Di sini kita hanya melakukan tes akhir dan perbaikan bug kecil, tidak ada penambahan fitur baru. Setelah stabil, di-merge ke main dan develop.
  • hotfix/*: Dicabangkan langsung dari main jika ada darurat (seperti skenario kita sebelumnya), lalu di-merge kembali ke main dan develop.
Memahami peta aliran ini membedakan seorang amatir dengan seorang engineer yang siap bekerja di skala enterprise.

6. Merge vs Rebase: Perdebatan Abadi Para Senior

Ketika kamu ingin menggabungkan branch fiturmu ke main, ada dua cara untuk melakukannya: git merge dan git rebase. Kamu wajib tahu perbedaannya karena menggunakan alat yang salah di waktu yang salah bisa mengundang amarah tim.

Pendekatan "Merge" (Jalur Aman)

Bash
git switch main
git merge feature/landing-page
Merge mengambil kedua ujung branch dan membuat satu commit baru yang menyatukan keduanya (disebut merge commit).

  • Kelebihan: Sangat aman. Sejarah Git tidak diubah. Kamu bisa melihat dengan jelas bahwa pada suatu titik, fitur ini dikerjakan secara paralel lalu digabung.
  • Kekurangan: Jika timmu besar, riwayat commit akan terlihat sangat berantakan dan rumit (seperti jaring laba-laba) dengan banyaknya merge commit.

Pendekatan "Rebase" (Jalur Bersih)

Bash
git switch feature/landing-page
git rebase main
Rebase mengambil seluruh commit di branch fiturmu, dan secara ajaib "menulis ulang" sejarah dengan memindahkannya ke ujung paling depan dari main.

  • Kelebihan: Riwayat commit menjadi garis lurus yang linear dan sangat rapi. Mudah dibaca.
  • Kekurangan: BERBAHAYA JIKA SALAH DIGUNAKAN. Karena rebase mengubah ID sejarah (hash), jika kamu me-rebase branch yang sudah dipakai oleh engineer lain, repositori mereka akan bentrok dan hancur.
Aturan Emas dari Senior: Jangan pernah me-rebase branch yang bersifat publik atau sedang dibagikan dengan orang lain. Gunakan rebase hanya untuk merapikan branch lokalmu sendiri sebelum kamu membuka Pull Request.

7. Conflict! (Merge Conflicts) Jangan Panik

Suatu hari, terminalmu akan berteriak merah: CONFLICT (content): Merge conflict in index.tsx. Jantungmu mungkin berdegup kencang, tapi percayalah, ini hal biasa.

Konflik terjadi jika kamu dan rekan timmu mengubah baris kode yang persis sama di file yang sama, pada branch yang berbeda. Git itu pintar, tapi dia tidak berani menebak kode siapa yang benar. Jadi, dia menyerahkan keputusannya kepadamu.

Saat terjadi konflik, Git akan menyuntikkan marker aneh ke dalam kode aslimu, terlihat seperti ini:

Plaintext
<<<<<<Login
=======
>>>>>>> feature/update-button
  • <<<<<< sampai ======= adalah kodemu saat ini (di branch tujuan).
======= sampai >>>>>>> branch-lain adalah kode dari branch yang sedang mencoba masuk.
Cara Menyelesaikannya:

  1.  
  2. Buka file yang bermasalah di code editor (VS Code biasanya menyorotinya dengan sangat jelas).
  3.  
  4. Hapus marker Git (<<<<<<<, =======, >>>>>>>).
  5.  
  6. Tentukan kode mana yang ingin kamu simpan. Apakah mau kode biru? Kode hijau? Atau gabungan keduanya?
  7.  
  8. Setelah kodenya benar, simpan file.
  9.  
  10. Jalankan git add nama-file.
  11.  
  12. Jalankan git commit untuk menyelesaikan resolusi konflik.
  13.  
Kuncinya adalah komunikasi. Jika kamu tidak yakin baris mana yang benar, panggil rekan timmu dan tanyakan, "Bro, kodenya bentrok nih di fungsi pembayaran, kita pakai logic-mu atau logic-ku?"

8. Pesan Penutup dan Best Practices

Menjadi mahir menggunakan Git Branching tidak diukur dari seberapa banyak perintah rumit yang kamu hafal, tetapi dari seberapa disiplin kamu menjaga kebersihan sistem kerja. Ingat beberapa best practice ini sebelum kamu menutup terminal:

  1.  
  2. Tetap Pendek dan Fokus: Feature branch tidak boleh hidup berbulan-bulan. Usahakan satu branch fokus pada satu fitur atau satu tiket pekerjaan. Semakin lama branch terpisah dari main, semakin besar potensi konflik dan rasa sakit saat merge.
  3.  
  4. Konvensi Penamaan yang Jelas: Jangan buat branch dengan nama fix-bug atau update-UI. Gunakan prefix yang jelas seperti feat/ (fitur baru), fix/ (perbaikan bug), chore/ (tugas pemeliharaan, misal update library), atau docs/ (dokumentasi). Contoh: feat/payment-gateway-integration.
  5.  
  6. Tulis Pesan Commit yang Bermakna: Pesan git commit -m "fix stuff" akan membuat dirimu di masa depan (dan teman timmu) menderita. Gunakan pesan yang menjelaskan apa dan kenapa. Contoh: fix: handle edge case when user balance is zero.
  7.  
Berlatihlah membuat cabang, beralih konteks, dan memecahkan konflik secara mandiri. Lakukan kesalahan di branch lokal, karena di sanalah tempat teraman untuk belajar. Selamat berlatih, Junior. Kopi saya sudah habis, sekarang waktunya kamu yang membuktikan diri di repository kita!
Sigit Wasis Subekti

Sigit Wasis Subekti

Software Engineer & Tech Educator

Software Engineer and Tech Educator sharing insights on web development and software architecture.