Search code examples
gitgithubgit-filter-branchgit-filter-repo

How to use git-filter-repo to merge one repo as subdirectory into another


While trying to use git filter-branch to merge repos using this gist. Adding just the relevant snippet in question:

git filter-branch -f --prune-empty --tree-filter '
        mkdir -p "${REPO_NAME}_tmp"
        git ls-tree --name-only $GIT_COMMIT | xargs -I{} mv {} "${REPO_NAME}_tmp"
        mv "${REPO_NAME}_tmp" "$REPO_NAME"
    '

I got a warning from git stating the following:

WARNING: git-filter-branch has a glut of gotchas generating mangled history
     rewrites.  Hit Ctrl-C before proceeding to abort, then use an
     alternative filtering tool such as 'git filter-repo'
     (https://github.com/newren/git-filter-repo/) instead.  See the
     filter-branch manual page for more details; to squelch this warning,
     set FILTER_BRANCH_SQUELCH_WARNING=1.

So, I took a look at git filter-repo, the description states the following:

restructuring the file layout (such as moving all files into a subdirectory in preparation for merging with another repo, ...

This showed that this issue can be resolved with git filter-repo, but even after checking the documentation and given examples I could not find a way to achieve this. Can someone please help me with the same.


Solution

  • Replace the filter-branch command in the script

    git filter-branch -f --prune-empty --tree-filter '
            mkdir -p "${REPO_NAME}_tmp"
            git ls-tree --name-only $GIT_COMMIT | xargs -I{} mv {} "${REPO_NAME}_tmp"
            mv "${REPO_NAME}_tmp" "$REPO_NAME"
        '
    

    with this

    git filter-repo --to-subdirectory-filter "$REPO_NAME"
    

    See Path shortcuts section here

    --to-subdirectory-filter <directory>

    Treat the project root as instead being under <directory>

    Equivalent to using --path-rename :<directory>/