4

While working on projects, I want to always edit on branches other than master. Master is for working, tested code.

I sometimes forget this, and start coding on master branch. Then I have to reset changes, etc.

I wonder is there any way to make master files read-only, but still allow merges into it.

Zargo
  • 561
  • 3
  • 16
  • 1
    Allowing merges into it by *definition* makes it not read-only. Though assuming you're doing pull requests, you can require a review before you allow a merge. The main this is to always check which branch you're actually working on before making a commit. – Obsidian Age Aug 20 '19 at 03:55
  • 1
    if you haven't commit the new changes just create a new branch and the modified files will be moved over to the new branch and you can commit – rioV8 Aug 20 '19 at 09:09

1 Answers1

1

You could add a pre-commit hook (like this gist, which stop accidental commits to master)
You can adapt that hook to bypass it for merge commits.

VSCode should respect, through Git, that pre-commit, and you would not be able to commit right away if you are on master.
You would need to stash, switch branch, stash pop.

Actually, with the new git switch command (Git 2.23, August 2019), you don't even have to stash.

The example section of git switch deals with your scenario (starting working on the "wrong" branch)

After working in the wrong branch, switching to the correct branch would be done using:

$ git switch mytopic

However, your "wrong" branch and correct "mytopic" branch may differ in files that you have modified locally, in which case the above switch would fail like this:

$ git switch mytopic
error: You have local changes to 'frotz'; not switching branches.

You can give the -m flag to the command, which would try a three-way merge:

$ git switch -m mytopic
Auto-merging frotz
VonC
  • 1,042,979
  • 435
  • 3,649
  • 4,283
  • This prevents committing on the master, but it does not prevent starting to change the files. – Zargo Oct 05 '19 at 19:43
  • @user9144 no, but at least you can then switch branches (while keeping your index), and apply your current changes to the right branch. See the new [`git switch` command](https://stackoverflow.com/a/57066202/6309). – VonC Oct 05 '19 at 19:45
  • @user9144 I have edited the answer accordingly. The point is: start working from wherever, you can then switch and merge your work in progress to the right branch later on. – VonC Oct 05 '19 at 19:50