jw-pkg/src/python/jw/pkg/cmds/projects/CmdGetAuthInfo.py
Jan Lindemann f687ded1a6
App.find_dir(): Allow return value None
Allow find_dir() to return None in case it couldn't find a directory,
that's a legal outcome. Add a boolean parameter "throw" to support
throwing an exception if the existence needs to be asserted.

It would probably be nicer for the type checkers to split this up
into a throwing and non-throwing function. Postponed.

Signed-off-by: Jan Lindemann <jan@janware.com>
2026-06-01 20:22:09 +02:00

96 lines
3.1 KiB
Python

from __future__ import annotations
import os
import re
from ...lib.log import DEBUG, log
from ...lib.Uri import Uri
from .Cmd import Cmd, Parent
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from argparse import ArgumentParser, Namespace
class CmdGetAuthInfo(Cmd): # export
def __init__(self, parent: Parent) -> None:
super().__init__(
parent,
'get-auth-info',
help = 'Try to retrieve authentication information from the source tree',
)
def add_arguments(self, parser: ArgumentParser) -> None:
super().add_arguments(parser)
parser.add_argument(
'--only-values',
default = False,
action = 'store_true',
help = 'Don\'t prefix values by "<field-name>="',
)
parser.add_argument(
'--username',
default = False,
action = 'store_true',
help = 'Show user name'
)
parser.add_argument(
'--password',
default = False,
action = 'store_true',
help = 'Show password'
)
parser.add_argument(
'--remote-owner-base',
default = False,
action = 'store_true',
help = 'Show remote base URL for owner jw-pkg was cloned from',
)
parser.add_argument(
'--remote-base',
default = False,
action = 'store_true',
help = 'Show remote base URL',
)
async def _run(self, args: Namespace) -> None:
keys = ['username', 'password']
# --- Milk jw-pkg repo
jw_pkg_dir = self.app.find_dir('jw-pkg', pretty = False)
if jw_pkg_dir is None:
log(DEBUG, 'Can\'t find jw-pkg directory')
return None
if not os.path.isdir(jw_pkg_dir + '/.git'):
log(DEBUG, f'jw-pkg directory is not a Git repo: {jw_pkg_dir}')
return None
git_result = await self.app.exec_context.run(
['git', '-C', jw_pkg_dir, 'remote', '-v']
)
result: dict[str, str] = {}
for line in git_result.stdout_str.splitlines():
name, url, typ = re.split(r'\s+', line)
if name == 'origin' and typ in [
'(pull)',
'(fetch)',
]: # TODO: Use other remotes, too?
parsed = Uri(url)
for key in keys:
result[key] = getattr(parsed, key)
base = parsed.to_string
base = re.sub(r'/jw-pkg', '', base)
base = re.sub(r'/proj$', '', base)
base = re.sub(r'/proj$', '', base)
result['remote_owner_base'] = base
result['remote_base'] = os.path.dirname(base)
break
# --- Print results
for key, val in result.items():
if not getattr(args, key, None):
continue
if val is None:
continue
if args.only_values:
print(val)
continue
print(f'{key}="{val}"')