Git
計算 Current Branch Behind Dev Branch
git rev-list --left-right --count dev...HEADOutput:
<behind_count> <ahead_count>Example(當前分支落後 dev 分支 5 個提交,超前 2 個提交):
5 2Checkout 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 --hard | git revert |
|---|---|---|
| 變更歷史處理 | 丟棄所有指定提交之後的歷史 | 保留所有歷史,並新增反向提交 |
| 操作結果 | 將分支回到某個指定的提交狀態 | 創建新的反向提交,對應回退指定的提交 |
| 提交保留 | 不保留之後的提交,會完全移除這些提交 | 保留所有提交,只是通過反向提交撤銷變更 |
| 衝突處理 | 丟棄所有之後的更改,因此可能不會產生衝突 | 需要解決衝突,特別是在反向提交時 |
| 提交軌跡可追溯性 | 不可追溯,歷史提交被丟棄 | 可追溯,因為反向提交保留了完整的提交歷史 |
Undo Last Commit
保留變更在 working directory:
git reset --soft HEAD~1reflog
git reflog showgit reflog show $(git branch --show-current)log
git log --onelinegit 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-runForce Delete Branch
git branch -D branch_nameCompare Branches Code Lines
git diff --shortstat <base-commit> feature-branchWorktree
適用場景:需要暫時切換處理 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-12345Revert / 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 前兩個版本