Created
November 12, 2020 18:07
-
-
Save j-fuentes/741188bfa5e06f538baf3cbb63fb768b to your computer and use it in GitHub Desktop.
Import a repo into a subfolder of another repo preserving commit history
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -eux | |
shopt -s extglob dotglob | |
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" | |
TEMP_DIR="${DIR}/import-repos-temp" | |
# e.g. git@github.com:user/world-domination-frontend.git | |
SUBPROJECT_REPO="$1" | |
# e.g. frontend | |
SUBPROJECT_NAME="$2" | |
# It must be a local dir that is an existing git project where we want to move the subproject to. | |
# It needs to have at least one commit and it should not have file that conflict with files in the subproject you want to merge. | |
DESTINATION_REPO_DIR="$(realpath $3)" | |
rm -rf "${TEMP_DIR}" | |
mkdir -p "${TEMP_DIR}" | |
# We create a local bare repo to host a branch that moves all the content to a subproject folder. | |
cd "${TEMP_DIR}" | |
git init --bare "${SUBPROJECT_NAME}.git" | |
git clone "${SUBPROJECT_REPO}" "${SUBPROJECT_NAME}" | |
cd "${SUBPROJECT_NAME}" | |
git remote add -f local file://${TEMP_DIR}/${SUBPROJECT_NAME}.git | |
TRUNK_BRANCH=$(git rev-parse --abbrev-ref HEAD) | |
mkdir "${SUBPROJECT_NAME}" | |
mv !([.]git|${SUBPROJECT_NAME}) "./${SUBPROJECT_NAME}" | |
git add . | |
git commit -m "Move everything to the ${SUBPROJECT_NAME} subfolder" | |
git push local | |
# Merge the changes we pushed to the local copy of the repo into the destination repo. | |
cd ${DESTINATION_REPO_DIR} | |
git remote remove ${SUBPROJECT_NAME} || true | |
git remote add -f ${SUBPROJECT_NAME} file://${TEMP_DIR}/${SUBPROJECT_NAME}.git | |
git merge ${SUBPROJECT_NAME}/${TRUNK_BRANCH} --allow-unrelated-histories -m "Merge project ${SUBPROJECT_REPO} into ./${SUBPROJECT_NAME}" | |
# Cleanup | |
git remote remove ${SUBPROJECT_NAME} | |
rm -rf ${TEMP_DIR} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment