GitHub允许你配置你的存储库,这样用户就不能强制push到master,但是有没有办法完全防止push到master呢?我希望这样做,添加到提交到master的唯一方法是通过GitHub拉请求UI。


当前回答

您可以启用分支限制,并决定允许谁(根据组织的用户和团队)推送。

https://help.github.com/articles/about-branch-restrictions/

«注意:如果“包括管理员”被选中,并且您已经在分支上启用了所需的状态检查,并且它们失败了,那么任何将更改推到基础分支的尝试也将失败,无论用户或团队的权限状态如何。»

其他回答

您可以启用分支限制,并决定允许谁(根据组织的用户和团队)推送。

https://help.github.com/articles/about-branch-restrictions/

«注意:如果“包括管理员”被选中,并且您已经在分支上启用了所需的状态检查,并且它们失败了,那么任何将更改推到基础分支的尝试也将失败,无论用户或团队的权限状态如何。»

如果您正在使用Node,您可以使用husky创建一个预推送验证,以确保不会发生直接推送到master的情况。这样,您仍然可以使用管理员权限来合并pr。我想其他语言对husky也有类似的解决方案。

NPM安装husky——save-dev 在/ .huskyrc.js:

const preventPushToMaster = `branch=\`git symbolic-ref HEAD\`
if [ "$branch" = "refs/heads/master" ]; then
    echo "\\033[31mDirect push to master is not allowed.\\033[0m"
    exit 1
fi`;

module.exports = {
  hooks: {
    'pre-push': preventPushToMaster,
  },
};

当启用状态检查时,直接推送到远程的主服务器将被拒绝,这意味着在远程的主服务器上添加提交的唯一方法是合并GitHub上的拉请求(通过状态检查)。

下面是我对需要状态检查的主分支的实验结果:

在我的PC上的主分支上创建一个提交。 推到遥控器的主人。 出现拒绝消息。最后提交不会推送到远程。

C:\GitRepo\GitHub\TomoyukiAota\photo-location-map [master ↑1]> git push
Enumerating objects: 5, done.
Counting objects: 100% (5/5), done.
Delta compression using up to 12 threads
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 305 bytes | 305.00 KiB/s, done.
Total 3 (delta 2), reused 0 (delta 0)
remote: Resolving deltas: 100% (2/2), completed with 2 local objects.
remote: error: GH006: Protected branch update failed for refs/heads/master.
remote: error: 3 of 3 required status checks are expected.
To https://github.com/TomoyukiAota/photo-location-map.git
 ! [remote rejected] master -> master (protected branch hook declined)
error: failed to push some refs to 'https://github.com/TomoyukiAota/photo-location-map.git'
C:\GitRepo\GitHub\TomoyukiAota\photo-location-map [master ↑1]>

我希望这样做,添加到提交到master的唯一方法是通过GitHub拉请求UI。

我有一个解决方案,可以防止推送到主分支,并且不需要批准或长时间的状态检查来传递拉请求。

诀窍在于创建一个立即通过的状态检查。

在. GitHub /workflows/requirePullRequest.yml中创建以下GitHub Action。

name: require pull request

on:
  pull_request:
    branches:
      - master

jobs:
  job:
    name: require pull request
    runs-on: ubuntu-latest
    steps:
      - run: echo hello

接下来,更新存储库设置以要求通过要求拉取请求状态检查。

如果您希望管理员遵循相同的规则,则必须检查include administrators规则。

这样,GitHub将拒绝所有直接推送到主分支,拉取请求将不会被任何事情延迟。

我需要避免意外地将任何提交推到主分支。 这是一个类似于@christian-chandra的解决方案,但更简单。

转到本地工作副本,然后

$ cd .git/hooks
echo '' > pre-commit
$ chmod +x pre-commit

将此内容添加到文件(预提交)

#!/bin/sh

branch="$(git rev-parse --abbrev-ref HEAD)"

if [ "$branch" = "master" ]; then
  echo "Master Branch commit is blocked"
  exit 1
fi

完成了!