from git import Repo, GitConfigParser import logging import os from typing import Optional, List from pathlib import Path log = logging.getLogger("rc.cfghelper") token: Optional[str] = None def gen_gh_token_candidates() -> List[Path]: return [ Path(os.getcwd()).joinpath(".gh-token"), Path(os.getenv("HOME")).joinpath(".config", "gh-token"), Path("/etc").joinpath("cloner-gh-token"), ] def init_gh_token(): for candidate in gen_gh_token_candidates(): log.debug(f"Loading gh-candidate candidate {candidate.as_posix()}") load_gh_token(candidate) if token: log.info(f"Token succesfully loaded") break def load_gh_token(path: Path): global token log.info(f"Loading secret github token") if not path.is_file(): log.warning(f"Token load did not pass - file not found") return # load token token = path.read_text().strip() def config_try_override(config_writer: GitConfigParser, section: str, option: str, value: str): if section not in config_writer.sections(): log.debug(f"CFG Creating section: {section}") config_writer.add_section(section) if not config_writer.has_option(section, option): log.debug(f"CFG Creating option: {option}") config_writer.add_value(section, option, "") log.debug(f"Setting {section}.{option} = {value}") config_writer.set(section, option, value) def prepare_git_auth(repo: str, config_dir): log.debug(f"CFG: Opening repo {repo}") repo = Repo(repo) path: str = repo._get_config_path("user") log.debug(f"CFG config path: {path}") path = os.path.dirname(path) log.debug(f"CFG parent path: {path}") if not os.path.isdir(path): log.debug(f"CFG Creating config dir") os.mkdir(path) cred_store: str = os.path.join(path, "git-credentials") ssh_identity: str = os.path.join(config_dir, "ssh", "identity") with repo.config_writer("user") as cfgw: # github personal token # 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 if token: config_try_override( cfgw, f"url \"https://{token}:x-oauth-basic@github.com/\"", "insteadOf", "https://github.com/" ) # https credential store log.debug(f"Writing credential store setting") config_try_override(cfgw, "credential", "helper", f"store --file={cred_store}") # ssh key log.debug(f"Writing SSH cert path") config_try_override( cfgw, "core", "sshcommand", f"ssh -i {ssh_identity} -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o BatchMode=yes -q" )