Mahir Git dalam 30 Hari

Hari 30: Berkongsi Petua Operasi Git yang Berguna daripada Kerja

Selepas 29 hari mempelajari Git, artikel terakhir ini berkongsi petua dan helah praktikal yang menjadikan operasi Git harian lebih cekap dan menyeronokkan.

Petua Konfigurasi

Konfigurasi Global

# Set default editor
git config --global core.editor "code --wait"

# Enable color UI
git config --global color.ui auto

# Set default branch name
git config --global init.defaultBranch main

# Auto-correct typos
git config --global help.autocorrect 1

# Cache credentials
git config --global credential.helper cache --timeout=3600

Alias Berguna

# Short status
git config --global alias.st status

# Short log
git config --global alias.ll "log --oneline --graph --all --decorate"

# Last commit
git config --global alias.last "log -1 HEAD"

# Undo last commit (keep changes)
git config --global alias.undo "reset HEAD~1 --mixed"

# Amend without editing message
git config --global alias.amend "commit --amend --no-edit"

# List branches sorted by last modified
git config --global alias.br "branch --sort=-committerdate"

# Show changed files in last commit
git config --global alias.dl "diff --name-only HEAD~1"

# Search commit messages
git config --global alias.search "log --all --grep"

# Nuke branch (force delete)
git config --global alias.nuke "branch -D"

Petua Produktiviti

# Jump to repository root
alias gr='cd $(git rev-parse --show-toplevel)'

# Open repo in browser
alias browse='git remote get-url origin | xargs open'

Carian

# Find file in history
git log --all --full-history -- "**/filename.*"

# Search in all commits
git log -S "search term" --source --all

# Find who changed a line
git blame filename

# Prettier blame
git blame -w -C -C -L 10,20 filename

Pembersihan

# Delete merged branches
git branch --merged main | grep -v "^*\|main" | xargs git branch -d

# Delete all local branches except main
git branch | grep -v "main" | xargs git branch -D

# Remove untracked files (dry run first!)
git clean -n
git clean -fd

# Prune remote branches
git fetch --prune

Perintah Menjimatkan Masa

Commit Pantas

# Add and commit in one step
git commit -am "Quick fix"

# Add, commit, and push
alias gcp='git commit -am "$1" && git push'

Pengurusan Cabang

# Create and checkout branch in one step
git checkout -b feature/new-feature

# Switch to previous branch
git checkout -

# Show branches with last commit
git branch -v

# Show remote tracking branches
git branch -vv

Helah Stash

# Stash with message
git stash push -m "Work in progress on feature X"

# List stashes with details
git stash list --pretty=format:"%C(yellow)%gd%C(reset) - %C(bold)%s%C(reset)"

# Apply and drop in one step
git stash pop

# Apply specific stash
git stash apply stash@{2}

# Stash including untracked files
git stash -u

Teknik Lanjutan

Cherry-Pick Berbilang Commit

# Cherry-pick a range of commits
git cherry-pick A^..B

# Cherry-pick from another branch
git cherry-pick feature-branch~3..feature-branch

Pementasan Interaktif (Interactive Staging)

# Stage parts of a file
git add -p filename

# Interactive add
git add -i

Petua Diff

# Word diff instead of line diff
git diff --word-diff

# Ignore whitespace changes
git diff -w

# Show diff of staged changes
git diff --staged

# Diff between branches
git diff main..feature-branch

# Diff specific file between commits
git diff commit1 commit2 -- filename

Pemformatan Log

# Pretty log
git log --pretty=format:"%C(yellow)%h%C(reset) - %C(green)(%cr)%C(reset) %s %C(blue)<%an>%C(reset)"

# Log with graph
git log --graph --abbrev-commit --decorate --all

# Show files changed per commit
git log --stat

# Show patches
git log -p

Penyelesaian Masalah

Buat Asal Kesilapan

# Undo last commit (keep changes)
git reset --soft HEAD~1

# Undo last commit (discard changes)
git reset --hard HEAD~1

# Undo all uncommitted changes
git checkout .

# Unstage file
git reset HEAD filename

# Restore file from HEAD
git checkout HEAD -- filename

Pemulihan

# Find lost commits
git reflog

# Recover deleted branch
git branch branch-name <commit-hash>

# Find dangling commits
git fsck --lost-found

Nyahpepijat (Debug)

# See who introduced a bug (binary search)
git bisect start
git bisect bad  # Current version is bad
git bisect good <commit>  # Known good commit
# Git checks out middle commit
# Test and mark as good or bad
git bisect good/bad
# Repeat until found
git bisect reset

# Blame with line range
git blame -L 10,20 filename

# Show commit that introduced line
git log -S "function name" --source --all

Pengoptimuman Aliran Kerja

Hook Pra-Commit (Pre-Commit Hooks)

Cipta .git/hooks/pre-commit:

#!/bin/bash

# Run tests before commit
npm test
if [ $? -ne 0 ]; then
    echo "Tests failed, commit aborted"
    exit 1
fi

Templat Mesej Commit

Cipta ~/.git-commit-template:

# <type>: <subject>
#
# <body>
#
# <footer>
#
# Types: feat, fix, docs, style, refactor, test, chore

Tetapkan sebagai lalai:

git config --global commit.template ~/.git-commit-template

Petua Integrasi

Git dengan VS Code

# Open current repo in VS Code
code .

# Open merge tool
git mergetool --tool=vscode

Git dengan Vim

# Set Vim as default editor
git config --global core.editor vim

# Vim as diff tool
git config --global diff.tool vimdiff
git config --global difftool.prompt false

Petua Prestasi

Repositori Besar

# Shallow clone (faster)
git clone --depth 1 https://github.com/user/repo.git

# Partial clone (Git 2.22+)
git clone --filter=blob:none https://github.com/user/repo.git

# Sparse checkout (specific folders)
git sparse-checkout init
git sparse-checkout set folder1 folder2

Status yang Lebih Pantas

# Use untracked cache
git config core.untrackedCache true

# Use file system monitor
git config core.fsmonitor true

Petua Keselamatan

Tandatangan GPG

# Generate GPG key
gpg --gen-key

# List keys
gpg --list-secret-keys --keyid-format LONG

# Configure Git
git config --global user.signingkey <key-id>
git config --global commit.gpgsign true

# Sign commits
git commit -S -m "Signed commit"

Kelayakan (Credentials)

# Never store passwords in config
# Use credential helpers instead

# SSH for authentication (recommended)
ssh-keygen -t ed25519 -C "email@example.com"

# Use HTTPS with token
# Generate personal access token on GitHub
# Use it as password

Kebijaksanaan Terakhir

Senarai Semak Amalan Terbaik

  • Commit dengan kerap, push dengan kerap
  • Tulis mesej commit yang bermakna
  • Kekalkan commit atomik dan fokus
  • Buat cabang untuk setiap ciri/pembetulan
  • Semak kod anda sendiri sebelum PR
  • Pull sebelum push
  • Jangan sekali-kali force push ke cabang yang dikongsi
  • Gunakan .gitignore dengan betul
  • Tag keluaran
  • Dokumenkan aliran kerja anda

Apabila Keadaan Menjadi Salah

  1. Jangan panik: Git jarang kehilangan data
  2. Semak reflog: Ia adalah jaringan keselamatan anda
  3. Buat sandaran: Buat cabang sebelum bereksperimen
  4. Minta bantuan: Komuniti Git sangat membantu
  5. Belajar daripada kesilapan: Setiap ralat mengajar sesuatu

Tahniah!

Anda telah melengkapkan 30 hari penguasaan Git! Anda telah mempelajari:

  • Asas dan seni bina Git
  • Strategi pencabangan dan cantuman
  • Manipulasi sejarah (reset, rebase, amend)
  • Aliran kerja jauh dan kerjasama
  • Aliran kerja GitHub dan amalan terbaik
  • Petua lanjutan dan penyelesaian masalah

Teruskan Belajar

  • Berlatih dengan kerap
  • Menyumbang kepada sumber terbuka
  • Belajar daripada sejarah Git orang lain
  • Terokai ciri lanjutan
  • Ikuti perkembangan keluaran Git

Kata-kata Terakhir

Git ialah alat yang berkuasa yang menjadi semakin berharga semakin banyak anda menggunakannya. Jangan cuba mengingati semuanya - tandakan panduan ini dan rujuk kembali apabila diperlukan. Perkara yang paling penting ialah terus berlatih dan tidak takut untuk bereksperimen (dalam persekitaran yang selamat).

Selamat berkod, dan semoga cantuman anda sentiasa bebas konflik!

Pautan Rujukan



Terima Kasih!

Terima kasih kerana mengikuti perjalanan Git 30 hari ini. Terus berlatih, terus belajar, dan ingat - setiap pakar Git juga pernah menjadi pemula!