all repos — github-backup-script @ da780fd7e6f8a66298a6042cb8f85acc64163439

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
22github_user = get_config("github_username")
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_name = r.name
32    repo_path = Path(join(repo_dir, repo_name + ".git"))
33    if repo_path.exists():
34        return
35        logger.info("Updating " + repo_name)
36        repo = Repo(repo_path)
37        repo.remote().fetch("+refs/heads/*:refs/heads/*")
38        return repo
39    url = f"https://{github_user}:{github_token}@github.com/{r.owner.login}/{repo_name}.git"
40    logger.info("Cloning " + repo_name)
41    return Repo.clone_from(url, repo_path, bare=True)
42
43results = [ handle_repo(repo) for repo in repos if repo.name not in blacklist ]
44logger.info(results)