Automating to copy a set of commits from one branch to another
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 | |
# Prints usage | |
usage() { | |
echo "Usage: $0 -p <project_path> -s <source-branch> -t <target-branch> -f <commit-start> -e <commit-target>" 1>&2 | |
} | |
# Prints usage and exit | |
abnormal_exit() { | |
usage | |
exit 1 | |
} | |
# Variables for branches, commits and project_path | |
PROJECT_PATH="" | |
SOURCE_BRANCH="" | |
TARGET_BRANCH="" | |
FROM_COMMIT="" | |
TO_COMMIT="" | |
# Getting all the options | |
while getopts ":p:s:t:f:e:" o; do | |
case "${o}" in | |
p) | |
PROJECT_PATH="${OPTARG}" | |
;; | |
s) | |
SOURCE_BRANCH="${OPTARG}" | |
;; | |
t) | |
TARGET_BRANCH="${OPTARG}" | |
;; | |
f) | |
FROM_COMMIT="${OPTARG}" | |
;; | |
e) | |
TO_COMMIT="${OPTARG}" | |
;; | |
*) | |
abnormal_exit | |
;; | |
esac | |
done | |
shift $((OPTIND-1)) | |
# If one of the options is not set, just abnormal exit | |
if [ -z "${PROJECT_PATH}" ] || [ -z "${SOURCE_BRANCH}" ] || [ -z "${TARGET_BRANCH}" ] || [ -z "${FROM_COMMIT}" ] || [ -z "${TO_COMMIT}" ] | |
then | |
abnormal_exit | |
fi | |
# Showing all variables, you can uncomment them | |
echo "Repository Path : $PROJECT_PATH" | |
echo "Source branch: $SOURCE_BRANCH" | |
echo "Target branch: $TARGET_BRANCH" | |
echo "From commit: $FROM_COMMIT" | |
echo "To commit: $TO_COMMIT" | |
echo "" | |
echo "---Starting copying commits---" | |
# Go to the project path | |
cd "$PROJECT_PATH" | |
# Checkout to source branch | |
echo "Checking out to ${SOURCE_BRANCH}..." | |
git checkout "$SOURCE_BRANCH" | |
if ! [[ $? -eq 0 ]] | |
then | |
echo $'\u274c' "ERROR: Failed to checkout to $SOURCE_BRANCH" | |
exit 2 | |
fi | |
# Getting all commits between them inclusive | |
echo "Getting all commits..." | |
commits=($(git rev-list "$FROM_COMMIT^..$TO_COMMIT")) | |
# Now checking out to target branch | |
echo "Checking out to ${TARGET_BRANCH}..." | |
git checkout "$TARGET_BRANCH" | |
if ! [[ $? -eq 0 ]] | |
then | |
echo $'\u274c' "ERROR: Failed to checkout to $TARGET_BRANCH" | |
exit 2 | |
fi | |
# For each commit | |
for ((i=$((${#commits[@]}-1));i>=0;i--)) | |
do | |
echo "Cherry Picking ${commits[i]} ..." | |
git cherry-pick "${commits[i]}" | |
# If the above command fails, then exit with proper message | |
if ! [[ $? -eq 0 ]] | |
then | |
echo "ERROR: Cherry pick commit with ${commits[i]} failed, exiting..." | |
exit 2 | |
fi | |
# Show success message for the copied commit | |
echo "DONE: Commit ${commits[i]} copied" | |
done | |
# Show success message of all the commits copied | |
echo "COMPLETED: Cherry pick of ${#commits[@]} commits finished." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment