如何安全的在一个已有的git分支上,自动化的切换到另外一个分支指定commit

如何安全的在一个已有的git分支上,自动化的切换到另外一个分支指定commit?下面是一种干净的安全的可以自动化的做法:

  1. 清理本地脏数据
git checkout .
git clean -df .
  1. 将 commit 重置到 HEAD
git reset --hard HEAD
  1. 重置子git模块
git submodule foreach --recursive git reset --hard
git submodule update --init --recursive
  1. 删除可能的名字叫做 swap_tmp 的分支
git branch -D swap_tmp
  1. 创建并切换到一个临时分支 swap_tmp 分支
git checkout -b swap_tmp
  1. 删除旧的目标分支,这是因为本地 target_branch 可能已经被污染,删除以免冲突
git branch -D target_branch
  1. 从远程仓库拉取目标分支最新版本
git fetch origin target_branch
  1. 切换到目标分支
git checkout target_branch
  1. 重置到该分支的目标commit
git reset --hard target_commit
  1. 重置子git模块
git submodule foreach --recursive git reset --hard
git submodule update --init --recursive
  1. 使用 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--

posted @   ffl  阅读(34)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示