我想保留一个仓库中以特定字符串为前缀的分支,还想按照commit时间保留同一前缀的指定数量的分支,删除分支的脚本如下:
#!/usr/bin/env python
#-*- coding:utf8 -*-
#coding:utf-8
import os
user_prefix = ["swh", "hzz", "sxwang", "junfeng", "fsh", "sxl", "chenwei", "weiyang", "chiyang", "smj", "hyc", "zmh", "hsy", "xsk", "zzh","dasituer", "kjq", "shuolin", "zc", "lll", "lhy"]
reserve_prefix = ["oushudb", "hawq"]
branch_save_num = 2
output_file = '/tmp/delete_cmd'
if __name__ == '__main__':
fp = open(output_file, "w")
if os.system("git fetch --prune"):
print("Should in git repository.")
lines = []
# get all branch to be deleted belonging to users
for user in user_prefix:
cmd = "git for-each-ref refs/remotes/origin/{}* --format=\'%(committerdate:short) %09 %(refname:short)\' | sort -k1,1r".format(user)
branchs = os.popen(cmd)
delete_stat = "git push origin :"
num = 0
for branch in branchs:
if len(branch.strip("\n")) == 0:
continue
if num >= branch_save_num:
lines.append(delete_stat + branch.split("\t")[1].split("/")[1])
num += 1
# get all branch not in user list and reserve list
filter = "HEAD\|"
for user in user_prefix:
filter += user + "\|"
for reserve in reserve_prefix:
filter += reserve + "\|"
filter = filter[:len(filter)-2]
cmd = "git for-each-ref refs/remotes/origin/ --format=\'%(committerdate:short) %09 %(refname:short)\' | grep -v \'{}\' | sort -k1,1".format(filter)
branchs = os.popen(cmd)
for branch in branchs:
lines.append(delete_stat + branch.split("\t")[1][8:])
fp.writelines(lines)
fp.close()
标签:git,前缀,仓库,cmd,filter,prefix,user,branch
From: https://www.cnblogs.com/huasyuan/p/16750591.html