repo-cloner/repo_cloner/lib/cred_helper.py
Václav Valíček 1fef7bc404
New behavior, new tests, added wizzard and processor
Signed-off-by: Václav Valíček <valicek1994@gmail.com>
2022-08-07 21:44:31 +02:00

86 lines
2.3 KiB
Python

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(config_dir: str):
# create mockup repo
git_config = Path(config_dir).joinpath("git")
config_file = git_config.joinpath("config")
path: str = config_file.as_posix()
log.debug(f"CFG config path: {path}")
if not git_config.is_dir():
log.debug(f"CFG Creating config dir")
git_config.mkdir()
cred_store: str = os.path.join(config_dir, "auth", "git-credentials")
ssh_identity: str = os.path.join(config_dir, "auth", "ssh", "identity")
with GitConfigParser(path, read_only = False) as cfgw:
# github personal token
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"
)