Skip to content

Instantly share code, notes, and snippets.

@nwithan8
Last active April 21, 2022 06:52
Show Gist options
  • Select an option

  • Save nwithan8/416e47cbc7ce452382165071abec8e73 to your computer and use it in GitHub Desktop.

Select an option

Save nwithan8/416e47cbc7ce452382165071abec8e73 to your computer and use it in GitHub Desktop.
Add a single file to multiple local Git repositories and automatically open GitHub PRs
#!/bin/bash
# Copy a set of files to each repo in a dir, create a branch, and push to origin
# Requires GitHub CLI: `brew install gh` and must be logged in with `gh auth login`: https://cli.github.com/manual/
# Usage: multi_commit.sh BRANCH_NAME PATH_TO_LANDING_DIR_IN_REPO_1 PATH_TO_LANDING_DIR_IN_REPO_2 ... PATH_TO_FILE_TO_ADD
# You can edit these variables
MAIN_BRANCH="master"
# Do not edit below this line
#############################
if [ "$#" -lt 4 ]; then # if less than 4 parameters (script name counts as one)
echo "Missing required parameters"
fi
NEW_BRANCH_NAME=$1 # First argument is the branch name
REPO_PATHS=${@:2:$(($#-2))} # Second through second-to-last argument are the paths to where in the repos the file should be copied
FILE_PATH=${@:$#} # Last argument is the file to add
FILE_NAME=$(basename "$FILE_PATH") # Get the file name
COMMIT_MESSAGE="Added $FILE_NAME"
echo "Pushing changes for each repo..."
for REPO_PATH in $REPO_PATHS
do
# go to the repo
cd "$REPO_PATH" || exit 1
echo "Working in $(pwd)..."
# set up new branch
# this is where things will fail if this is not a Git repository
git stash # stash any changes on our current branch
git checkout "$MAIN_BRANCH" # checkout our main branch
git stash # stash any changes on our main branch
git pull # update our main branch
git checkout -b "$NEW_BRANCH_NAME" || git checkout "$NEW_BRANCH_NAME" # make and/or checkout new branch
# copy in file
cp "$FILE_PATH" .
echo "Copied $FILE_PATH to $(pwd)"
# add file (as part of all changes)
git add "$FILE_NAME"
# show diff
git diff
# commit
git commit -m "$COMMIT_MESSAGE"
# push
git push --set-upstream origin "$NEW_BRANCH_NAME"
# open a pull request via GitHub CLI
gh pr create --fill --base "$MAIN_BRANCH"
done
echo "Check GitHub for the open pull requests"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment