Git Rebase & Cherry-pick — Git

Git Rebase adalah alternatif merge untuk menggabungkan branch — menghasilkan history yang linear dan bersih. Merge vs Rebase: Merge: Rebase: A─B─C─────M…

Git Rebase adalah alternatif merge untuk menggabungkan branch — menghasilkan history yang linear dan bersih.

Merge vs Rebase:

Merge:                    Rebase:
  A─B─C─────M (main)       A─B─C─D─E (main)
       \   /                     linear!
        D─E (fitur)
<style> .c { fill: #f59e0b; stroke: #92400e; stroke-width: 2; } .m { fill: #10b981; stroke: #064e3b; stroke-width: 2; } .lbl { font: 600 12px ui-sans-serif, system-ui; fill: #111827; text-anchor: middle; } .t { font: 700 13px ui-sans-serif, system-ui; fill: #374151; text-anchor: middle; } .ln { stroke: #6b7280; stroke-width: 2; fill: none; } </style> Merge (Y-shape) M merge commit Rebase (linear) D' E' hash berubah

git rebase main — pindahkan commit branch kamu ke ujung main:

$ git checkout fitur
$ git rebase main
Successfully rebased and updated refs/heads/fitur

Interactive Rebase — editor ampuh untuk merapikan history sebelum PR.

$ git rebase -i HEAD~4

Git membuka editor berisi todo list. Kamu ubah baris pick menjadi perintah lain:

pick   a1b2c3d  tambah form login
squash 4e5f6g7  fix typo di form
reword 8h9i0j1  add validation  ← ganti ke: "feat: validasi email"
edit   2k3l4m5  refactor auth service
drop   6n7o8p9  console.log debug
exec   npm test   ← jalankan test setelah commit sebelumnya

Opsi lengkap:

Kata kunci Fungsi
pick (p) gunakan commit apa adanya
reword (r) pakai commit, ganti pesannya
edit (e) berhenti di commit ini untuk --amend / split
squash (s) gabung ke commit sebelumnya, buka editor pesan gabungan
fixup (f) seperti squash tapi buang pesan commit ini
drop (d) hapus commit
exec (x) jalankan shell command antar commit

Split satu commit jadi dua:

$ git rebase -i HEAD~3      # tandai commit target sebagai "edit"
$ git reset HEAD^            # un-commit, perubahan kembali ke working dir
$ git add file-a && git commit -m "bagian A"
$ git add file-b && git commit -m "bagian B"
$ git rebase --continue

Reorder cukup dengan memindahkan baris di editor. Abort kalau kacau: git rebase --abort.


git cherry-pick <commit> — mengambil satu commit tertentu dari branch lain:

$ git cherry-pick abc1234
[main def5678] fix: perbaiki bug login

Berguna saat kamu butuh satu fix dari branch lain tanpa merge seluruh branch.

Kapan pakai apa?

Situasi Perintah
Gabungkan branch dengan history lengkap git merge
History linear dan bersih git rebase
Ambil satu commit spesifik git cherry-pick
Rapikan commit sebelum PR git rebase -i

⚠️ Aturan emas rebase: Jangan rebase branch yang sudah di-push dan dipakai orang lain. Rebase mengubah history — ini bisa membuat masalah bagi kolaborator.

Yang akan kamu pelajari