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