gvoysey
gvoysey

Reputation: 546

make new git branch containing full history of only some files

I'm in the middle of a refactor that will eventually separate out "the core model" from the API i've built around it.

I have the current (simplified) directory structure:

/root
|-model_core.py
|-model_configuration.py
|-model_frontend.py
|-plot_model.py
|-cool_use_for_model.py

How do I make a new branch, model-core, that contains model_core.pyand model_configuration.py only, as well as their full commit history from the current branch?

Upvotes: 2

Views: 278

Answers (2)

CodeWizard
CodeWizard

Reputation: 142054

You have few options to do it:

http://blogs.atlassian.com/2014/04/tear-apart-repository-git-way/
https://lostechies.com/johnteague/2014/04/04/using-git-subtrees-to-split-a-repository/

The main 2 optins are:

git filter-branch

git subtree split --prefix=lib -b split

As mentioned above lets explain in details each options

filter-branch will loop over each commit and then you can checkout only the given files while git subteree split will be a better option in your case.

Explaining both of the option so you can choose which one you prefer.


Sample code:

filter-branch

# Filter the master branch to your directory and remove empty commits
git filter-branch --prune-empty --subdirectory-filter YOUR_FOLDER_NAME filter_from_branch

This will checkout all your desired files from the given folder to the current directory


subtree split

git subtree git-subtree - Merge subtrees together or split repository into subtrees

git subtree split -P <name-of-folder> -b <name-of-new-branch>

enter image description here

Upvotes: 2

BlueSpaceCanary
BlueSpaceCanary

Reputation: 411

I assume you're looking to remove the other files from the branch's history entirely, rather than just a git rm {model_frontend,plot_model,cool_use_for_model,}.py commit. If that covers what you need, though, definitely just do that rather than messing around with your repo's history.

Fair warning: Because this involves rewriting the files out of old commits, your git history will be rewritten and the branches will not agree on the contents of commits. This can make things messy. If you don't know what you're doing, do not do this.

That said, if you create the branch my-core-branch to do this in, then git filter-branch --tree-filter 'rm -f model_frontend.py plot_model.py cool_use_for_model.py' my-core-branch will rewrite history in my-core-branch to remove those files, but leave your other branches' history. The hashes for commits touching those files and also files you're not deleting will no longer match between branches, obviously, so again, for any git newbies reading this, use at your own risk.

Upvotes: 1

Related Questions