all repos — github-backup-script @ 5a6403d22c668e6611f481d394f7b401b9b6bda5

github_backup/__main__.py (view raw)

 1from github import Github, Auth
 2from git import Repo
 3from git.exc import GitCommandError
 4from pathlib import Path
 5from os.path import join
 6import logging, json
 7logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
 8logger = logging.getLogger(__name__)
 9logger.setLevel(logging.INFO)
10
11with open("config.json", "r") as in_file:
12    config = json.loads("".join(in_file.readlines()))
13    
14def get_config(key, default=None):
15    try:
16        return config[key]
17    except KeyError:
18        if default is None:
19            logger.error("Missing config key: {}.".format(key))
20            exit(1)
21        return default
22
23github_token = get_config("github_auth_token")
24repo_dir = get_config("repo_dir")
25blacklist = set(get_config("blacklist", []))
26
27g = Github(auth=Auth.Token(github_token))
28repos = g.get_user().get_repos()
29
30def handle_repo(r):
31    repo_path = Path(join(repo_dir, r.name + ".git"))
32    if repo_path.exists():
33        logger.info("Updating " + r.name)
34        repo = Repo(repo_path)
35        repo.remote().fetch("+refs/heads/*:refs/heads/*")
36        return repo
37    logger.info("Cloning " + r.git_url)
38    return Repo.clone_from(r.clone_url, repo_path, bare=True)
39
40results = [ handle_repo(repo) for repo in repos if repo.name not in blacklist ]
41logger.info(results)