Git:限制特定分支的范围

Git: Limit the scope of a specific branch

有没有办法强制(至少警告)git 提交给定分支以仅更新回购的一部分?

例如,假设我正在一个特殊的 update-docs 分支上处理文档,并且想确保我不会错误地提交我对代码的另一部分所做的一些更改。我希望 git 拒绝提交或至少警告我对 docs 文件夹范围之外的文件进行了更改...

有办法实现吗?

这可以使用 pre-commit hook

The pre-commit hook is run first, before you even type in a commit message. It’s used to inspect the snapshot that’s about to be committed, to see if you’ve forgotten something, to make sure tests run, or to examine whatever you need to inspect in the code. Exiting non-zero from this hook aborts the commit, although you can bypass it with git commit --no-verify. You can do things like check for code style (run lint or something equivalent), check for trailing whitespace (the default hook does exactly this), or check for appropriate documentation on new methods.

对于您的情况,您可以查看文件列表以查看是否添加了“文档”树之外的任何内容以供提交。

如果您正在与他人协作并希望确保其他人不会将 non-docs 提交到 update-docs 分支,那么您可以安装服务器端 pre-receiveupdate 钩子来验证这一点。