Skip to content

Instantly share code, notes, and snippets.

@dreness
Last active April 25, 2024 07:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dreness/0486046c4735d7dc542057c106509abd to your computer and use it in GitHub Desktop.
Save dreness/0486046c4735d7dc542057c106509abd to your computer and use it in GitHub Desktop.
Use gh cli and fzf to add a remote for a fork of the current repo
#!/bin/sh
# Scenario:
# - you have a local checkout of a github repo
# - you're looking at public forks of that repo
# - you want to add a remote to your local checkout for one of the forks
set -e
set PIPEFAIL
# Use a fifo for a POSIX compatible array read.
FP=$(mktemp -d)/fifo
mkfifo "${FP}"
# Fetch all forks of the repo in the current directory.
# Sort by last pushed date.
# For each fork, print .pushed_at, owner.login, and .clone_url
# Use fzf to select a fork, and:
# - don't include column 3 in the preview
# - sort in reverse order (most recently pushed at the bottom)
# Redirect selection to the fifo; background so we don't block.
gh api --paginate "repos/{owner}/{repo}/forks" \
| jq -s '.[] | sort_by(.pushed_at)' \
| jq -r '.[] | "\(.pushed_at) \(.owner.login) \(.clone_url)"' \
| fzf --with-nth=1,2 --tac > "${FP}" &
# Read the fifo and let word splitting do its thing. We only need the last two words.
read -r _ FORK_OWNER FORK_CLONE_URL < "${FP}"
git remote add "${FORK_OWNER}" "${FORK_CLONE_URL}"
echo "Added remote ${FORK_OWNER}"
@dreness
Copy link
Author

dreness commented Jan 28, 2024

@huyz
Copy link

huyz commented Apr 24, 2024

For line 9, I think you mean

set -o pipefail

Btw, my preamble is always:

set -euo pipefail
shopt -s failglob
# shellcheck disable=SC2317
function trap_err { echo "ERR signal on line $(caller)" >&2; }
trap trap_err ERR
trap exit INT  # So that ^C will stop the entire script, not just the current subprocess
export PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }'

@huyz
Copy link

huyz commented Apr 24, 2024

This is a great script. I took your ideas further and added some features:

https://github.com/huyz/trustytools/blob/master/unixy/gh-remote-add-fork.sh

  • Support multi-select of forks
  • Let the results stream in as batches (no guaranteed final sorting if more batches come in, but easy to filter by year: '2024). (Btw, I don't think that a fifo helps for this)
  • Support searching the upstream's forks instead of the current repo's forks.
  • Support importing all the fork's tags
  • Auto-detect origin if gh can't detect what the default repo is.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment