Skip to content

Instantly share code, notes, and snippets.

@hyper0x
Created January 24, 2026 03:10
Show Gist options
  • Select an option

  • Save hyper0x/209f534de44ca809eb44d99fcc158f53 to your computer and use it in GitHub Desktop.

Select an option

Save hyper0x/209f534de44ca809eb44d99fcc158f53 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import os
import subprocess
import sys
# Homebrew 镜像配置脚本
# 支持镜像:tsinghua(清华)、ustc(中科大)、aliyun(阿里云)、official(官方)
MIRROR_CHOICE = "tsinghua" # 只需改这里切换镜像
# 镜像配置表
MIRRORS = {
"tsinghua": {
"brew": "https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/brew.git",
"core": "https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/homebrew-core.git",
"cask": "https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/homebrew-cask.git",
"bottles": "https://mirrors.tuna.tsinghua.edu.cn/homebrew-bottles"
},
"ustc": {
"brew": "https://mirrors.ustc.edu.cn/git/homebrew/brew.git",
"core": "https://mirrors.ustc.edu.cn/git/homebrew/homebrew-core.git",
"cask": "https://mirrors.ustc.edu.cn/git/homebrew/homebrew-cask.git",
"bottles": "https://mirrors.ustc.edu.cn/homebrew-bottles"
},
"aliyun": {
"brew": "https://mirrors.aliyun.com/homebrew/brew.git",
"core": "https://mirrors.aliyun.com/homebrew/homebrew-core.git",
"cask": "https://mirrors.aliyun.com/homebrew/homebrew-cask.git",
"bottles": "https://mirrors.aliyun.com/homebrew-bottles"
},
"official": {
"brew": "https://github.com/Homebrew/brew.git",
"core": "https://github.com/Homebrew/homebrew-core.git",
"cask": "https://github.com/Homebrew/homebrew-cask.git",
"bottles": ""
}
}
# 校验镜像选择是否合法
if MIRROR_CHOICE not in MIRRORS:
print(f"❌ 无效的镜像选择!可选:{', '.join(MIRRORS.keys())}")
sys.exit(1)
current_mirror = MIRRORS[MIRROR_CHOICE]
# 封装系统命令执行函数
def run_cmd(cmd):
"""
执行系统命令,返回 (输出内容, 是否执行成功)
:param cmd: 要执行的命令字符串
:return: (stdout_str, is_success)
"""
result = subprocess.run(
cmd,
shell=True,
capture_output=True,
text=True,
encoding="utf-8"
)
stdout = result.stdout.strip()
return stdout, result.returncode == 0
# 生成zsh环境变量配置文件(~/.brew_mirrors.sh)
config_path = os.path.expanduser("~/.brew_mirrors.sh")
# 处理bottles配置(空值则unset,否则export)
if not current_mirror["bottles"]:
bottles_config = "unset HOMEBREW_BOTTLE_DOMAIN"
else:
bottles_config = f'export HOMEBREW_BOTTLE_DOMAIN="{current_mirror["bottles"]}"'
# 拼接配置文件内容
config_content = f'''#!/bin/zsh
# 由Python脚本(brew_mirror.py)自动生成的Homebrew镜像配置
export HOMEBREW_BREW_GIT_REMOTE="{current_mirror["brew"]}"
export HOMEBREW_CORE_GIT_REMOTE="{current_mirror["core"]}"
export HOMEBREW_CASK_GIT_REMOTE="{current_mirror["cask"]}"
{bottles_config}
# 可选优化项
export HOMEBREW_NO_ANALYTICS=1 # 禁用数据分析(小幅提速)
export HOMEBREW_NO_INSTALL_FROM_API=1 # 关闭API安装模式,兼容镜像
export HOMEBREW_SKIP_GPG_VERIFY=0 # 跳过GPG签名验证(提速)
export HOMEBREW_AUTO_UPDATE_SECS=43200 # 每12小时自动更新一次
'''
# 写入配置文件(覆盖原有文件)
with open(config_path, "w", encoding="utf-8") as f:
f.write(config_content)
print(f"✅ 已生成镜像配置文件:{config_path}")
# 第二步:强制修改Homebrew仓库的remote
def set_brew_remote(repo_name, remote_url):
"""
修改指定Homebrew仓库的remote地址
:param repo_name: 仓库名(如homebrew/core,空字符串表示brew本体)
:param remote_url: 镜像远程地址
"""
# 获取仓库路径
repo_path, is_success = run_cmd(f"brew --repository {repo_name}")
if is_success and repo_path:
# 执行git remote set-url命令
run_cmd(f"git -C {repo_path} remote set-url origin {remote_url}")
# 处理repo_name为空的情况(brew本体)
display_name = f"“{repo_name}”" if repo_name else "brew本体"
print(f"✅ 已设置{display_name}仓库remote:{remote_url}")
else:
print(f"⚠️ “{repo_name}”仓库路径不存在,跳过设置")
# 设置核心仓库remote
set_brew_remote("homebrew/core", current_mirror["core"])
set_brew_remote("homebrew/cask", current_mirror["cask"])
set_brew_remote("", current_mirror["brew"]) # brew本体仓库无repo_name,传空
# 第三步:将配置文件引入.zshrc(确保永久生效,避免重复添加)
zshrc_path = os.path.expanduser("~/.zshrc")
source_line = f"source {config_path}"
# 检查.zshrc是否已包含该source行
try:
with open(zshrc_path, "r", encoding="utf-8") as f:
zshrc_content = f.read()
if source_line not in zshrc_content:
# 追加到.zshrc末尾
with open(zshrc_path, "a", encoding="utf-8") as f:
f.write(f"\n{source_line}\n")
print("✅ 已将配置文件引入 ~/.zshrc")
except FileNotFoundError:
# 处理.zshrc不存在的情况
print(f"⚠️ ~/.zshrc 文件不存在,跳过配置引入")
# 第四步:输出验证信息
print("\n🎉 镜像配置完成!执行以下命令生效:")
print("source ~/.zshrc && brew update-reset && brew cleanup")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment