Minimal Git CI using hooks
Minimal Git CI using hooks
使用 Git Hooks 实现极简 CI
I have a personal server where I am hosting my git repos. Setting up a new git repo is easy: I just run ssh server git init --bare repo. That’s it. Cloning my newly created repo is as simple as git clone server:repo.
我有一台个人服务器用于托管 Git 仓库。创建一个新的 Git 仓库非常简单:只需运行 ssh server git init --bare repo 即可。克隆新创建的仓库也同样简单,只需执行 git clone server:repo。
For some projects I’ve needed a CI, and I looked around for some existing solutions. The CI systems I found are convoluted, yaml-ridden, slow, messy or hard to self-host. Luckily, I do not need many “modern” CI features like complete isolation for my builds or secret management. I just need something that runs some tests, builds a project or moves some files. 对于某些项目,我需要一套 CI(持续集成)系统,于是我调研了一些现有的解决方案。但我发现这些 CI 系统要么过于复杂、充斥着 YAML 配置,要么运行缓慢、混乱不堪,或者难以自托管。幸运的是,我并不需要那些“现代”CI 的复杂功能,比如构建环境的完全隔离或密钥管理。我只需要一个能运行测试、构建项目或移动文件的简单工具。
What I have settled on is a simple CI using git hooks. Specifically, I added a remote post-receive hook, which is a hook that runs whenever I push to a project. It is just a shell-script that I add to the hooks directory in a bare git repository.
最终,我决定使用 Git Hooks 来实现一个简单的 CI。具体来说,我添加了一个远程 post-receive 钩子,它会在我向项目推送代码时自动触发。这本质上就是一个我添加到裸仓库(bare repository)hooks 目录下的 Shell 脚本。
The thing to watch out for with post-receive hooks is if the script fails, the code you push will be rejected. Also, if the script is slow, pushing will take a while. You generally don’t want either. I solved this by using nq, a minimal job queue, to queue up my jobs in the background instead.
使用 post-receive 钩子需要注意:如果脚本执行失败,你推送的代码会被拒绝;此外,如果脚本运行缓慢,推送过程也会变慢。通常我们都不希望出现这些情况。我通过使用 nq(一个极简的任务队列工具)解决了这个问题,它能将任务放入后台排队执行。
The result is quite sleek: my post-receive hook just executes nq, and I can access the logs by running ssh server nqtail -a. The CI runs instantly, and is very easy to set up, so I am happy with the result. If you’d like to set it up for yourself, I created a short tutorial.
最终的效果非常简洁:我的 post-receive 钩子只需执行 nq,我可以通过运行 ssh server nqtail -a 来查看日志。CI 运行即时且易于配置,我对这个结果非常满意。如果你也想尝试,我为此编写了一个简短的教程。
There are many ways you could expand the base I provide in the tutorial: you could sandbox the builds (for example with landdown), use podman to isolate builds from the environment, or use sops to manage secrets. For bazaar-style development, receiving git patches via email should be enough. You can also set up cathedral-style development using git-shell or git http-backend.
你可以在我教程提供的基础之上进行多种扩展:例如使用 landdown 对构建进行沙盒化,使用 podman 将构建与环境隔离,或者使用 sops 来管理密钥。对于“集市模式”(bazaar-style)开发,通过电子邮件接收 Git 补丁就足够了。你也可以使用 git-shell 或 git http-backend 来搭建“大教堂模式”(cathedral-style)的开发环境。
[1] Thanks to Michał Bartoszkiewicz for showing me an even simpler way to create a new repository. [1] 感谢 Michał Bartoszkiewicz 向我展示了创建新仓库的更简便方法。