开发自定义 Homebrew 程序包
本文主要基于 《Homebrew Documentation - Formula Cookbook》 进行实践后记录。
实践环境
| 项目 | 说明 |
|---|---|
| macOS | Catalina 10.15.7 (19H524) |
| brew | 3.0.4-50-ga930e2b |
术语
| 术语 | 描述 | 示例 |
|---|---|---|
| Formula | 程序包的定义文件 | /usr/local/Homebrew/Library/Taps/homebrew/homebrew-core/Formula/foo.rb |
| Keg | 程序包的安装路径 | /usr/local/Cellar/foo/0.1 |
| opt prefix | 当前所使用版本的符号链接 | /usr/local/opt/foo |
| Cellar | 所有 Kegs 的安装目录 | /usr/local/Cellar |
| Tap | Formula 的 Git 仓库目录 | /usr/local/Homebrew/Library/Taps/homebrew/homebrew-core |
| Bottle | 用于替代(从源码编译)的(预编译好的二进制文件压缩包) | qt-4.8.4.catalina.bottle.tar.gz |
| Cask | Homebrew 扩展,用于安装 macOS 本地应用 | /Applications/MacDown.app/Contents/SharedSupport/bin/macdown... |
| Brew Bundle | Homebrew 扩展,用于描述依赖关系 | brew 'myservice', restart_service: true |
基本介绍
Homebrew 使用 Git 下载更新以及提交更新。
程序包是根据 Formula 进行安装的。而 Formula 都被存放在 /usr/local/Homebrew/Library/Taps/homebrew/homebrew-core/Formula 目录中。
使用 brew edit 命令来查看/编辑 Formula。例如:brew edit etl、brew edit git。
基础指令
在开始之前,先运行 brew update 将 Homebrew 安装目录变成 Git 仓库。
抓取源代码压缩包
这里,我们在 github 上新建一个 homebrew-helloworld 项目,如下:

main.go:

go.mod:

创建 github tag 并拷贝源代码压缩包地址:

运行 brew create --set-name zhb127 URL 新建一个名为 zhb127 的 Formula:
brew create --set-name zhb127 https://github.com/zhb127/homebrew-helloworld/archive/0.1.tar.gz运行以上命令,将创建 /usr/local/Homebrew/Library/Taps/homebrew/homebrew-core/Formula/zhb127.rb 并自动使用默认编辑器打开,内容如下:
# Documentation: https://docs.brew.sh/Formula-Cookbook
# https://rubydoc.brew.sh/Formula
# PLEASE REMOVE ALL GENERATED COMMENTS BEFORE SUBMITTING YOUR PULL REQUEST!
class Zhb127 < Formula
desc ""
homepage ""
url "https://github.com/zhb127/homebrew-helloworld/archive/0.1.tar.gz"
sha256 "dd26eb15512fc5418e9a522746e87151f37da4bdae60dc5483aba10393d125c7"
license ""
# depends_on "cmake" => :build
def install
# ENV.deparallelize # if your formula fails when building in parallel
# Remove unrecognized options if warned by configure
system "./configure", "--disable-debug",
"--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{prefix}"
# system "cmake", ".", *std_cmake_args
end
test do
# `test do` will create, run in and delete a temporary directory.
#
# This test will fail and we won't accept that! For Homebrew/homebrew-core
# this will need to be a test that verifies the functionality of the
# software. Run the test with `brew test zhb127`. Options passed
# to `brew install` such as `--HEAD` also need to be provided to `brew test`.
#
# The installed folder is not in the path, so use the entire path to any
# executables being tested: `system "#{bin}/program", "do", "something"`.
system "false"
end
end修改 Formula 定义文件,如下:

检查构建系统

根据提示,使用 brew 安装命令(从源码构建):

运行安装后的命令 zhb127:

至此,完成自定义 Homebrew 程序包开发。
关于 Homebrew 程序包的其他内容介绍,详见:https://docs.brew.sh/Formula-Cookbook。