git

Convert or copy a folder from a git branch with all its history to be a new git branch


I have the following Git Branch folder structure:

- b1
-- f1
-- f2
-- f3

I want to create a new branch b2 based on b1 and folder f2 only, then make changes in f2 and rename the folder from f2 to f2_updated and push only f2_updated without f1 and f3. I want to include the commit history of b1/f2 under b2/f2_update.

How I can do that?

I am thinking to do the following:

>git checkout <b1> -- <f2>
>git switch <b2>
...
make the changes
rename f2 to f2_UPDATED
...
>git push ...

The final structure should look like:

- b1
-- f1
-- f2
-- f3


- b2
-- f2_updated

Solution

  • Make a new branch from a subdirectory of an existing branch:

    git update-ref refs/heads/$subdir $(
        git commit-tree -p $existing -m "slice $subdir" $existing:$subdir
    )
    

    and everything in $subdir will show up as renames of what they were in the parent.

    You can merge any changes back by asking Git to spend some time looking for this kind of thing with git merge -Xsubtree or just tell it with -Xsubtree=$subdir.