Search code examples
gitgit-subtree

Push changes from git subtree to a branch for a pull request


How can I create local changes to a git subtree and then push those changes to a branch in the subtree's repo so that I can then create a pull request to merge the changes from that branch into the subtree's master?

Assume I have two repos, project and protocols, both of which are under my control.

Step 1: add protocols as a subtree in the project repo

$ git remote add protocols [email protected]:corp/protocols.git

$ git remote
origin
protocols

$ git subtree add --prefix=protocols protocols master --squash
...
From bitbucket.org:corp/protocols
 * branch            master     -> FETCH_HEAD
 * [new branch]      master     -> protocols/master
Added dir 'protocols'

Step 2: make some changes in the project repo to files that are in the protocols subtree

$ cd protocols
$ echo "foo" > some_file
$ git commit -a -m "added foo"

Step 3: create a branch in the protocols repo and push my local changes from project/protocols subtree to that branch

??

I'm unsure as to how best to achieve this...

Once my subtree changes have been successfully pushed to a branch in the remote protocols repo, I can then create a pull-request to merge those changes back into the protocols master.

Questions:

  • I have a local copy of protocols. Should I change to that repository, create a branch, and then change back to project and push the subtree changes to my local protocols repo?

  • Can I push the subtree changes directly to a new branch (as of yet uncreated) in my local protocols repo?

  • Can I push the subtree changes directly to a new branch (as of yet uncreated) in the remote protocols repo?

  • Is this a recommended workflow?


Solution

  • create a branch in the protocols repo and push my local changes from project/protocols subtree to that branch

    You can achieve that with a single command, subtree push, specifying a new remote branch:

    $ git subtree push --prefix=protocols protocols feature
    

    This will create a new branch, feature in the remote repository protocols

    you can now create a pull request to merge the feature branch back into the master branch of protocols.

    Once the branch has been merged back, you can update your subtree using a pull with --squash

    $ git subtree pull --prefix=protocols protocols master --squash
    

    This will create another commit with all the changes in the protocols repo squashed into one, and then a merge commit to merge into your project repo

    Note there is a slight quirk to this method, and that is there will now be two commits in your project repo which contain the changes to the protocols repo.

    • The original commit made in the project repo's protocols subtree
    • The commit created by a subsequent subtree pull (typically along with other protocol changes, assuming --squash was used)