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_user = get_config("github_username")
24github_token = get_config("github_auth_token")
25repo_dir = get_config("repo_dir")
26blacklist = set(get_config("blacklist", []))
27
28g = Github(auth=Auth.Token(github_token))
29repos = g.get_user().get_repos()
30
31def handle_repo(r):
32 repo_name = r.name
33 repo_path = Path(join(repo_dir, repo_name + ".git"))
34 if repo_path.exists():
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)