SuperAPI AI Directory

git-rebase-workflow

Coding & development

View repository

Updated 10-16 01:33

About this skill

Git Rebase Workflow

Rebase the current feature branch onto the latest target branch (usually master/main), keeping a linear commit history.

Use Cases

  • The feature branch is behind master and needs to synchronize the latest code
  • Keep the commit history clean before submitting an MR/PR
  • Avoid using git merge to generate merge commits

Pre-checks

  1. Confirm the current branch status:

    git branch -v
    git status
    
  2. Confirm the working tree is clean (no uncommitted changes)

Rebase Workflow

1. Fetch the latest code

git fetch origin <目标分支>

2. Perform the Rebase

git rebase origin/<目标分支>

3. Resolve conflicts (if any)

If conflicts occur, handle them as follows:

  1. View conflicting files:

    git status
    
  2. View conflict details:

    grep -n "<<<<<<< HEAD\|=======\|>>>>>>>" <冲突文件>
    
  3. Conflict resolution strategies:

    • Keep the target branch version (ours):

      git checkout --ours <文件路径>
      
    • Keep the current branch version (theirs):

      git checkout --theirs <文件路径>
      
    • Manually edit: Directly modify the conflicting files and remove the conflict markers

  4. Mark the conflict as resolved:

    git add <文件路径>
    
  5. Continue the rebase:

    git rebase --continue
    

    In non-interactive environments or automated execution, avoid rebase --continue hanging after opening the editor. You can temporarily disable the editor:

    GIT_EDITOR=true git rebase --continue
    

    If the command is already hanging due to the editor, first confirm the current process and rebase state, then terminate the stuck editor process; do not abort the rebase or repeatedly run commands that would rewrite the state.

  6. If you need to abort the rebase:

    git rebase --abort
    

4. Push the updates

git push origin <当前分支> --force-with-lease

Note: You must use --force-with-lease to safely force push

Common Issues

Conflict Resolution Principles

  • Version number conflicts: Usually keep the newer version
  • API changes: Analyze based on the specific situation and ask the user for their intent
  • Configuration changes: Assess the impact of the change and choose the appropriate version

Safety Recommendations

  1. Before rebasing, ensure you have a backup or a branch that has already been pushed
  2. Do not rebase public branches (such as master)
  3. Use --force-with-lease instead of --force to push
  4. If uncertain, ask the user to choose first

Complete Example

# 1. 检查状态
git branch -v
git status

# 2. 获取最新代码
git fetch origin master

# 3. 执行 rebase
git rebase origin/master

# 4. 解决冲突(如需要)
# - 查看冲突: git status
# - 保留 ours/theirs 或手动编辑
# - git add <文件>
# - git rebase --continue

# 5. 推送
git push origin feature-branch --force-with-lease