gitlab仓库地址变更,批量更新本地配置的远程仓库脚本

发布时间 2023-06-14 16:35:26作者: 暗an天使
import subprocess
from pathlib import Path


def replace(old_url):
old_host = 'http://AAAA:8081'
new_host = 'http://BBBB:8081'
return old_url.replace(old_host, new_host)


paths = list(Path('D:\\workspacenew').glob('*'))
length = len(paths)
for index, cwd in enumerate(paths, start=1):
if cwd.is_dir():
process = subprocess.run('git remote -v', stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
cwd=cwd) # 获取远端URL
result = process.stdout.decode()
print(result)
print("===" * 15)
if result.startswith('fatal'):
print(f'({index}/{length}) pass {cwd}')
continue # 跳过错误
old_url = result.splitlines()[1].split()[1]
new_url = replace(old_url)
print("urls are as follows:")
print(old_url, new_url)

status_process = subprocess.run(f'git remote set-url origin {new_url}', stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=cwd) # 修改远端URL
status_result = status_process.stdout.decode()
print("Status result is: ", status_result)
print(f'({index}/{length}) {old_url.ljust(80)} : {new_url.rjust(80)}') # 输出进度