Skip to content

Instantly share code, notes, and snippets.

@AltGr
Created July 25, 2014 17:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AltGr/db3bd8a238ceb63d56d0 to your computer and use it in GitHub Desktop.
Save AltGr/db3bd8a238ceb63d56d0 to your computer and use it in GitHub Desktop.
Plug git directories between repos with history
#!/bin/bash -ue
usage() {
echo "Usage: $0 srcdir[#ref] dstdir[#ref]"
echo
echo "Pastes between subdirectories of git repositories,"
echo "preserving history"
}
SRC="$1"; shift
DST="$1"; shift
if [ $# -gt 0 ]; then usage; exit 2; fi
SRCBRANCH=${SRC#*#}
SRC=${SRC%#*}
if [ x"$SRC" = x"$SRCBRANCH" ]; then SRCBRANCH=master; fi
SRC=$(readlink -f "$SRC")
SRCGIT=$(cd "$SRC" && git rev-parse --show-toplevel)
SRCDIR=.${SRC##$SRCGIT}
DSTBRANCH=${DST#*#}
DST=${DST%#*}
if [ x"$DST" = x"$DSTBRANCH" ]; then DSTBRANCH=master; fi
mkdir -p "$DST"
DST=$(readlink -f "$DST")
DSTGIT=$(cd "$DST" && git rev-parse --show-toplevel)
DSTDIR=.${DST##$DSTGIT}
TMP=$(mktemp -d /tmp/git-graft.XXXXX)
trap "rm -rf /tmp/${TMP#/tmp/}" EXIT
echo "=== pasting dir $SRCDIR from $SRCGIT at $SRCBRANCH"
echo "=== to dir $DSTDIR within $DSTGIT at $DSTBRANCH"
echo "=== using temp dir $TMP"
cd $TMP
git clone -- "$SRCGIT" src
cd src
if [ x"$SRCDIR" != x"." ]; then
git filter-branch --subdirectory-filter "${SRCDIR#./}"
fi
if [ x"$DSTDIR" != x"." ]; then
git filter-branch -f --index-filter '\
git ls-files -s | \
sed "s#\t#&'"${DSTDIR#./}"'/#" | \
GIT_INDEX_FILE=.gitindex.new git update-index --index-info && \
(mv .gitindex.new $GIT_INDEX_FILE || true)'
fi
cd $DSTGIT
BRANCH=graft-from-${SRCGIT##*/}${SRCDIR//\//-}
BRANCH=${BRANCH//./}
git fetch "$TMP/src"
MERGED=$(git branch --merged $DSTBRANCH $BRANCH)
if [ -n "$MERGED" ]; then
git rebase --preserve-merges $BRANCH FETCH_HEAD
git checkout -B $BRANCH HEAD
git checkout $DSTBRANCH
git merge $BRANCH
else
git branch -f $BRANCH FETCH_HEAD
git merge $BRANCH
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment