Home > Enterprise >  Is it possible to make a Git commit on another branch without changing branches?
Is it possible to make a Git commit on another branch without changing branches?

Time:01-05

I am working on branch feature-a, and I need to make a change to feature-b on an unrelated part of the source code. I forgot (or was too lazy) to make a secondary work tree, and edited some files that should be changed in the feature-b branch.

I could now make a worktree and rsync my uncommitted changes to the worktree. Or I could make my changes on the current branch and then git-cherry-pick/git-rebase them into the right place.

But really I just want to be able to make a commit on feature-b that reflects my edits, without actually changing the branch, switching out the contents of the main working tree, etc.

Is this possible with the Git CLI?

CodePudding user response:

Yes, that is possible. But you will have to use git low-level commands (a.k.a. git plumbing). The basic tasks would be:

  • create new objects for the changed files (git hash-object -w)
  • create new trees for the directories containing the changed files (git write-tree)
  • create a new commit object referencing the tree for the root directory and the appropriate parent commit (git commit-tree)
  • move the branch to that new commit
  • push the branch

Note that for the last two steps you can use high-level git-commands, the first three are the tricky ones.

The example in chapter 10.2 does pretty much what you want.

  •  Tags:  
  • Related