user2012677
user2012677

Reputation: 5735

Divide Git branch by files

Git Branch A has a number of files modified(about 50 files or so), which were modified over time and sometimes as in the same commit:

Example:

File A
File B
File C
File AA
File BB
File CC
File ZZ

I would like to split the file changes into two branches, File A, B, C, ZZ would be in Branch A, and Files AA,BB,CC, ZZ would be on Branch B. I need one common file.

Is there a way to do this? If so how?

Example:

Master --------\
                \
                 \- - - - -- Branch A (Files, A,B,C,AA,BB,CC, ZZ)

Goal:
Master --------\
               |\
               | \- - - Branch A (Files, A,B,C, ZZ)
               |
               |-------- Branch B (Files, AA,BB,CC,ZZ)

Upvotes: 2

Views: 673

Answers (2)

balloon_voice
balloon_voice

Reputation: 11

One approach I like for the "case that the changes to your files are not mixed within the same commit" is to create a new branch at the tip of the branch I want to split and use rebase -i to drop irrelevant commits.

i.e.

With branch_a checked out run:

git checkout -b branch_b
git rebase -i <common ancestor commit>

For my use cases, most often <common ancestor commit> is the name of the main branch I have checked out, e.g. main or develop or something like that off of which I started working.

Upvotes: 1

Oxymoron
Oxymoron

Reputation: 1452

  1. Identify your common ancestor revision commit hash. This is identified with a red asterisk in all images below. I'm going to use a9c146a09505837ec03b as an example hash.

    a. git show or gitk can help with this

  2. Checkout a new branch with that hash as your head (i.e. Branch B)

    a. git checkout -b Branch_B a9c146a09505837ec03b

  3. checkout the specific files from Branch A onto your new branch Branch B.

    a. i.e. git checkout Branch_A -- "A.file"

or if you would like to keep your commit messages you can use git cherry-pick, but only in the case that the changes to your files are not mixed within the same commit. If you have to split the commit up then your best using the example above with checkout. You will loose your history, but if you really need to retain that, you can git checkout on specific commit hashes too and walk through your history bring over the file mutations in order. A sever headache for sure.

Please keep in mind, your hashes ARE going to change.

repeat steps 2 & 3 as necessary for the amount of branches you would like to create. Avoid making changes to the same content across multiple branches, this will lead to a merge conflict.


Some Examples:

Current State

Example with no common files

Example with common file changes

Upvotes: 1

Related Questions