批量修改Mercurial hgrc文件:调整default与default-push协议配置
我来分享几个实用的方法,帮你批量修改Mercurial的hgrc配置文件,实现把[paths]段的default地址从HTTP换成SSH,同时保留原HTTP地址作为default-push:
方法1:用sed命令批量处理(适合Linux/macOS)
如果你的所有仓库都集中在某个目录下(比如/path/to/repos),可以用递归的sed命令一次性修改所有.hg/hgrc文件:
find /path/to/repos -name hgrc -type f -exec sed -i.bak '/^\[paths\]$/,/^\[/ { /^default = http/ { h s/default = http:\/\/ourmercurialserver\.de\/apps\//default = ssh:\/\/myusername@ourmercurialserver\.de\/\/path\/to\/repositories\/apps\// p g s/default = /default-push = / } }' {} \;
命令说明:
find ... -exec sed ... {} \;:递归遍历目标目录下所有.hg/hgrc文件,并对每个文件执行sed操作-i.bak:修改文件前自动创建备份(后缀为.bak,确认修改无误后可以批量删除这些备份)/^\[paths\]$/,/^\[/:仅处理[paths]配置段到下一个配置段之间的内容,避免误改其他部分- 匹配到
default = http开头的行后:h:把当前行暂存到sed的临时空间- 第一处替换:将原HTTP地址替换为目标SSH地址
p:输出修改后的default行g:恢复暂存的原HTTP行- 第二处替换:将
default =改为default-push =,输出这一行
通用化调整:
如果你的仓库路径各不相同,可以用正则匹配更灵活的地址:
s/default = http:\/\/ourmercurialserver\.de\/\(.*\)/default = ssh:\/\/myusername@ourmercurialserver\.de\/\/path\/to\/repositories\/\1/
这样不管原HTTP地址的后缀是什么,都会自动替换成对应的SSH路径。
方法2:Python脚本(跨平台,适合复杂场景)
如果你需要跨Windows/Linux/macOS使用,或者要处理更复杂的配置逻辑,可以用Python脚本实现:
import os import re # 配置参数,根据你的实际情况修改 REPO_BASE = "/path/to/repos" # 你的仓库根目录 OLD_HTTP_PREFIX = "http://ourmercurialserver.de/" NEW_SSH_PREFIX = "ssh://myusername@ourmercurialserver.de//path/to/repositories/" def update_hgrc(hgrc_path): # 读取原文件内容 with open(hgrc_path, 'r') as f: lines = f.readlines() in_paths_section = False modified = False new_lines = [] for line in lines: stripped_line = line.strip() # 进入[paths]段 if stripped_line == "[paths]": in_paths_section = True new_lines.append(line) # 离开[paths]段(遇到下一个配置段) elif stripped_line.startswith("[") and in_paths_section: in_paths_section = False new_lines.append(line) # 在[paths]段内匹配default的HTTP地址 elif in_paths_section and stripped_line.startswith("default = http"): # 生成default-push行 default_push_line = line.replace("default = ", "default-push = ") # 生成新的default SSH行 default_line = line.replace(OLD_HTTP_PREFIX, NEW_SSH_PREFIX) new_lines.append(default_line) new_lines.append(default_push_line) modified = True else: new_lines.append(line) # 如果有修改,备份原文件并写入新内容 if modified: backup_path = f"{hgrc_path}.bak" os.rename(hgrc_path, backup_path) with open(hgrc_path, 'w') as f: f.writelines(new_lines) print(f"已更新: {hgrc_path},备份文件: {backup_path}") else: print(f"无需修改: {hgrc_path}") # 递归遍历所有仓库的.hg/hgrc文件 for root, dirs, files in os.walk(REPO_BASE): if ".hg" in dirs: hgrc_path = os.path.join(root, ".hg", "hgrc") if os.path.exists(hgrc_path): update_hgrc(hgrc_path)
验证修改结果
修改完成后,随便进入一个仓库,运行以下命令检查配置是否正确:
hg paths
正常情况下会输出类似:
default = ssh://myusername@ourmercurialserver.de//path/to/repositories/apps/ default-push = http://ourmercurialserver.de/apps/
内容的提问来源于stack exchange,提问作者user8252938
相关产品推荐
相关产品推荐

