Skip to content

Instantly share code, notes, and snippets.

@yuitest
Last active January 1, 2016 23:29
Show Gist options
  • Save yuitest/8217190 to your computer and use it in GitHub Desktop.
Save yuitest/8217190 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
from __future__ import unicode_literals, print_function
import json
import argparse
import os
import sys
import logging
from subprocess import check_output
from urllib import urlopen
class GistBackup(object):
@classmethod
def logger(cls, logger_name='gist_backup'):
return logging.getLogger(logger_name)
@classmethod
def list_api_url(
cls, username,
base='https://api.github.com/users/{username}/gists'
):
return base.format(username=username)
@classmethod
def fetch_list(cls, username):
url = cls.list_api_url(username)
gist_list = json.load(urlopen(url))
return gist_list
@classmethod
def backup(cls, gist_info):
logger = cls.logger()
id_ = gist_info['id']
pull_url = gist_info['git_pull_url']
if os.path.exists(id_):
logger.info('update: {}'.format(id_))
out = check_output(['git', 'pull'], cwd=id_)
logger.debug(out)
else:
logger.info('clone: {}'.format(id_))
out = check_output(['git', 'clone', pull_url])
logger.debug(out)
@classmethod
def backup_all(cls, github_username):
for gist_info in cls.fetch_list(github_username):
cls.backup(gist_info)
def main_setup():
parser = argparse.ArgumentParser(description='Gist backup')
parser.add_argument('username', nargs='?', help='github username')
parser.add_argument(
'destdir', nargs='?', type=os.path.abspath,
help='backup directory')
verbosity_group = parser.add_mutually_exclusive_group()
verbosity_group.add_argument('--quiet', action='store_true')
verbosity_group.add_argument('--verbose', action='store_true')
parser.set_defaults(user=os.environ['USER'], destdir=sys.path[0])
args = parser.parse_args()
logger = logging.getLogger('gist_backup')
logger.setLevel(logging.INFO)
if args.quiet:
logger.setLevel(logging.ERROR)
if args.verbose:
logger.setLevel(logging.DEBUG)
basic_handler = logging.StreamHandler()
basic_handler.setLevel(logging.DEBUG)
logger.addHandler(basic_handler)
return args
if __name__ == '__main__':
args = main_setup()
os.chdir(args.destdir)
GistBackup.backup_all(args.username)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment