如何安全的在一个已有的git分支上,自动化的切换到另外一个分支指定commit
如何安全的在一个已有的git分支上,自动化的切换到另外一个分支指定commit?下面是一种干净的安全的可以自动化的做法:
- 清理本地脏数据
git checkout .
git clean -df .
- 将 commit 重置到 HEAD
git reset --hard HEAD
- 重置子git模块
git submodule foreach --recursive git reset --hard
git submodule update --init --recursive
- 删除可能的名字叫做 swap_tmp 的分支
git branch -D swap_tmp
- 创建并切换到一个临时分支 swap_tmp 分支
git checkout -b swap_tmp
- 删除旧的目标分支,这是因为本地 target_branch 可能已经被污染,删除以免冲突
git branch -D target_branch
- 从远程仓库拉取目标分支最新版本
git fetch origin target_branch
- 切换到目标分支
git checkout target_branch
- 重置到该分支的目标commit
git reset --hard target_commit
- 重置子git模块
git submodule foreach --recursive git reset --hard
git submodule update --init --recursive
- 使用 Python 串起来自动化:
import os
def reset_to_git_branch_and_commit(repo_dir, target_branch, target_commit):
git_cmds = [
f'cd {repo_dir}',
f'git checkout .',
f'git clean -df .',
f'git reset --hard HEAD',
f'git submodule foreach --recursive git reset --hard',
f'git submodule update --init --recursive',
f'git branch -D swap_tmp',
f'git checkout -b swap_tmp',
f'git branch -D {target_branch}',
f'git fetch origin {target_branch}',
f'git checkout {target_branch}',
f'git reset --hard {target_commit}',
f'git submodule foreach --recursive git reset --hard',
f'git submodule update --init --recursive',
]
for git_cmd in git_cmds:
ret = os.system(git_cmd)
print(f"run: {git_cmd}, ret:{ret}")
--end--
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix