#!/usr/bin/env python3 import os import argparse import tempfile import logging from pathlib import Path from git import Repo DEFAULT_GIT_REPO = "git@github.com:YunoHost/apps" class TemporaryPath(Path): """ Just a helper to return agnostically a Path or a TemporaryDirectory """ def __init__(self, *args, **kwargs): self.temporary_directory = tempfile.TemporaryDirectory(*args, **kwargs) Path.__init__(self, self.temporary_directory.name) def with_segments(self, *pathsegments): """ We need to overload this method because it calls type(self) but we don't want to create multiple TemporaryPaths. """ return Path(*pathsegments) APPS_REPO_DIR: TemporaryPath | None = None def add_args(parser: argparse.ArgumentParser, required: bool = True, allow_temp: bool = True) -> None: env_apps_dir_str = os.environ.get("YNH_APPS_DIR") env_apps_dir = Path(env_apps_dir_str) if env_apps_dir_str is not None else None repo_group = parser.add_mutually_exclusive_group(required=required) if allow_temp: repo_group.add_argument("-c", "--apps-repo", type=str, default=DEFAULT_GIT_REPO, help="Git url to clone the 'apps' repository") repo_group.add_argument("-d", "--apps-dir", type=Path, help="Path to an existing 'apps' repository", default=env_apps_dir) def from_args(args: argparse.Namespace | None) -> Path: global APPS_REPO_DIR if APPS_REPO_DIR is not None: return APPS_REPO_DIR assert args is not None if args.apps_dir is not None: APPS_REPO_DIR = args.apps_dir return APPS_REPO_DIR if args.apps_repo is not None: tmpdir = TemporaryPath(prefix="yunohost_apps_") logging.info("Cloning the 'apps' repository...") repo = Repo.clone_from(args.apps_repo, to_path=tmpdir) assert repo.working_tree_dir is not None APPS_REPO_DIR = tmpdir return APPS_REPO_DIR raise RuntimeError("You need to pass either --apps-repo or --apps-dir!")