@@ -32,12 +32,13 @@ def main_menu():
3232 print (" [7] 删除本地分支" )
3333 print (" [8] 删除远程分支" )
3434 print (" [10] 创建 Pull Request" )
35+ print (" [11] 清理 Commits (谨慎使用!)" )
3536 print ("\n [0] 退出" )
3637 print ("\n " )
3738
3839 while True :
39- choice = input (" 请选择 (0-10 ): " )
40- if choice in ('0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , '10' ):
40+ choice = input (" 请选择 (0-11 ): " )
41+ if choice in ('0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , '10' , '11' ):
4142 return choice
4243 else :
4344 print ("\n **错误**: 无效的选择,请重新选择." )
@@ -444,6 +445,61 @@ def create_pull_request():
444445
445446 input ("\n 按任意键继续..." )
446447
448+ def clean_commits ():
449+ """清理 Commits (使用 git reset --hard)
450+ **危险操作**: 将会永久丢弃未推送的 commits! 使用前请务必备份!
451+ 命令:git reset --hard HEAD~<number_of_commits>
452+ """
453+ clear_screen ()
454+ print ("=====================================================" )
455+ print (" [11] 清理 Commits (极其危险!)" )
456+ print ("=====================================================" )
457+ print ("\n " )
458+
459+ print (" **警告:此操作会永久丢弃你本地分支上未推送的 commits! 使用前请务必备份你的代码!**" )
460+ print (" 此操作会将 HEAD 重置到指定 commit,并丢弃之后的 commits。" )
461+ print (" 如果你想保留最近的 n 个 commits,将会丢弃后面的 commits。" )
462+
463+ num_commits = input ("\n 要保留最近多少个 commits? (输入数字并回车,输入0则清空所有commit): " )
464+ if not num_commits :
465+ print ("\n **错误**: 必须输入要保留的 commits 数量! 操作已取消。" )
466+ input ("\n 按任意键继续..." )
467+ return
468+
469+ try :
470+ num_commits = int (num_commits )
471+ if num_commits < 0 :
472+ print ("\n **错误**: commit 数量必须是非负整数! 操作已取消。" )
473+ input ("\n 按任意键继续..." )
474+ return
475+ except ValueError :
476+ print ("\n **错误**: 输入的不是有效的整数! 操作已取消。" )
477+ input ("\n 按任意键继续..." )
478+ return
479+
480+ # 再次发出警告
481+ print ("\n **再次警告: 你确定要丢弃最近的 {} 个 commit 之后的所有 commits 吗?此操作不可撤销!**" .format (num_commits ))
482+ confirmation = input (" 输入 'yes' 继续,输入其他任何内容取消操作: " )
483+ if confirmation .lower () != "yes" :
484+ print ("\n 操作已取消。" )
485+ input ("\n 按任意键继续..." )
486+ return
487+
488+ reset_command = f"git reset --hard HEAD~{ num_commits } "
489+
490+ print (f"\n 执行命令: { reset_command } " ) # 显示将要执行的命令
491+
492+ return_code , stdout , stderr = run_git_command (["git" , "reset" , "--hard" , f"HEAD~{ num_commits } " ])
493+
494+ if return_code != 0 :
495+ print ("\n **错误**: reset 失败,请检查您的操作。" )
496+ print (stderr )
497+ else :
498+ print ("\n 成功重置到 HEAD~{}!" .format (num_commits ))
499+ print (" **注意: 你的本地更改可能已经被丢弃,请检查你的工作目录。**" )
500+
501+ input ("\n 按任意键继续..." )
502+
447503
448504if __name__ == "__main__" :
449505 while True :
@@ -472,4 +528,6 @@ def create_pull_request():
472528 elif choice == '8' :
473529 delete_remote_branch ()
474530 elif choice == '10' :
475- create_pull_request () # 新增 PR 功能
531+ create_pull_request () # 新增 PR 功能
532+ elif choice == '11' :
533+ clean_commits ()
0 commit comments