Skip to content

Instantly share code, notes, and snippets.

@henri
Forked from SpotlightKid/clone-gists.py
Created August 3, 2021 23:12
Show Gist options
  • Save henri/1795817c1b44d0182d4df57aef7da40e to your computer and use it in GitHub Desktop.
Save henri/1795817c1b44d0182d4df57aef7da40e to your computer and use it in GitHub Desktop.
Clone all gists of GitHub username given on the command line.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Clone all gists of GitHub user with given username.
Clones all gist repos into the current directory, using the gist id as the
directory name. If the directory already exists as a git repo, try to perform a
'git pull' in it.
"""
import argparse
import sys
from os.path import exists, join
from subprocess import CalledProcessError, check_call
import requests
def main(args=None):
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("username", help="GitHub username")
ap.add_argument("token", nargs='?', help="GitHub auth token")
args = ap.parse_args(args)
url = 'https://api.github.com/users/{}/gists'.format(args.username)
headers = {"Authorization": "token " + args.token} if args.token else {}
req = requests.get(url, headers=headers)
if req.status_code == 200:
for gist in req.json():
try:
if exists(join(gist['id'], '.git')):
check_call(['git', 'pull', '-v'], cwd=gist['id'])
else:
check_call(['git', 'clone', gist['git_pull_url']])
except CalledProcessError:
print("*** ERROR cloning/updating gist {id}. "
"Please check output.".format(**gid))
except KeyboardInterrupt:
break
else:
return "Error reponse: {}".format(req.json().get('message'))
if __name__ == '__main__':
sys.exit(main() or 0)
#!/bin/bash
#
# replace gist git repo remote origin https URL with SSH one.
#
for d in *; do
if [ -d "$d/.git" ]; then
pushd "$d"
url="$(git remote get-url origin)"
newurl="$(echo $url | sed -e 's|https://|git@|;s|\.com/|.com:|')"
if [ "x$url" != "x$newurl" ]; then
git remote remove origin && git remote add origin "$newurl"
git pull origin master
git branch --set-upstream-to=origin/master master
fi
popd
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment