Git

計算 Current Branch Behind Dev Branch

git rev-list --left-right --count dev...HEAD

Output:

<behind_count> <ahead_count>

Example(當前分支落後 dev 分支 5 個提交,超前 2 個提交):

5 2

Checkout to Specific Branch

方法一:

git checkout <hash> # detached head
git branch -D feature/xxx # delete local branch
git checkout -b feature/xxx # create new local branch
git push -f origin feature/xxx # push remote

方法二:

git checkout feature/xxx
git reset --hard <commit_hash_before_dev_pull>  # return to specific commit
git push -f origin feature/xxx

方法三:

git checkout feature/xxx
git revert <commit_hash1> <commit_hash2> ...     # 逐個回退從 dev 分支拉取的變更
git push origin feature/xxx                      # 推送回退結果

reset vs revert

特性git reset --hardgit revert
變更歷史處理丟棄所有指定提交之後的歷史保留所有歷史,並新增反向提交
操作結果將分支回到某個指定的提交狀態創建新的反向提交,對應回退指定的提交
提交保留不保留之後的提交,會完全移除這些提交保留所有提交,只是通過反向提交撤銷變更
衝突處理丟棄所有之後的更改,因此可能不會產生衝突需要解決衝突,特別是在反向提交時
提交軌跡可追溯性不可追溯,歷史提交被丟棄可追溯,因為反向提交保留了完整的提交歷史

Undo Last Commit

保留變更在 working directory:

git reset --soft HEAD~1

reflog

git reflog show
git reflog show $(git branch --show-current)

log

git log --oneline
git log --oneline --graph --all

清理不需要的提交

git checkout feature/a-123
git rebase -i HEAD~N

將不要的一行 pick 改為 drop,然後:

git push origin feature/a-123 --force

模擬推送

git push --force --dry-run

Force Delete Branch

git branch -D branch_name

Compare Branches Code Lines

git diff --shortstat <base-commit> feature-branch

Worktree

適用場景:需要暫時切換處理 hotfix,但不想 stash 當前工作。

### 確認目前位置 ```bash git branch # feature/l-001 ``` ### 從 main 建立 hotfix worktree ```bash git worktree add -b hotfix-123 .worktrees/hotfix-123 main ``` 或: ```bash git worktree add .worktrees/hotfix-123 main ``` ```bash git worktree list /workspace/git-playground 0e439b8 [feature/l-001] /workspace/git-playground/.worktrees/hotfix-123 0e439b8 [main] ``` ### 切換到 hotfix 目錄 ```bash cd .worktrees/hotfix-123 ``` 如果使用第二種方式,需要額外 checkout: ```bash git checkout -b hotfix-123 ``` ### 在 hotfix branch 修復問題 ```bash # 修改檔案 git add . git commit -m "fix: issue description" ``` ### 推送並合併 hotfix ```bash git push origin hotfix-123 # 在遠端完成 PR & Merge 到 main ``` ### 切回專案根目錄 ```bash cd ../.. ``` ### 清理 hotfix worktree ```bash git worktree remove .worktrees/hotfix-123 git fetch git pull origin main ``` ### 繼續原本 feature branch 的開發工作

Demo

git worktree add ../worktree/feature/ABC-12345 prod.1.112.4 -b feature/ABC-12345

Revert / Reset / Rebase

git revert HEAD

git reset HEAD
git reflog
# 三種模式:mixed, soft, hard

git restore .

版本切換

git checkout <commit_number>

git checkout main

git checkout HEAD~   # 回到 HEAD 前一個版本
git checkout HEAD~2  # 回到 HEAD 前兩個版本