Reputation: 100486
Say I have this sequence of commands:
current_branch="$(git rev-parse --abbrev-ref HEAD)"
git checkout -b "foo"
git lock "$current_branch" # i made this up
what I want to do is lock a branch so that I cannot accidentally make changes to it after I am done with it. For example, after a feature branch has been squashed and merged into the integration branch.
Is there a way to do this with git? Perhaps there is a way to lock a worktree using https://git-scm.com/docs/git-worktree?
Upvotes: 2
Views: 2787
Reputation: 4580
How about we roll this feature ourselves? Lets start with your git lock
command. We can write that as an alias;
$ git config alias.lock "! touch .locks;
git rev-parse --abbrev-ref HEAD | cat - .locks | sort | uniq > .locks.tmp;
mv .locks.tmp .locks;"
Whenever we call git lock
we're going to add the current branch to the .locks
file which is our distinct list of locked branches.
Then create (or edit) .git/hooks/pre-commit
to include;
#!/bin/sh
if grep -Fxq `git rev-parse --abbrev-ref HEAD` .locks
then
cat <<\EOF
Error: Branch is locked
EOF
exit 1
fi
Which will check the .locks
file each time we commit to make sure we're not commiting to a locked branch.
Add an entry in your .gitignore
to ignore our new .locks
file and you're done.
Example usage;
adam@lime ~/git-lock $ git checkout -b MuhBranch
Switched to a new branch 'MuhBranch'
adam@lime ~/git-lock $ git commit -m "Final changes." --allow-empty
[MuhBranch 0304f21] Final changes.
adam@lime ~/git-lock $ git lock
adam@lime ~/git-lock $ git commit -m "Just one more..." --allow-empty
Error: Branch is locked
Remember to make your .git/hooks/pre-commit
executable using chmod u+x .git/hooks/pre-commit
.
Upvotes: 3
Reputation: 1888
To lock a branch, you can use git hooks. Check out this SO.
#!/bin/sh # lock the myfeature branch for pushing refname="$1" if [[ $refname == "refs/heads/myfeature" ]] then echo "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" echo "You cannot push to myfeature! It's locked" echo "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" exit 1 fi exit 0
Upvotes: 0