Rakesh Rawat
Rakesh Rawat

Reputation: 327

GIT: Is it possible to pick files or changes from a different repo with different directory structure

I want to pick some files and changes from a different repo which has different directory structure rather than copy things and to keep history. Is it possible in git?

Upvotes: 2

Views: 597

Answers (1)

VonC
VonC

Reputation: 1329722

As described in "Moving Files from one Git Repository to Another, Preserving History", this is easier if the file(s) you want to import are in a folder: exporting/importing a folder (with its history) is easier than just a file.

Goal: Move directory 1 from Git repository A to Git repository B.

  • Make a copy of repository A so you can mess with it without worrying about mistakes too much.
  • It’s also a good idea to delete the link to the original repository to avoid accidentally making any remote changes (line 3).
  • Line 4 is the critical step here. It goes through your history and files, removing anything that is not in directory 1

That is:

git clone <git repository A url>
cd <git repository A directory>
git remote rm origin
git filter-branch --subdirectory-filter <directory 1> -- --all
mkdir <directory 1>
mv * <directory 1>
git add .
git commit
  • Make a copy of repository B if you don’t have one already.
  • On line 3, you’ll create a remote connection to repository A as a branch in repository B.
  • Then simply pull from this branch (containing only the directory you want to move) into repository B.
  • The pull copies both files and history.

Step 2:

git clone <git repository B url>
cd <git repository B directory>
git remote add repo-A-branch <git repository A directory>
git pull repo-A-branch master --allow-unrelated-histories

git remote rm repo-A-branch

You have other options described in this answer or this one, which preserves the full path name (but forces you to specify all that you want to exclude, which is longer than specifying the one folder you want to keep).

# 1. clone the source
git clone ssh://<user>@<source-repo url>
cd <source-repo>
# 2. remove the stuff we want to exclude
git filter-branch --tree-filter "rm -rf <files to exclude>" --prune-empty HEAD
# 3. move to target repo and create a merge branch (for safety)
cd <path to target-repo>
git checkout -b <merge branch>
# 4. Add the source-repo as remote 
git remote add source-repo <path to source-repo>
# 5. fetch it
git pull source-repo master

Upvotes: 2

Related Questions