Created
March 14, 2023 12:05
-
-
Save rexagod/bca78ec4c8828cbd3c6ecfa27f94a1e0 to your computer and use it in GitHub Desktop.
In the land of infinite remotes, take this with you! ⚔️
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
#!/usr/bin/bash | |
# Author: @rexagod, et al. | |
# Set -e so that the script exits if any command fails. | |
set -e | |
# This utility: | |
# * takes in a URI, in the format: remote_name:branch, | |
# * adds that remote if it doesn't exist, and finally, | |
# * checks out to that branch. | |
# Example usage: | |
# ./checkout-to.sh foo:bar | |
# ./checkout-to.sh clean foo:bar | |
# Add this to your `git` workflow by running the command below. | |
# * git config --global alias.checkout-to '<path to executable script>' | |
# Example usage: | |
# git checkout-to foo:bar | |
# git checkout-to clean foo:bar | |
# Accept the URI as an argument, and validate the format. | |
uri=$1 | |
clean=false | |
# If $1 was "clean", then assign $2 to $uri. | |
if [[ $uri == "clean" ]]; then | |
uri=$2 | |
clean=true | |
fi | |
if [[ $uri != *:* ]]; then | |
echo "Invalid URI format. Please use the format: remote_name:branch" | |
exit 1 | |
fi | |
# Split the URI into remote and branch. | |
remote=$(echo "$uri" | cut -d: -f1) | |
branch=$(echo "$uri" | cut -d: -f2) | |
# If clean is true, then remove the remote and branch. | |
if [[ $clean == true ]]; then | |
git remote remove "$remote" | |
git checkout - | |
git branch -D "$branch" | |
exit 0 | |
fi | |
# Add the remote if it doesn't exist, and update it. | |
if ! git remote | grep -q "$remote"; then | |
repo=$(basename "$(git rev-parse --show-toplevel)") | |
remote_uri="git@github.com:$remote/$repo.git" | |
git remote add "$remote" "$remote_uri" | |
git remote update "$remote" | |
fi | |
# Checkout to the branch. | |
git checkout --track "$remote/$branch" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The general idea behind this is for collaborators or maintainers to easily checkout odd branches, and clean any artefacts when they are done with it.