如何安全的在一个已有的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 @ 2024-01-30 22:52  ffl  阅读(22)  评论(0编辑  收藏  举报