repo-cloner/repo_cloner/lib/cred_helper.py

44 lines
1.4 KiB
Python
Raw Normal View History

from git import Repo, GitConfigParser
import logging
import os
log = logging.getLogger("rc.cfghelper")
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:
log.debug(f"Writing credential store setting")
config_try_override(cfgw, "credential", "helper", f"store --file={cred_store}")
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"
)