Skip to content

Commit 233686d

Browse files
authored
Change git-cp to use cleaner branch approach (#1169)
* Change git-cp to use cleaner branch approach, per https://stackoverflow.com/a/46484848/32841 and https://devblogs.microsoft.com/oldnewthing/20190919-00/?p=102904 * Name the temporary branch to better fit in with git-extras * Again, git-extras naming is "copy", not "split" * Make the commit messages more clear
1 parent 5c3fb1b commit 233686d

File tree

1 file changed

+16
-24
lines changed

1 file changed

+16
-24
lines changed

bin/git-cp

Lines changed: 16 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -50,37 +50,29 @@ else
5050
fi
5151
fi
5252

53-
MERGE_OPT=
54-
ff=$(git config --get merge.ff || true)
55-
if [[ "$ff" == "only" ]]; then
56-
MERGE_OPT="--ff"
57-
fi
5853

5954
echo "Copying $CURRENT_FILENAME into $DESTINATION_FILENAME"
6055

61-
INTERMEDIATE_FILENAME="${CURRENT_FILENAME//\//__}-move-to-${DESTINATION_FILENAME//\//__}"
62-
63-
# We keep the existing file on the side in a commit
64-
git mv "${CURRENT_FILENAME}" "${INTERMEDIATE_FILENAME}"
65-
git commit -nm "Keep $CURRENT_FILENAME"
56+
# Pre-check that the source and destination will work
57+
git mv --dry-run "${CURRENT_FILENAME}" "${DESTINATION_FILENAME}"
6658

67-
# We come back to the previous state and revert that change
68-
INTERMEDIATE_SAVED=$(git rev-parse HEAD)
69-
git reset --hard HEAD^
59+
# Make a new branch and switch to it
60+
BRANCH_NAME="git-cp-$(date +%s)"
61+
git checkout -b "$BRANCH_NAME"
7062

71-
# We move the file to its new destination
63+
# Move the original file to the new destination, in this branch
7264
git mv "${CURRENT_FILENAME}" "${DESTINATION_FILENAME}"
73-
git commit -nm "Copy $CURRENT_FILENAME into $DESTINATION_FILENAME"
65+
git commit -nm "--Duplicate $CURRENT_FILENAME history into $DESTINATION_FILENAME"
7466

75-
# We come back to the previous state and revert that change again
76-
DESTINATION_SAVED=$(git rev-parse HEAD)
77-
git reset --hard HEAD^
67+
# Restore the original file to keep it in the history
68+
git checkout HEAD~ "${CURRENT_FILENAME}"
69+
git commit -nm "--Restore $CURRENT_FILENAME"
7870

79-
# We keep both files
80-
# shellcheck disable=SC2086
81-
git merge $MERGE_OPT "${DESTINATION_SAVED}" "${INTERMEDIATE_SAVED}" -m "Duplicate ${CURRENT_FILENAME} history."
71+
# Switch to the original branch and merge this back in.
72+
git checkout -
73+
git merge --no-ff "$BRANCH_NAME" -m "Copy $CURRENT_FILENAME into $DESTINATION_FILENAME"
8274

83-
# We get back our original name
84-
git mv "${INTERMEDIATE_FILENAME}" "${CURRENT_FILENAME}"
85-
git commit -nm "Set back ${CURRENT_FILENAME} file"
75+
# We're now done with the branch, so delete it.
76+
# We shouldn't need -D here, as we've already merged it back in.
77+
git branch -d "$BRANCH_NAME"
8678
fi

0 commit comments

Comments
 (0)