30.08.20

Moving commits to a rewritten git repository

The situation: a git repository had been fully prettify-ed using git filter-branch, but I kept working in a separate branch of the old version of the repository.

It seems that git filter-branch could not help me, as the new repository’s internal structure was no longer compatible with my old branch. Therefore, I used this quick and dirty shell script. It worked!

#!/bin/bash
#######################################
# Before running:
#   1. Replace 'oldproject', 'newproject' and the contents of STARTCOMMIT
#   2. Put this script in a directory above oldproject and newproject
#   3. chmod +x thisscript.sh
#
# Use at your own risk.
#######################################

cd oldproject

STARTCOMMIT="...";
COMMITS="$(git log --oneline $STARTCOMMIT..HEAD  | tac | awk '{print $1}')"

for COMMIT in $COMMITS; do
  echo "******************** $COMMIT *****************"
  MESG="$(git log --pretty=format:'%s' $COMMIT~1..$COMMIT)"
  FILES="$(git diff-tree --no-commit-id --name-only -r $COMMIT | grep -v package-lock)"

  # Copy files within commit
  for FILE in $FILES; do
    git show $COMMIT:$FILE > ../newproject/$FILE
  done

  cd ../newproject/

  # Run 'prettier' on the files
  # NOTE: this can be optimized by only using files from $FILES
  node_modules/.bin/prettier --no-config --single-quote --tab-width=4 \
  --arrow-parens always --use-tabs --print-width=140 --write "**/**.js"
  git add -A
  git commit -m "$MESG"

  cd ../oldproject
done