1

I keep accidentally making changes to files in my "live" branch instead of my "work" branch.

So following the advice at Prevent commits in master branch, I added a commit stopper to the pre-commit hook. So now I can only merge into the live branch, never commit. (which I think also means I can't merge --squash). (Wish there were a way to just say these files can't be edited. ??)

So I made a ton of changes in live, and now "live" shows lots of modified files. I have NOT made a commit since I start making changes.

So I think my strategy is to: stash all the uncommitted work: git stash -u

That clears all the changes from the live branch.

Now create a new feature branch from live: git branch -b work2

Now unstash the changes into the new branch git stash pop.

Then I'm clean to go. I can commit work2 and then merge into live.

Is that right/reasonable/righteous?

  • When your hook disallows any commits, then it won't matter if you are on master or work2. But if it only inhibits commits on master, your procedure should work. – j6t Apr 13 '23 at 06:14
  • The beginning of your question talks about different repositories, but then you talk about different branches. I guess the latter is correct; but please [edit] to clarify this. – tripleee Apr 13 '23 at 06:49
  • Sounds like you simply want to move your uncommitted changes to a different, new branch. There's a canonical question and answer. If your use-case is different, please let us know. – knittl Apr 13 '23 at 07:09

1 Answers1

2

You can stash them:

git add .
git stash
git checkout -b my_new_branch
git stash pop
git commit -m "my commit message"

However if you haven't made any commits to the wrong branch, you could just check out of that branch to another branch right now, then commit the work that you have. I prefer this over stashing which can be dangerous:

git checkout -b my_new_branch
git add .
git commit -m "my commit message"

This will work especially if the wrong branch you are working on is up to date in commits to the state of the new branch you want to create. If it isn't, then stashing might be the better option to grab just the new work you've done.

Kelsey Hannan
  • 2,857
  • 2
  • 30
  • 46