Permalink
Switch branches/tags
Nothing to show
Find file
Fetching contributors…
Cannot retrieve contributors at this time
executable file 136 lines (108 sloc) 2.35 KB
#!/usr/bin/env bash
#
# gist-backup
#
# Backs up all your public and private gists
# to the given directory.
#
# Example:
#
# gist-backup ~/gist-backups
#
# In addition to your own gists you can also backup your starred gists
# or (public) gists of a defined user by putting the gists url in an
# environment variable.
#
# Example:
#
# GIST_URL=https://api.github.com/gists/starred gist-backup ~/gist-backups/starred
# GIST_URL=https://api.github.com/users/aprescott/gists gist-backup ~/gist-backups/aprescott
#
token=$(git config --get github.gist.oauth.token)
url=${GIST_URL:-https://api.github.com/gists}
usage() {
cat <<END_USAGE
Usage:
gist-backup DIRECTORY
Example:
gist-backup ~/gist-backups
END_USAGE
if [ -z $token ]
then
cat <<END_USAGE_NOTE
NOTE:
In order for this to work, you're going to need
an OAuth token set in your git config under
github.gist.oauth.token
This is because the API token for your account
cannot be used as authentication/authorization
in version 3 of GitHub's API.
END_USAGE_NOTE
fi
}
if [ -z $token ]
then
echo "No OAuth token found in github.gist.oauth.token git config."
exit 1
fi
# if no backup directory has been given
if [ -z "$1" ]
then
echo "No backup directory given."
usage
exit 1
fi
# if the given directory doesn't exist, create it
if [ ! -e "$1" ]
then
mkdir -p $1
fi
# go into the given backup directory
cd $1
# if we failed to cd for some reason, abort
if [ $? -gt 0 ]
then
exit 1
fi
# Take's a git remote URI and clones it into
# the backup directory. If that directory
# exists already, cd's into it and does a
# git pull.
backup() {
echo "Backing up $1"
local dir=$(echo "$1" | cut -d / -f 4 | cut -d . -f 1)
if [ -e $dir ]
then
echo " Already cloned at $PWD/$dir. Pulling."
cd $dir
git pull -q
cd $OLDPWD
else
git clone -q $1
fi
}
page=1
retries=0
MAX_RETRIES=5
while [ $retries -lt $MAX_RETRIES ]
do
echo "Requesting Gist page: $page from $url"
gists=$(
curl -s -H "Authorization: token $token" -d "page=$page" -G $url |
sed -n 's/.*git_pull_url": "\(.*\)",/\1/p'
)
if [ -z "$gists" ]
then
echo "No gists found on this page. Trying again."
retries=$(( retries + 1 ))
continue
fi
for gist in $gists
do
backup $gist
done
page=$(( page + 1 ))
retries=0
done
echo "No gists found (anymore). Not trying again."
exit 0