2022年07月06日 - Tomo Masakura    

メインブランチへの誤プッシュを防ぐ

役割がMaintainerでもメインブランチへの誤プッシュを防ぎます。

機能ブランチにコミットしなければいけないところを、誤ってメインブランチにコミットした経験はありませんか?それだけならまだしも、GitLabにプッシュしてから気がついたことはありませんか?

メインブランチへの誤プッシュは、メインブランチにレビューされていないかつ不完全なソースコードが含まれてしまいますので、他の開発者に迷惑となります。

GitLab標準では役割Developerのメンバーはメインブランチにプッシュできません。開発者として参加しているプロジェクトでは、誤って機能ブランチの修正をメインブランチにコミットしたとしても、GitLabにプッシュした段階で拒否されます。

残念ながら、役割Maintainerのメンバーのメインブランチへの誤プッシュはできてしまうわけです。

これを防ぐのは簡単で、GitLabプロジェクトの左側のサイドメニューの設定->リポジトリ->Protected branchesより保護ブランチのプッシュを許可No one(誰もできない)にするだけです。

保護ブランチの設定

試しにメインブランチにプッシュしてみると、阻止してくれます。

$ git push
Enumerating objects: 5, done.
Counting objects: 100% (5/5), done.
Delta compression using up to 16 threads
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 294 bytes | 294.00 KiB/s, done.
Total 3 (delta 2), reused 0 (delta 0)
remote: GitLab: You are not allowed to push code to protected branches on this project.
To gitlab.com:/masakura/asynchronous.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'git@gitlab.com:/masakura/asynchronous.git'

横着して、ブランチを切り替えるのは後からでもいいかあとやってしまうのが悪いんですけどね。

間違えたローカルリポジトリを何とかする

GitLabへのプッシュは阻止できました。しかし、機能ブランチにコミットすべき内容はローカルのGitリポジトリのメインブランチにコミットされたままです。これを何とかする方法を紹介します。

機能ブランチ側にコミットしたつもりでした。

機能ブランチへの切り替えを忘れてメインブランチにコミットしてしまいました。

今はメインブランチにいます。

$ git status
ブランチ main
このブランチは 'origin/main' よりも2コミット進んでいます。
  (use "git push" to publish your local commits)

nothing to commit, working tree clean

GitLabからマージリクエストの機能ブランチのみをプルして切り替えます。

$ git pull origin 1-branch2:1-branch2
From gitlab.com:/masakura/mistake-commit
 * [new branch]      1-branch2  -> 1-branch2
 * [new branch]      1-branch2  -> origin/1-branch2
Already up to date.

$ git checkout 1-branch2
Switched to branch '1-branch2'

メインブランチにコミットしてしまった修正を取り込みます。

$ git merge main
Updating e999941..6e67226
Fast-forward
 README.md | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

修正をGitLabにプッシュします。

$ git push -u origin 1-branch2
Enumerating objects: 8, done.
Counting objects: 100% (8/8), done.
Delta compression using up to 16 threads
Compressing objects: 100% (4/4), done.
Writing objects: 100% (6/6), 516 bytes | 516.00 KiB/s, done.
Total 6 (delta 2), reused 0 (delta 0)
remote: 
remote: View merge request for 1-branch2:
remote:   https://gitlab.com/masakura/mistake-commit/-/merge_requests/1
remote: 
To gitlab.com:/masakura/mistake-commit.git
   e999941..6e67226  1-branch2 -> 1-branch2
Branch '1-branch2' set up to track remote branch '1-branch2' from 'origin'.

メインブランチの誤ったコミットを削除します。ローカルのメインブランチを削除して、リモートのメインブランチから作成し直します。

$ git branch -D main
Deleted branch main (was 6e67226).

$ git checkout main
Branch 'main' set up to track remote branch 'main' from 'origin'.
Switched to a new branch 'main'

ローカルリポジトリの状態によってはこの方法が使えないこともあります。不安な方は、いろいろ試そうとせずに、近くのGitマイスターにヘルプを頼んでください。

Gitlab x icon svg