Skip to content

Instantly share code, notes, and snippets.

@sihil
Created March 20, 2019 13:49
Show Gist options
  • Save sihil/7958bb2dcbc5544b81a1f30ca6946f0a to your computer and use it in GitHub Desktop.
Save sihil/7958bb2dcbc5544b81a1f30ca6946f0a to your computer and use it in GitHub Desktop.
A script to clone recently used github repos
#!/bin/bash -e
if [ -z "$1" -o -z "$2" ]; then
cat <<MSG
${BASH_SOURCE[0]} is a script to clone recently used github repos. Potentially
useful when you have a new laptop.
Usage: ${BASH_SOURCE[0]} user token [clone_dir] [months]
user: your github username
token: a github token with enough permission to see the repos you want
to checkout (the repo scope seems to be required for private repos)
clone_dir: the directory that repos should be cloned in (defaults to ~/code)
months: the number of months to look back (defaults to 12)
When cloning this script uses ssh, please ensure you have already used ssh-add
or similar to ensure your github ssh key is available.
MSG
exit 1
fi
USER=$1
TOKEN=$2
DIR=${3:-~/code}
MONTHS=${4:-12}
BASE_URL="https://api.github.com/search/commits"
DATE=$(date -v -${MONTHS}m +%Y-%m-%d)
get_repos() {
PAGE_NUMBER=$1
curl -s -u ${USER}:${TOKEN} \
-H "Accept: application/vnd.github.cloak-preview" \
"${BASE_URL}?q=author:${USER}+author-date:%3E${DATE}&page=${PAGE_NUMBER}"\
| jq -r .items[].repository.full_name
}
PAGE=1
REPOS=""
NL=$'\n'
echo -n "Getting list of github repos ${USER} has committed to in the last ${MONTHS} months "
while true; do
NEXT_PAGE=$(get_repos ${PAGE})
if [ -z "${NEXT_PAGE}" ]; then
echo " done"
break;
else
echo -n "."
REPOS="${REPOS}${NL}${NEXT_PAGE}"
fi
((PAGE++))
done
UNIQ_REPOS=$(echo "$REPOS" | sort | uniq)
mkdir -p ${DIR}
pushd ${DIR}
for repo in ${UNIQ_REPOS}; do
cd ${DIR}
repo_dir=$(basename ${repo})
if [ ! -e $repo_dir ]; then
echo "Cloning ${repo}"
git clone --quiet git@github.com:${repo}.git
else
echo "Skipping ${repo} as /${repo_dir} exists"
fi
done
popd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment