Skip to content

Instantly share code, notes, and snippets.

@alexjyong
Created June 22, 2023 20:09
Show Gist options
  • Save alexjyong/29d7a357ecfed2e9cffec126e0d2d668 to your computer and use it in GitHub Desktop.
Save alexjyong/29d7a357ecfed2e9cffec126e0d2d668 to your computer and use it in GitHub Desktop.
codespace_port_forward.sh
#!/bin/bash
#this script is meant to be ran on your local machine with gh installed.
#it is not meant to be ran within codespaces.
# this will select a codespace from a repo of your choosing and forward the ports to your
#local machine, so you can visit any process running on the codespace in your browser instead of going to the
# complex codespace generated url, which may break some code.
# this is pretty much the codespace version of this for gitpod https://www.gitpod.io/blog/local-app
# Function to clean up port forwarding processes
cleanup() {
echo "Cleaning up port forwarding processes..."
for pid in "${pids[@]}"; do
kill "$pid" 2>/dev/null
done
}
# Trap to catch interrupt signal and clean up before exiting
trap 'cleanup; exit' INT
# Check if jq is installed
if ! command -v jq >/dev/null 2>&1; then
echo "Error: jq is not installed."
echo "Please install jq from https://stedolan.github.io/jq/download/ and try again."
exit 1
fi
# Check if fzf is installed
if ! command -v fzf >/dev/null 2>&1; then
echo "Error: fzf is not installed."
echo "Please install fzf from https://github.com/junegunn/fzf#installation and try again."
exit 1
fi
# Check if a repository argument is provided
if [ -z "$1" ]; then
echo "Usage: $0 <repository>"
echo "Example: $0 alexjyong/mycoolrepo"
exit 1
fi
# Set the repository from the command-line argument
repo="$1"
# Get the codespace names for the specified repository
codespace_names=$(gh codespace list --json name,repository | jq -r ".[] | select(.repository == \"$repo\") | .name")
# Check if any codespaces were found
if [ -z "$codespace_names" ]; then
echo "No codespace found for $repo"
exit 1
fi
# Count the number of codespaces
codespace_count=$(echo "$codespace_names" | wc -l)
# If there are multiple codespaces, let the user select one using fzf
if [ "$codespace_count" -gt 1 ]; then
echo "Multiple codespaces found for $repo:"
codespace_name=$(echo "$codespace_names" | fzf)
else
codespace_name="$codespace_names"
fi
# Get the list of ports for the selected codespace
ports=$(gh codespace ports -c "$codespace_name" --json sourcePort -q '.[].sourcePort')
# Forward each port less than 10000 and store their PIDs
declare -a pids
for port in $ports; do
if [ "$port" -lt 10000 ]; then
echo "Forwarding port $port"
gh codespace ports forward "$port:$port" -c "$codespace_name" &
pids+=("$!")
echo $pids
fi
done
# Wait for all port forwarding processes to complete
wait
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment