diff --git a/alembic/env.py b/alembic/env.py index a9575b1e..eb679467 100644 --- a/alembic/env.py +++ b/alembic/env.py @@ -24,6 +24,7 @@ from wrolpi.collections.models import Collection, CollectionItem # noqa: F401 from modules.videos.models import Video, Channel # noqa: F401 from modules.archive.models import Archive # noqa: F401 from modules.zim.models import Zim, TagZimEntry, ZimSubscription # noqa: F401 +from modules.repos.models import Repository # noqa: F401 target_metadata = Base.metadata diff --git a/alembic/versions/2026_10_06_1200_repository.py b/alembic/versions/2026_10_06_1200_repository.py new file mode 100644 index 00000000..e4537267 --- /dev/null +++ b/alembic/versions/2026_10_06_1200_repository.py @@ -0,0 +1,43 @@ +"""Add the repository table for git Repos (Collections with kind='repo'). + +Revision ID: 2026_10_06_1200 +Revises: 2026_10_05_1200 +""" +import sqlalchemy as sa +from alembic import op + +import wrolpi.dates + +# revision identifiers, used by Alembic. +revision = '2026_10_06_1200' +down_revision = '2026_10_05_1200' +branch_labels = None +depends_on = None + + +def upgrade(): + op.create_table( + 'repository', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('url', sa.String(), nullable=False), + sa.Column('host', sa.String(), nullable=True), + sa.Column('owner', sa.String(), nullable=True), + sa.Column('mode', sa.String(), nullable=False), + sa.Column('branch', sa.String(), nullable=True), + sa.Column('default_branch', sa.String(), nullable=True), + sa.Column('head_sha', sa.String(), nullable=True), + sa.Column('head_date', wrolpi.dates.TZDateTime(), nullable=True), + sa.Column('head_message', sa.Text(), nullable=True), + sa.Column('last_fetch', wrolpi.dates.TZDateTime(), nullable=True), + sa.Column('size', sa.BigInteger(), nullable=True), + sa.Column('readme_path', sa.String(), nullable=True), + sa.Column('collection_id', sa.Integer(), nullable=False), + sa.ForeignKeyConstraint(['collection_id'], ['collection.id'], ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('collection_id'), + sa.UniqueConstraint('url'), + ) + + +def downgrade(): + op.drop_table('repository') diff --git a/app/src/test-fixtures.js b/app/src/test-fixtures.js index f8f8242f..7746d375 100644 --- a/app/src/test-fixtures.js +++ b/app/src/test-fixtures.js @@ -71,6 +71,7 @@ export const settingsFixture = (overrides = {}) => ({ media_directory: '/media/wrolpi', nav_color: 'violet', playlists_destination: 'playlists', + repos_destination: 'repos/%(repo_tag)s/%(repo_name)s', require_cookies_unlocked: false, require_media_mounted: false, save_ffprobe_json: true, diff --git a/conftest.py b/conftest.py index 04a24e10..a19f94f9 100644 --- a/conftest.py +++ b/conftest.py @@ -1,5 +1,6 @@ from modules.archive.conftest import * # noqa from modules.inventory.conftest import * # noqa +from modules.repos.conftest import * # noqa from modules.videos.conftest import * # noqa from modules.zim.conftest import * # noqa from wrolpi.conftest import * # noqa diff --git a/modules/__init__.py b/modules/__init__.py index 3e496d2f..0065a060 100644 --- a/modules/__init__.py +++ b/modules/__init__.py @@ -2,5 +2,6 @@ from .archive import api from .docs import api from .inventory import api from .map import api +from .repos import api from .videos import api from .zim import api, test diff --git a/modules/repos/__init__.py b/modules/repos/__init__.py new file mode 100644 index 00000000..c8a564c2 --- /dev/null +++ b/modules/repos/__init__.py @@ -0,0 +1,3 @@ +from .downloader import GitDownloader # noqa + +__all__ = [] diff --git a/modules/repos/api.py b/modules/repos/api.py new file mode 100644 index 00000000..7748aac9 --- /dev/null +++ b/modules/repos/api.py @@ -0,0 +1,97 @@ +from http import HTTPStatus + +from sanic import Request, Blueprint, response +from sanic_ext.extensions.openapi import openapi + +from wrolpi.api_utils import json_response +from wrolpi.common import wrol_mode_check, logger +from wrolpi.downloader import download_manager +from wrolpi.errors import ValidationError +from . import lib, schema +from .models import Repository + +repos_bp = Blueprint('Repos', '/api/repos') + +logger = logger.getChild(__name__) + + +@repos_bp.get('/') +@openapi.definition(summary='List all git Repos') +async def get_repos(request: Request): + repos = lib.get_repositories(request.ctx.session) + return json_response(dict(repos=repos)) + + +@repos_bp.post('/') +@openapi.definition( + summary='Add a git Repo; it will be cloned, then kept up to date', + body=schema.RepoCreateRequest, + validate=True, +) +@wrol_mode_check +async def post_repo(request: Request, body: schema.RepoCreateRequest): + session = request.ctx.session + repo = lib.create_repository( + session, + body.url, + tag_name=body.tag_name or None, + frequency=body.frequency or lib.DEFAULT_REPO_FREQUENCY, + mode=body.mode or 'full', + branch=body.branch or None, + name=body.name or None, + description=body.description or None, + ) + repo = Repository.find_by_id(session, repo.id, options=Repository.json_options()) + return json_response(dict(repo=repo.__json__()), status=HTTPStatus.CREATED) + + +@repos_bp.get('/') +@openapi.definition(summary='Get a git Repo') +async def get_repo(request: Request, repo_id: int): + repo = Repository.find_by_id(request.ctx.session, repo_id, options=Repository.json_options()) + return json_response(dict(repo=repo.__json__())) + + +@repos_bp.put('/') +@openapi.definition( + summary="Change a git Repo's settings", + body=schema.RepoUpdateRequest, + validate=True, +) +@wrol_mode_check +async def put_repo(request: Request, repo_id: int, body: schema.RepoUpdateRequest): + session = request.ctx.session + lib.update_repository(session, repo_id, description=body.description, frequency=body.frequency, + mode=body.mode, branch=body.branch) + repo = Repository.find_by_id(session, repo_id, options=Repository.json_options()) + return json_response(dict(repo=repo.__json__())) + + +@repos_bp.delete('/') +@openapi.definition(summary='Delete a git Repo. Its files are kept unless `delete_files=true`.') +@wrol_mode_check +async def delete_repo(request: Request, repo_id: int): + delete_files = request.args.get('delete_files', '').lower() in ('1', 'true', 'yes') + await lib.delete_repository(request.ctx.session, repo_id, delete_files=delete_files) + return response.empty() + + +@repos_bp.post('//update') +@openapi.definition(summary='Update a git Repo now') +@wrol_mode_check +async def post_update_repo(request: Request, repo_id: int): + session = request.ctx.session + repo = Repository.find_by_id(session, repo_id, options=Repository.json_options()) + if not (download := repo.download): + raise ValidationError('Repo has no download') + download_manager.restart_download(session, download.id) + return response.empty(HTTPStatus.NO_CONTENT) + + +@repos_bp.get('//tree') +@openapi.definition(summary="List a directory of a git Repo's files") +@openapi.parameter('path', str, 'query', description='Directory in the repo, relative to its root', required=False) +async def get_repo_tree(request: Request, repo_id: int): + repo = Repository.find_by_id(request.ctx.session, repo_id) + tree = lib.list_repo_tree(repo, request.args.get('path', '')) + return json_response(tree) diff --git a/modules/repos/conftest.py b/modules/repos/conftest.py new file mode 100644 index 00000000..39d07217 --- /dev/null +++ b/modules/repos/conftest.py @@ -0,0 +1,87 @@ +import os +import pathlib +import subprocess +from typing import Callable + +import pytest +from mock import mock + +from modules.repos import lib +from modules.repos.downloader import GitDownloader +from wrolpi.downloader import DownloadManager + +# Commits made by the tests have a fixed identity and do not read the developer's git config. +TEST_GIT_ENV = dict( + GIT_AUTHOR_NAME='WROLPi Test', GIT_AUTHOR_EMAIL='test@example.com', + GIT_COMMITTER_NAME='WROLPi Test', GIT_COMMITTER_EMAIL='test@example.com', + GIT_CONFIG_NOSYSTEM='1', GIT_CONFIG_GLOBAL=os.devnull, +) + + +class GitRemote: + """A local repo which the Repos module sees as `https://git.example.com//`.""" + + def __init__(self, path: pathlib.Path, url: str): + self.path = path + self.url = url + + def git(self, *args: str) -> str: + env = dict(os.environ, **TEST_GIT_ENV) + result = subprocess.run(['git', *args], cwd=self.path, env=env, check=True, capture_output=True) + return result.stdout.decode().strip() + + def commit(self, files: dict, message: str = 'Commit') -> str: + """Write `files` ({relative path: contents}), commit them, return the commit's sha.""" + for name, contents in files.items(): + file = self.path / name + file.parent.mkdir(parents=True, exist_ok=True) + file.write_text(contents) + self.git('add', '--all') + self.git('commit', '--quiet', '-m', message) + return self.git('rev-parse', 'HEAD') + + @property + def head(self) -> str: + return self.git('rev-parse', 'HEAD') + + +@pytest.fixture +def git_remote_factory(tmp_path_factory) -> Callable[..., GitRemote]: + """Create local git repos which are cloned over `https://git.example.com/...` URLs. + + git's `url..insteadOf` rewrites the https URL to the local path, and `file://` is allowed for the test, + so the Repos module runs the same commands it runs in production.""" + remotes = dict() + # Outside the media directory (which is `tmp_path`). + remotes_directory = tmp_path_factory.mktemp('remotes') + + def git_env(): + env = original_git_env() + env['GIT_CONFIG_COUNT'] = str(len(remotes)) + for idx, (url, path) in enumerate(remotes.items()): + env[f'GIT_CONFIG_KEY_{idx}'] = f'url.file://{path}.insteadOf' + env[f'GIT_CONFIG_VALUE_{idx}'] = url + return env + + original_git_env = lib.git_env + + def factory(name: str = 'example', owner: str = 'owner', branch: str = 'main', + files: dict = None) -> GitRemote: + path = remotes_directory / owner / name + path.mkdir(parents=True) + url = f'https://git.example.com/{owner}/{name}' + remote = GitRemote(path, url) + remote.git('init', '--quiet', f'--initial-branch={branch}') + remote.commit(files or {'README.md': f'# {name}\n\nThe {name} repo.\n'}, 'Initial commit') + remotes[url] = path + return remote + + with mock.patch('modules.repos.lib.ALLOWED_PROTOCOLS', ('https', 'file')), \ + mock.patch('modules.repos.downloader.git_env', git_env): + yield factory + + +@pytest.fixture +def repos_download_manager(test_download_manager) -> DownloadManager: + test_download_manager.register_downloader(GitDownloader()) + yield test_download_manager diff --git a/modules/repos/downloader.py b/modules/repos/downloader.py new file mode 100644 index 00000000..a3dc241f --- /dev/null +++ b/modules/repos/downloader.py @@ -0,0 +1,203 @@ +import asyncio +import pathlib +import re +from dataclasses import dataclass +from datetime import datetime +from typing import Optional + +from sqlalchemy.orm import Session + +from wrolpi.common import logger +from wrolpi.dates import now +from wrolpi.downloader import Downloader, Download, DownloadContext, DownloadResult, make_progress_callback +from wrolpi.errors import DownloadError +from .lib import git_command, git_env, find_readme, get_repo_size +from .models import Repository + +__all__ = ['GitDownloader', 'git_downloader', 'PreparedRepo', 'ExecutedRepo', 'parse_git_progress'] + +logger = logger.getChild(__name__) + +# e.g. "Receiving objects: 45% (123/456), 1.20 MiB | 1.00 MiB/s" +GIT_PROGRESS_RE = re.compile(r'^(?:remote: )?(?P[A-Za-z ]+):\s+(?P\d+)%') + +# Full mode keeps every branch of the remote as `origin/`. +FULL_REFSPEC = '+refs/heads/*:refs/remotes/origin/*' + + +def parse_git_progress(line: str) -> Optional[dict]: + if match := GIT_PROGRESS_RE.match(line): + return dict(stage=match.group('stage').strip(), percent=int(match.group('percent'))) + return None + + +@dataclass +class PreparedRepo: + repository_id: int + url: str + directory: pathlib.Path + mode: str + branch: Optional[str] + + +@dataclass +class ExecutedRepo: + repository_id: int + default_branch: Optional[str] + head_sha: str + head_date: datetime + head_message: str + size: int + readme_path: Optional[str] + + +class GitCancelled(Exception): + """A git command was cancelled; carries the cancel_wrapper's DownloadResult.""" + + def __init__(self, result: DownloadResult): + super().__init__(result.error) + self.result = result + + +class GitDownloader(Downloader): + """Clones a git repo into its Repo's directory, or updates the existing clone. + + Repos are mirrors: local changes are discarded by every update. Upstream disappearing never deletes the + local copy; the download is deferred with git's error.""" + name = 'git' + pretty_name = 'Git' + # Repos are added on the Repos page, not the generic download form. + listable = False + + def prepare_download(self, session: Session, download: Download) -> PreparedRepo: + repo = Repository.get_by_collection_id(session, download.collection_id) if download.collection_id else None + if not repo: + raise DownloadError(f'No Repo for this download, add it on the Repos page: {download.url}') + directory = repo.collection.get_or_set_directory(session) + return PreparedRepo(repository_id=repo.id, url=repo.url, directory=directory, mode=repo.mode, + branch=repo.branch) + + async def _git(self, download: Download, ctx: DownloadContext, cwd: pathlib.Path, *args, + config: tuple = (), progress: bool = False, check: bool = True) -> str: + """Run a git command, return its output (stdout and stderr).""" + cmd = git_command(*args, config=config) + stdout_callback = make_progress_callback(ctx.report_progress, parse_git_progress) if progress else None + result = await self.process_runner(download, cmd, cwd, env=git_env(), merge_stderr=True, + stdout_callback=stdout_callback, start_new_session=True, ctx=ctx) + if isinstance(result, DownloadResult): + raise GitCancelled(result) + output = result.stdout.decode(errors='replace').strip() + if check and result.return_code != 0: + raise DownloadError(f'git {args[0]} failed ({result.return_code}): {output}') + return output + + async def _default_branch(self, download: Download, ctx: DownloadContext, prepared: PreparedRepo) -> str: + """Ask the remote for its default branch. This fails quickly when the upstream is gone.""" + output = await self._git(download, ctx, prepared.directory.parent, 'ls-remote', '--symref', prepared.url, + 'HEAD') + for line in output.splitlines(): + if line.startswith('ref: refs/heads/') and line.endswith('\tHEAD'): + return line[len('ref: refs/heads/'):-len('\tHEAD')] + raise DownloadError(f'Repo has no default branch (is it empty?): {prepared.url}') + + async def _clone(self, download: Download, ctx: DownloadContext, prepared: PreparedRepo, branch: str): + directory = prepared.directory + if directory.is_dir() and any(directory.iterdir()): + raise DownloadError(f'Refusing to clone into a directory which is not empty: {directory}') + directory.mkdir(parents=True, exist_ok=True) + + args = ['clone', '--progress', '--branch', branch] + if prepared.mode == 'snapshot': + args.extend(['--depth', '1', '--single-branch', '--no-tags']) + args.extend(['--', prepared.url, str(directory)]) + await self._git(download, ctx, directory.parent, *args, progress=True) + + async def _update(self, download: Download, ctx: DownloadContext, prepared: PreparedRepo, branch: str): + directory = prepared.directory + git = lambda *args, **kwargs: self._git(download, ctx, directory, *args, **kwargs) # noqa: E731 + + old_head = await git('rev-parse', '--verify', '--quiet', 'HEAD', check=False) + if prepared.mode == 'snapshot': + await git('fetch', '--progress', '--depth', '1', '--no-tags', 'origin', branch, progress=True) + target = 'FETCH_HEAD' + else: + # Fetch every branch and tag. Branches deleted upstream are kept (no --prune). + await git('config', 'remote.origin.fetch', FULL_REFSPEC) + args = ['fetch', '--progress', '--tags', '--force', 'origin'] + if (directory / '.git/shallow').exists(): + # This was a snapshot; get the whole history. + args.insert(1, '--unshallow') + await git(*args, progress=True) + target = f'refs/remotes/origin/{branch}' + + new_head = await git('rev-parse', '--verify', target) + if prepared.mode == 'full' and old_head and old_head != new_head: + if not await self._is_ancestor(download, ctx, directory, old_head, new_head): + # Upstream rewrote history (force push). Keep what we had. + backup = f'refs/wrolpi/backup/{now().strftime("%Y%m%d%H%M%S")}' + await git('update-ref', backup, old_head) + logger.warning(f'Repo {prepared.url} history was rewritten; saved old HEAD as {backup}') + + await git('checkout', '--force', '-B', branch, new_head) + await git('clean', '-ffdx') + if prepared.mode == 'snapshot': + # Shallow fetches leave the previous commits behind; drop them. + await git('gc', '--prune=now', '--quiet', + config=('gc.reflogExpire=now', 'gc.reflogExpireUnreachable=now')) + + async def _is_ancestor(self, download: Download, ctx: DownloadContext, directory: pathlib.Path, + ancestor: str, descendant: str) -> bool: + cmd = git_command('merge-base', '--is-ancestor', ancestor, descendant) + result = await self.process_runner(download, cmd, directory, env=git_env(), merge_stderr=True, ctx=ctx) + if isinstance(result, DownloadResult): + raise GitCancelled(result) + return result.return_code == 0 + + async def execute_download(self, prepared: PreparedRepo, ctx: DownloadContext, + download: Download = None) -> ExecutedRepo | DownloadResult: + download = download if download is not None else Download(url=prepared.url) + directory = prepared.directory + directory.parent.mkdir(parents=True, exist_ok=True) + + try: + default_branch = await self._default_branch(download, ctx, prepared) + branch = prepared.branch or default_branch + if (directory / '.git').is_dir(): + await self._update(download, ctx, prepared, branch) + else: + await self._clone(download, ctx, prepared, branch) + + head = await self._git(download, ctx, directory, 'log', '-1', '--format=%H%x00%cI%x00%s') + except GitCancelled as e: + return e.result + finally: + ctx.clear_progress() + + head_sha, head_date, head_message = head.split('\x00', 2) + size = await asyncio.to_thread(get_repo_size, directory) + return ExecutedRepo( + repository_id=prepared.repository_id, + default_branch=default_branch, + head_sha=head_sha, + head_date=datetime.fromisoformat(head_date), + head_message=head_message, + size=size, + readme_path=find_readme(directory), + ) + + def finalize_download(self, session: Session, download: Download, executed: ExecutedRepo) -> DownloadResult: + repo = session.query(Repository).filter_by(id=executed.repository_id).one_or_none() + if not repo: + return DownloadResult(success=False, error='Repo was deleted while downloading') + repo.default_branch = executed.default_branch + repo.head_sha = executed.head_sha + repo.head_date = executed.head_date + repo.head_message = executed.head_message + repo.size = executed.size + repo.readme_path = executed.readme_path + repo.last_fetch = now() + logger.info(f'Updated repo {repo.url} to {executed.head_sha}') + return DownloadResult(success=True, location=repo.location) + + +git_downloader = GitDownloader() diff --git a/modules/repos/errors.py b/modules/repos/errors.py new file mode 100644 index 00000000..28dc94b5 --- /dev/null +++ b/modules/repos/errors.py @@ -0,0 +1,21 @@ +from http import HTTPStatus + +from wrolpi.errors import APIError + + +class UnknownRepo(APIError): + code = 'UNKNOWN_REPO' + summary = 'Unable to find the repo' + status_code = HTTPStatus.NOT_FOUND + + +class InvalidRepo(APIError): + code = 'INVALID_REPO' + summary = 'The repo is invalid' + status_code = HTTPStatus.BAD_REQUEST + + +class RepoConflict(APIError): + code = 'REPO_CONFLICT' + summary = 'The repo conflicts with an existing repo' + status_code = HTTPStatus.CONFLICT diff --git a/modules/repos/lib.py b/modules/repos/lib.py new file mode 100644 index 00000000..f4648caa --- /dev/null +++ b/modules/repos/lib.py @@ -0,0 +1,523 @@ +import asyncio +import os +import pathlib +import re +import shutil +from dataclasses import dataclass, field +from typing import List, Optional +from urllib.parse import urlparse + +from sqlalchemy import func +from sqlalchemy.orm import Session + +from wrolpi.cmd import GIT_BIN +from wrolpi.collections.models import Collection +from wrolpi.common import ConfigFile, get_media_directory, get_relative_to_media_directory, logger, \ + escape_file_name, background_task +from wrolpi.db import get_db_session +from wrolpi.downloader import DownloadFrequency, save_downloads_config +from wrolpi.errors import UnknownDirectory, ValidationError +from wrolpi.events import Events +from wrolpi.switches import register_switch_handler, ActivateSwitchMethod +from wrolpi.tags import Tag +from .errors import InvalidRepo, RepoConflict +from .models import Repository, REPO_MODES + +logger = logger.getChild(__name__) + +__all__ = ['ParsedRepoURL', 'parse_repo_url', 'repo_url_key', 'git_command', 'git_env', 'create_repository', + 'update_repository', 'delete_repository', 'get_repositories', 'list_repo_tree', 'find_readme', + 'repo_destination_variables', 'ReposConfig', 'repos_config', 'get_repos_config', 'save_repos_config', + 'import_repos_config', 'DEFAULT_REPO_FREQUENCY'] + +DEFAULT_REPO_FREQUENCY = DownloadFrequency.weekly.value + +# The only transports git may use. Submodules and redirects cannot reach `file://`, `ext::`, ssh, etc. +ALLOWED_PROTOCOLS = ('https',) + +# README files in the order they are preferred; matched case-insensitively. +README_NAMES = ('readme.md', 'readme.markdown', 'readme.rst', 'readme.txt', 'readme') + +# A forge's web URL of a branch: GitHub `/owner/repo/tree/`, GitLab `/group/repo/-/tree/`. +TREE_URL_RE = re.compile(r'^(?P/.+?)(?:/-)?/tree/(?P[^?#]+)$') + + +@dataclass +class ParsedRepoURL: + url: str + host: str + owner: str + name: str + branch: Optional[str] = None + + +def parse_repo_url(url: str) -> ParsedRepoURL: + """Validate an https git URL and split it into its parts. + + A forge's branch URL (e.g. `https://github.com/owner/repo/tree/dev`) becomes the repo URL and its branch.""" + url = (url or '').strip() + parsed = urlparse(url) + if parsed.scheme not in ALLOWED_PROTOCOLS: + raise InvalidRepo('Only https:// repo URLs are supported') + if parsed.username or parsed.password: + # Credentials would be saved in the configs. + raise InvalidRepo('Repo URL must not contain a username or password') + if not parsed.hostname: + raise InvalidRepo('Repo URL must have a host') + if parsed.query or parsed.fragment: + raise InvalidRepo('Repo URL must not contain a query or fragment') + + path = parsed.path.rstrip('/') + branch = None + if match := TREE_URL_RE.match(path): + path, branch = match.group('repo'), match.group('branch') + + parts = [i for i in path.split('/') if i] + if not parts: + raise InvalidRepo('Repo URL must have a path') + name = parts[-1].removesuffix('.git') + if not name: + raise InvalidRepo('Repo URL must have a name') + owner = '/'.join(parts[:-1]) + + host = parsed.hostname.lower() + netloc = f'{host}:{parsed.port}' if parsed.port else host + return ParsedRepoURL(url=f'{parsed.scheme}://{netloc}{path}', host=host, owner=owner, name=name, branch=branch) + + +def repo_url_key(url: str) -> str: + """Two URLs of the same repo have the same key (`.git` suffix and case of the host are ignored).""" + parsed = urlparse(url.strip()) + return f'{(parsed.hostname or "").lower()}{parsed.path.rstrip("/").removesuffix(".git")}' + + +def git_command(*args, config: tuple = ()) -> tuple: + """Build a git command that is safe to run against an untrusted remote repo.""" + if not GIT_BIN: + raise InvalidRepo('git is not installed') + safety = [ + '-c', 'protocol.allow=never', + *(i for p in ALLOWED_PROTOCOLS for i in ('-c', f'protocol.{p}.allow=always')), + # Never run the repo's hooks. + '-c', 'core.hooksPath=/dev/null', + # A symlink in a repo could point outside the repo (e.g. /etc/shadow), and media files are served. + # Symlinks are checked out as plain files containing the link's target. + '-c', 'core.symlinks=false', + '-c', 'core.fsmonitor=false', + # The media directory may be owned by another user (e.g. a Docker volume). + '-c', 'safe.directory=*', + '-c', 'credential.helper=', + '-c', 'submodule.recurse=false', + ] + for i in config: + safety.extend(['-c', i]) + return GIT_BIN, *safety, *args + + +def git_env() -> dict: + """Environment for git: never prompt for credentials, ignore the user's and system's git configs.""" + env = dict(os.environ) + env.update( + GIT_TERMINAL_PROMPT='0', + GIT_ASKPASS='true', + SSH_ASKPASS='true', + GIT_CONFIG_NOSYSTEM='1', + GIT_CONFIG_GLOBAL=os.devnull, + GIT_LFS_SKIP_SMUDGE='1', + LC_ALL='C', + ) + return env + + +def find_readme(directory: pathlib.Path) -> Optional[str]: + """Return the name of the preferred README file in `directory`, if any.""" + try: + files = {i.name.lower(): i.name for i in directory.iterdir() if i.is_file() and not i.is_symlink()} + except FileNotFoundError: + return None + for name in README_NAMES: + if name in files: + return files[name] + return None + + +def repo_destination_variables(collection: Collection) -> dict: + """Variables for `repos_destination` which are stored on the Repository (not the Collection).""" + session = Session.object_session(collection) + repo = Repository.get_by_collection_id(session, collection.id) if session and collection.id else None + return dict( + repo_owner=escape_file_name(repo.owner) if repo and repo.owner else '', + repo_host=escape_file_name(repo.host) if repo and repo.host else '', + ) + + +def get_repository_by_url(session: Session, url: str) -> Optional[Repository]: + key = repo_url_key(url) + for id_, repo_url in session.query(Repository.id, Repository.url): + if repo_url_key(repo_url) == key: + return session.query(Repository).filter_by(id=id_).one() + return None + + +def _validate_mode(mode: str): + if mode not in REPO_MODES: + raise ValidationError(f'Repo mode must be one of {", ".join(REPO_MODES)}') + + +def _validate_frequency(frequency: int): + if not isinstance(frequency, int) or frequency <= 0: + raise ValidationError('Repo frequency must be a positive number of seconds') + + +def create_repository(session: Session, url: str, tag_name: str = None, frequency: int = DEFAULT_REPO_FREQUENCY, + mode: str = 'full', branch: str = None, name: str = None, description: str = None, + directory: pathlib.Path = None) -> Repository: + """Create a Repo (Collection + Repository + recurring Download). The download clones it.""" + parsed = parse_repo_url(url) + _validate_mode(mode) + _validate_frequency(frequency) + branch = branch or parsed.branch or None + name = (name or parsed.name).strip() + + if get_repository_by_url(session, parsed.url): + raise RepoConflict(f'A repo with this URL already exists: {parsed.url}') + if session.query(Collection).filter_by(kind='repo', name=name).one_or_none(): + suggestion = f'{parsed.owner.replace("/", "-")}-{name}' if parsed.owner else f'{parsed.host}-{name}' + raise RepoConflict(f'A repo named {name!r} already exists. Try the name {suggestion!r}') + + tag = Tag.get_or_create_tag(session, tag_name) if tag_name else None + collection = Collection(kind='repo', name=name, description=description, tag=tag) + session.add(collection) + session.flush([collection]) + repo = Repository(url=parsed.url, host=parsed.host, owner=parsed.owner, mode=mode, branch=branch, + collection_id=collection.id) + session.add(repo) + session.flush([repo]) + + directory = directory or collection.format_destination(tag_name) + if not str(directory.resolve()).startswith(str(get_media_directory().resolve()) + '/'): + raise InvalidRepo('Repo directory must be in the media directory') + if session.query(Collection).filter(Collection.directory == directory, Collection.id != collection.id).first(): + raise RepoConflict(f'Another collection already uses the directory {get_relative_to_media_directory(directory)}') + collection.directory = directory + + download = collection.get_or_create_download(session, parsed.url, frequency, downloader_name='git') + # The Download may already exist (e.g. imported from download_manager.yaml). + download.frequency = frequency + session.commit() + + save_repos_config.activate_switch() + save_downloads_config.activate_switch() + return repo + + +def update_repository(session: Session, repo_id: int, description: str = None, frequency: int = None, + mode: str = None, branch: str = None) -> Repository: + """Change a Repo's settings. An empty `branch` follows the remote's default branch.""" + repo = Repository.find_by_id(session, repo_id) + if description is not None: + repo.collection.description = description or None + if mode is not None: + _validate_mode(mode) + repo.mode = mode + if branch is not None: + repo.branch = branch.strip() or None + if frequency is not None: + _validate_frequency(frequency) + if download := repo.download: + download.frequency = frequency + else: + repo.collection.get_or_create_download(session, repo.url, frequency, downloader_name='git') + session.commit() + + save_repos_config.activate_switch() + save_downloads_config.activate_switch() + return repo + + +def _delete_repository(session: Session, repo: Repository): + collection = repo.collection + for download in list(collection.downloads): + session.delete(download) + session.delete(collection) + session.flush() + + +async def delete_repository(session: Session, repo_id: int, delete_files: bool = False) -> dict: + """Delete a Repo and its Download. The repo's files are kept unless `delete_files`.""" + repo = Repository.find_by_id(session, repo_id) + directory = repo.directory + result = dict(id=repo.id, name=repo.name, directory=str(get_relative_to_media_directory(directory))) + _delete_repository(session, repo) + session.commit() + + if delete_files and directory and directory.is_dir(): + media_directory = get_media_directory().resolve() + if directory.resolve() == media_directory or media_directory not in directory.resolve().parents: + raise InvalidRepo('Refusing to delete a directory outside the media directory') + background_task(_delete_directory(directory)) + + save_repos_config.activate_switch() + save_downloads_config.activate_switch() + return result + + +async def _delete_directory(directory: pathlib.Path): + await asyncio.to_thread(shutil.rmtree, directory) + logger.info(f'Deleted repo directory {directory}') + + +def get_repositories(session: Session) -> List[dict]: + repos = session.query(Repository).options(*Repository.json_options()) \ + .join(Collection, Collection.id == Repository.collection_id) \ + .order_by(func.lower(Collection.name)).all() + return [i.__json__() for i in repos] + + +@dataclass +class RepoTreeEntry: + name: str + path: str + is_dir: bool + size: Optional[int] = None + + def __json__(self) -> dict: + return dict(name=self.name, path=self.path, is_dir=self.is_dir, size=self.size) + + +def list_repo_tree(repo: Repository, path: str = '') -> dict: + """List one directory of a Repo's checked out files, directories first. `.git` is hidden.""" + root = repo.directory + if not root or not root.is_dir(): + raise UnknownDirectory('Repo has not been downloaded') + root = root.resolve() + + path = (path or '').strip('/') + directory = (root / path).resolve() + if directory != root and root not in directory.parents: + raise InvalidRepo('Path is not in the repo') + if not directory.is_dir(): + raise UnknownDirectory(f'No directory {path!r} in repo') + + entries = [] + for entry in directory.iterdir(): + if entry.name == '.git' or entry.is_symlink(): + continue + relative = str(entry.relative_to(root)) + if entry.is_dir(): + entries.append(RepoTreeEntry(name=entry.name, path=relative, is_dir=True)) + else: + entries.append(RepoTreeEntry(name=entry.name, path=relative, is_dir=False, size=entry.stat().st_size)) + entries.sort(key=lambda i: (not i.is_dir, i.name.lower())) + + readme = find_readme(directory) + return dict( + path=path, + entries=[i.__json__() for i in entries], + readme_path=str((directory / readme).relative_to(root)) if readme else None, + ) + + +def get_repo_size(directory: pathlib.Path) -> int: + """Total size of every file in the repo, including `.git`.""" + total = 0 + for dir_path, _, file_names in os.walk(directory): + for name in file_names: + try: + total += os.lstat(os.path.join(dir_path, name)).st_size + except FileNotFoundError: + pass + return total + + +@dataclass +class ReposConfigValidator: + version: int = 0 + repos: List[dict] = field(default_factory=list) + + +class ReposConfig(ConfigFile): + """Config file for git Repos (Collections with kind='repo'). + + Format: + repos: + - name: kiwix-tools + url: https://github.com/kiwix/kiwix-tools + directory: repos/software/kiwix-tools + tag_name: software + mode: full + branch: null + frequency: 604800 + """ + file_name = 'repos.yaml' + validator = ReposConfigValidator + default_config = dict(version=0, repos=[]) + width = 120 + + @property + def repos(self) -> List[dict]: + return self._config.get('repos', []) + + def import_config(self, file: pathlib.Path = None, send_events=False): + """Import Repos from the config into the database.""" + file = file or self.get_file() + file_str = str(self.get_relative_file()) + + # A missing config is not an empty config; never delete Repos because a file is lost. + if not file.is_file(): + logger.info(f'No repos config file, skipping import: {file_str}') + self.successful_import = True + return + + super().import_config(file, send_events) + repos_data = self._config.get('repos', []) + + # An empty repos list never deletes DB records. Deleting all repos is done through the API. + if not repos_data: + logger.info(f'No repos in config, preserving existing DB repos: {file_str}') + self.successful_import = True + return + + try: + with get_db_session(commit=True) as session: + imported_ids = set() + for data in repos_data: + try: + repo = self._import_repo(session, data) + except Exception as e: + logger.error(f'Failed to import repo from config: {data}', exc_info=e) + self.import_skipped += 1 + continue + imported_ids.add(repo.id) + + for repo in session.query(Repository).all(): + if repo.id not in imported_ids: + logger.info(f'Deleting repo {repo.name!r} (no longer in config)') + _delete_repository(session, repo) + + logger.info(f'Imported {len(imported_ids)} repos from {file_str}') + self.successful_import = True + except Exception as e: + self.successful_import = False + message = f'Failed to import {file_str} config!' + logger.error(message, exc_info=e) + if send_events: + Events.send_config_import_failed(message) + raise + + @staticmethod + def _import_repo(session: Session, data: dict) -> Repository: + parsed = parse_repo_url(data['url']) + name = data.get('name') or parsed.name + mode = data.get('mode') or 'full' + _validate_mode(mode) + frequency = data.get('frequency') or DEFAULT_REPO_FREQUENCY + _validate_frequency(frequency) + directory = data.get('directory') + directory = get_media_directory() / directory if directory else None + tag_name = data.get('tag_name') + + repo = get_repository_by_url(session, parsed.url) + if not repo: + return create_repository(session, parsed.url, tag_name=tag_name, frequency=frequency, mode=mode, + branch=data.get('branch'), name=name, description=data.get('description'), + directory=directory) + + collection = repo.collection + collection.name = name + collection.description = data.get('description') + collection.tag = Tag.get_or_create_tag(session, tag_name) if tag_name else None + if directory: + collection.directory = directory + repo.mode = mode + repo.branch = data.get('branch') or None + if download := repo.download: + download.frequency = frequency + else: + collection.get_or_create_download(session, repo.url, frequency, downloader_name='git') + session.flush() + return repo + + def dump_config(self, file: pathlib.Path = None, send_events=False, overwrite=False): + """Dump all Repos to the config file.""" + with get_db_session() as session: + repos = session.query(Repository).options(*Repository.json_options()) \ + .join(Collection, Collection.id == Repository.collection_id) \ + .order_by(func.lower(Collection.name)).all() + data = [] + for repo in repos: + download = repo.download + entry = dict( + name=repo.name, + url=repo.url, + directory=str(get_relative_to_media_directory(repo.directory)) if repo.directory else None, + tag_name=repo.tag_name, + description=repo.collection.description, + mode=repo.mode, + branch=repo.branch, + frequency=download.frequency if download else None, + ) + data.append(entry) + + self._config['repos'] = data + logger.info(f'Dumping {len(data)} repos to config') + self.save(file, send_events, overwrite) + + def preview_backup_import(self, backup_date: str, mode: str) -> dict: + """Preview which Repos a backup import would add/remove (keyed by URL).""" + backup_data = self.read_config_file(self._get_backup_file(backup_date)) + current_data = self.read_config_file() if self.get_file().is_file() else dict(repos=[], version=0) + + backup_repos = {repo_url_key(i['url']): i for i in backup_data.get('repos', []) if i.get('url')} + current_repos = {repo_url_key(i['url']): i for i in current_data.get('repos', []) if i.get('url')} + + add = [dict(type='repo', name=i.get('name', ''), url=i['url']) + for key, i in backup_repos.items() if key not in current_repos] + unchanged = len([i for i in backup_repos if i in current_repos]) + remove = [] + if mode == 'overwrite': + remove = [dict(type='repo', name=i.get('name', ''), url=i['url']) + for key, i in sorted(current_repos.items()) if key not in backup_repos] + return dict(mode=mode, add=add, remove=remove, unchanged=unchanged) + + def import_backup(self, backup_date: str, mode: str, send_events: bool = False): + """Restore Repos from a dated backup of repos.yaml ('overwrite' or 'merge' by URL).""" + self._preserve_current_config() + backup_file = self._get_backup_file(backup_date) + config_file = self.get_file() + config_file.parent.mkdir(parents=True, exist_ok=True) + + if mode == 'overwrite': + shutil.copy2(backup_file, config_file) + elif mode == 'merge': + backup_data = self.read_config_file(backup_file) + current_data = self.read_config_file() if config_file.is_file() else dict(repos=[], version=0) + current_keys = {repo_url_key(i['url']) for i in current_data.get('repos', []) if i.get('url')} + merged = list(current_data.get('repos', [])) + merged.extend(i for i in backup_data.get('repos', []) + if i.get('url') and repo_url_key(i['url']) not in current_keys) + self.write_config_data(dict(repos=merged, version=current_data.get('version', 0) + 1), config_file) + + self.import_config(send_events=send_events) + save_downloads_config.activate_switch() + + +repos_config = ReposConfig() + + +def get_repos_config() -> ReposConfig: + return repos_config + + +@register_switch_handler('save_repos_config') +def save_repos_config(): + """Save the repos config when the switch is activated.""" + repos_config.background_dump.activate_switch() + + +save_repos_config: ActivateSwitchMethod + + +def import_repos_config(): + logger.info('Importing repos config') + repos_config.import_config() diff --git a/modules/repos/models.py b/modules/repos/models.py new file mode 100644 index 00000000..024976fa --- /dev/null +++ b/modules/repos/models.py @@ -0,0 +1,119 @@ +import pathlib +from typing import Optional + +from sqlalchemy import Column, Integer, String, ForeignKey, BigInteger, Text +from sqlalchemy.orm import relationship, Session, joinedload, selectinload + +from wrolpi.collections.models import Collection +from wrolpi.common import Base, ModelHelper, get_relative_to_media_directory +from wrolpi.dates import TZDateTime +from wrolpi.db import serializer +from wrolpi.downloader import Download +from .errors import UnknownRepo + +__all__ = ['Repository', 'REPO_MODES'] + +# full: every branch and tag, with all history. snapshot: only the latest commit of one branch. +REPO_MODES = ('full', 'snapshot') + + +class Repository(ModelHelper, Base): + """A git repository mirrored into a `kind='repo'` Collection's directory. + + The name, directory and Tag live on the Collection; the Collection's recurring Download keeps the mirror + up to date.""" + __tablename__ = 'repository' + id = Column(Integer, primary_key=True) + # The https clone URL; unique (compared without a trailing `.git`, see `repo_url_key`). + url = Column(String, nullable=False, unique=True) + host = Column(String) + owner = Column(String) + mode = Column(String, nullable=False, default='full') + # The branch to check out; None follows the remote's default branch. + branch = Column(String) + default_branch = Column(String) + head_sha = Column(String) + head_date = Column(TZDateTime) + head_message = Column(Text) + last_fetch = Column(TZDateTime) + size = Column(BigInteger) + # The README in the repo's root directory, relative to the repo. + readme_path = Column(String) + + collection_id = Column(Integer, ForeignKey('collection.id', ondelete='CASCADE'), nullable=False, unique=True) + # Joined: a Repository's name, directory and Tag live on its Collection. + collection = relationship('Collection', foreign_keys=[collection_id], lazy='joined') + + def __repr__(self): + return f'' + + @property + def name(self) -> Optional[str]: + return self.collection.name if self.collection else None + + @property + def directory(self) -> Optional[pathlib.Path]: + return self.collection.directory if self.collection else None + + @property + def tag_name(self) -> Optional[str]: + return self.collection.tag_name if self.collection else None + + @property + def download(self) -> Optional[Download]: + """The recurring Download which keeps this repo up to date.""" + downloads = [i for i in self.collection.downloads if i.frequency] if self.collection else [] + return downloads[0] if downloads else None + + @property + def location(self) -> str: + return f'/repos/{self.id}' + + @staticmethod + def json_options() -> tuple: + """Loader options for a query whose Repositories will be serialized.""" + return ( + joinedload(Repository.collection).joinedload(Collection.tag), + joinedload(Repository.collection).selectinload(Collection.downloads).defer(Download.info_json), + ) + + @serializer + def __json__(self) -> dict: + download = self.download + return { + 'id': self.id, + 'collection_id': self.collection_id, + 'name': self.name, + 'description': self.collection.description if self.collection else None, + 'directory': str(get_relative_to_media_directory(self.directory)) if self.directory else None, + 'tag_name': self.tag_name, + 'url': self.url, + 'host': self.host, + 'owner': self.owner, + 'mode': self.mode, + 'branch': self.branch, + 'default_branch': self.default_branch, + 'head_sha': self.head_sha, + 'head_date': self.head_date, + 'head_message': self.head_message, + 'last_fetch': self.last_fetch, + 'size': self.size, + 'readme_path': self.readme_path, + 'location': self.location, + 'frequency': download.frequency if download else None, + 'download_id': download.id if download else None, + 'download_status': download.status if download else None, + 'download_error': download.error if download else None, + 'next_download': download.next_download if download else None, + } + + @staticmethod + def find_by_id(session: Session, id_: int, options: tuple = ()) -> 'Repository': + repo = session.query(Repository).options(*options).filter_by(id=id_).one_or_none() + if not repo: + raise UnknownRepo(f'Cannot find repo with id {id_}') + return repo + + @staticmethod + def get_by_collection_id(session: Session, collection_id: int) -> Optional['Repository']: + return session.query(Repository).filter_by(collection_id=collection_id).one_or_none() diff --git a/modules/repos/schema.py b/modules/repos/schema.py new file mode 100644 index 00000000..af117cd1 --- /dev/null +++ b/modules/repos/schema.py @@ -0,0 +1,21 @@ +from dataclasses import dataclass +from typing import Optional + + +@dataclass +class RepoCreateRequest: + url: str + tag_name: Optional[str] = None + frequency: Optional[int] = None + mode: Optional[str] = None + branch: Optional[str] = None + name: Optional[str] = None + description: Optional[str] = None + + +@dataclass +class RepoUpdateRequest: + description: Optional[str] = None + frequency: Optional[int] = None + mode: Optional[str] = None + branch: Optional[str] = None diff --git a/modules/repos/test/__init__.py b/modules/repos/test/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/modules/repos/test/test_api.py b/modules/repos/test/test_api.py new file mode 100644 index 00000000..0c5ba8b2 --- /dev/null +++ b/modules/repos/test/test_api.py @@ -0,0 +1,137 @@ +import json +from http import HTTPStatus + +import pytest + +from modules.repos import lib +from modules.repos.models import Repository +from wrolpi.downloader import Download, DownloadFrequency, DownloadStatus + + +@pytest.mark.asyncio +async def test_repos_crud(test_session, test_directory, async_client, test_wrolpi_config): + body = dict(url='https://github.com/kiwix/kiwix-tools', tag_name='software', frequency=DownloadFrequency.daily) + request, response = await async_client.post('/api/repos', content=json.dumps(body)) + assert response.status_code == HTTPStatus.CREATED, response.json + repo = response.json['repo'] + assert repo['name'] == 'kiwix-tools' + assert repo['tag_name'] == 'software' + assert repo['directory'] == 'repos/software/kiwix-tools' + assert repo['mode'] == 'full' + assert repo['frequency'] == DownloadFrequency.daily + assert repo['download_status'] == DownloadStatus.new + assert repo['location'] == f'/repos/{repo["id"]}' + repo_id = repo['id'] + + request, response = await async_client.post('/api/repos', content=json.dumps(dict(url='https://github.com/a/b'))) + assert response.status_code == HTTPStatus.CREATED + + request, response = await async_client.get('/api/repos') + assert response.status_code == HTTPStatus.OK + assert [i['name'] for i in response.json['repos']] == ['b', 'kiwix-tools'] + + body = dict(description='Kiwix tools', mode='snapshot', branch='dev', frequency=DownloadFrequency.weekly) + request, response = await async_client.put(f'/api/repos/{repo_id}', content=json.dumps(body)) + assert response.status_code == HTTPStatus.OK, response.json + request, response = await async_client.get(f'/api/repos/{repo_id}') + repo = response.json['repo'] + assert (repo['description'], repo['mode'], repo['branch'], repo['frequency']) == \ + ('Kiwix tools', 'snapshot', 'dev', DownloadFrequency.weekly) + + request, response = await async_client.delete(f'/api/repos/{repo_id}') + assert response.status_code == HTTPStatus.NO_CONTENT + request, response = await async_client.get(f'/api/repos/{repo_id}') + assert response.status_code == HTTPStatus.NOT_FOUND + assert response.json['code'] == 'UNKNOWN_REPO' + + +@pytest.mark.asyncio +async def test_create_repo_errors(test_session, async_client, test_wrolpi_config): + request, response = await async_client.post('/api/repos', content=json.dumps(dict(url='git@github.com:a/b'))) + assert response.status_code == HTTPStatus.BAD_REQUEST + assert response.json['code'] == 'INVALID_REPO' + + request, response = await async_client.post('/api/repos', content=json.dumps(dict(url='https://github.com/a/b'))) + assert response.status_code == HTTPStatus.CREATED + request, response = await async_client.post('/api/repos', + content=json.dumps(dict(url='https://github.com/a/b.git'))) + assert response.status_code == HTTPStatus.CONFLICT + assert response.json['code'] == 'REPO_CONFLICT' + + +@pytest.mark.asyncio +async def test_repo_tree_and_update(test_session, async_client, git_remote_factory, repos_download_manager): + remote = git_remote_factory(files={'README.md': '# Example', 'docs/guide.md': 'guide'}) + repo = lib.create_repository(test_session, remote.url) + await repos_download_manager.wait_for_all_downloads() + + request, response = await async_client.get(f'/api/repos/{repo.id}/tree') + assert response.status_code == HTTPStatus.OK + assert response.json['readme_path'] == 'README.md' + assert [i['path'] for i in response.json['entries']] == ['docs', 'README.md'] + + request, response = await async_client.get(f'/api/repos/{repo.id}/tree?path=docs') + assert [i['path'] for i in response.json['entries']] == ['docs/guide.md'] + + request, response = await async_client.get(f'/api/repos/{repo.id}/tree?path=../..') + assert response.status_code == HTTPStatus.BAD_REQUEST + + # "Update now" renews the download. + new_head = remote.commit({'new.txt': 'new'}, 'New') + request, response = await async_client.post(f'/api/repos/{repo.id}/update') + assert response.status_code == HTTPStatus.NO_CONTENT + await repos_download_manager.wait_for_all_downloads() + test_session.expire_all() + assert test_session.query(Repository).one().head_sha == new_head + + +@pytest.mark.asyncio +async def test_tag_repo_moves_clone(test_session, test_directory, async_client, git_remote_factory, + repos_download_manager, await_background_tasks): + """Tagging a Repo (through the collections API) moves the whole clone, including `.git`.""" + remote = git_remote_factory() + repo = lib.create_repository(test_session, remote.url) + await repos_download_manager.wait_for_all_downloads() + old_directory = test_directory / 'repos/example' + assert (old_directory / '.git').is_dir() + + body = dict(tag_name='software', directory='repos/software/example') + request, response = await async_client.post(f'/api/collections/{repo.collection_id}/tag', + content=json.dumps(body)) + assert response.status_code == HTTPStatus.OK, response.json + await await_background_tasks() + test_session.expire_all() + + new_directory = test_directory / 'repos/software/example' + assert repo.directory == new_directory + assert repo.tag_name == 'software' + assert (new_directory / '.git').is_dir() + assert (new_directory / 'README.md').is_file() + assert not old_directory.exists() + assert test_session.query(Download).one().destination == new_directory + + # The moved clone still updates. + new_head = remote.commit({'new.txt': 'new'}, 'New') + download = test_session.query(Download).one() + download.renew() + test_session.commit() + await repos_download_manager.wait_for_all_downloads() + test_session.expire_all() + assert repo.head_sha == new_head + assert (new_directory / 'new.txt').is_file() + + +@pytest.mark.asyncio +async def test_repos_destination_setting(async_client, test_wrolpi_config): + request, response = await async_client.get('/api/settings') + assert response.json['repos_destination'] == 'repos/%(repo_tag)s/%(repo_name)s' + + body = dict(repos_destination='/repos') + request, response = await async_client.patch('/api/settings', content=json.dumps(body)) + assert response.status_code == HTTPStatus.BAD_REQUEST + + body = dict(repos_destination='repos/%(repo_owner)s/%(repo_name)s') + request, response = await async_client.patch('/api/settings', content=json.dumps(body)) + assert response.status_code == HTTPStatus.NO_CONTENT + request, response = await async_client.get('/api/settings') + assert response.json['repos_destination'] == 'repos/%(repo_owner)s/%(repo_name)s' diff --git a/modules/repos/test/test_config.py b/modules/repos/test/test_config.py new file mode 100644 index 00000000..2e2c1145 --- /dev/null +++ b/modules/repos/test/test_config.py @@ -0,0 +1,87 @@ +import pytest + +from modules.repos import lib +from modules.repos.models import Repository +from wrolpi.collections.models import Collection +from wrolpi.downloader import Download, DownloadFrequency + + +@pytest.mark.asyncio +async def test_dump_and_import(test_session, test_directory, async_client, test_wrolpi_config, await_switches): + """repos.yaml is the source of truth; a lost database is rebuilt from it.""" + lib.create_repository(test_session, 'https://github.com/kiwix/kiwix-tools', tag_name='software', + description='Tools', frequency=DownloadFrequency.daily) + lib.create_repository(test_session, 'https://github.com/a/b', mode='snapshot', branch='dev') + await await_switches() + + config = lib.get_repos_config() + assert config.get_file().is_file() + assert config.repos == [ + dict(name='b', url='https://github.com/a/b', directory='repos/b', tag_name=None, description=None, + mode='snapshot', branch='dev', frequency=DownloadFrequency.weekly), + dict(name='kiwix-tools', url='https://github.com/kiwix/kiwix-tools', directory='repos/software/kiwix-tools', + tag_name='software', description='Tools', mode='full', branch=None, frequency=DownloadFrequency.daily), + ] + + # Lose the database. + for repo in test_session.query(Repository).all(): + lib._delete_repository(test_session, repo) + test_session.commit() + assert test_session.query(Collection).count() == 0 + + config.import_config() + test_session.expire_all() + repos = {i.name: i for i in test_session.query(Repository)} + assert repos['kiwix-tools'].directory == test_directory / 'repos/software/kiwix-tools' + assert repos['kiwix-tools'].tag_name == 'software' + assert repos['kiwix-tools'].collection.description == 'Tools' + assert repos['kiwix-tools'].download.frequency == DownloadFrequency.daily + assert (repos['b'].mode, repos['b'].branch) == ('snapshot', 'dev') + assert {i.downloader for i in test_session.query(Download)} == {'git'} + + # A repo removed from the config is deleted. + data = config.read_config_file() + data['repos'] = data['repos'][1:] + data['version'] += 1 + config.write_config_data(data, config.get_file()) + config.import_config() + test_session.expire_all() + assert [i.name for i in test_session.query(Repository)] == ['kiwix-tools'] + assert test_session.query(Download).count() == 1 + + +@pytest.mark.asyncio +async def test_import_links_existing_download(test_session, async_client, test_wrolpi_config): + """A Repo imported after download_manager.yaml re-uses its Download.""" + lib.create_repository(test_session, 'https://github.com/a/b') + test_session.query(Repository).delete() + test_session.query(Collection).delete() + test_session.commit() + download = test_session.query(Download).one() + assert download.collection_id is None + + config = lib.get_repos_config() + config.write_config_data(dict(version=1, repos=[dict(name='b', url='https://github.com/a/b', frequency=3600)]), + config.get_file()) + config.import_config() + test_session.expire_all() + + repo = test_session.query(Repository).one() + assert test_session.query(Download).one().id == download.id + assert download.collection_id == repo.collection_id + assert download.frequency == 3600 + + +@pytest.mark.asyncio +async def test_delete_last_repo(test_session, async_client, test_wrolpi_config, await_switches): + """Deleting the last Repo empties the config, so it does not return on the next import.""" + repo = lib.create_repository(test_session, 'https://github.com/a/b') + await await_switches() + config = lib.get_repos_config() + assert len(config.read_config_file()['repos']) == 1 + + request, response = await async_client.delete(f'/api/repos/{repo.id}') + assert config.read_config_file()['repos'] == [] + + config.import_config() + assert test_session.query(Repository).count() == 0 diff --git a/modules/repos/test/test_downloader.py b/modules/repos/test/test_downloader.py new file mode 100644 index 00000000..b962669c --- /dev/null +++ b/modules/repos/test/test_downloader.py @@ -0,0 +1,211 @@ +import shutil +import subprocess + +import pytest + +from modules.repos import lib +from modules.repos.downloader import parse_git_progress +from modules.repos.models import Repository +from wrolpi.downloader import Download, DownloadStatus + + +def git(directory, *args) -> str: + return subprocess.run(['git', '-c', 'safe.directory=*', *args], cwd=directory, check=True, + capture_output=True).stdout.decode().strip() + + +@pytest.mark.asyncio +async def test_clone_full(test_session, test_directory, git_remote_factory, repos_download_manager): + """A new Repo is cloned with its whole history, and the Repo describes the checked out commit.""" + remote = git_remote_factory('kiwix-tools', owner='kiwix', files={'README.md': '# Kiwix\n', 'src/main.c': 'int'}) + remote.commit({'CHANGELOG': 'v2'}, 'Second commit') + remote.git('tag', 'v2') + + repo = lib.create_repository(test_session, remote.url, tag_name='software') + await repos_download_manager.wait_for_all_downloads() + test_session.expire_all() + + directory = test_directory / 'repos/software/kiwix-tools' + assert repo.directory == directory + assert (directory / 'README.md').read_text() == '# Kiwix\n' + assert (directory / 'src/main.c').is_file() + # Full mode has all the history and tags. + assert git(directory, 'rev-list', '--count', 'HEAD') == '2' + assert git(directory, 'tag') == 'v2' + assert not (directory / '.git/shallow').exists() + + assert repo.head_sha == remote.head + assert repo.head_message == 'Second commit' + assert repo.head_date is not None + assert repo.default_branch == 'main' + assert repo.readme_path == 'README.md' + assert repo.size > 0 + assert repo.last_fetch is not None + + download, = test_session.query(Download).all() + assert download.status == DownloadStatus.complete + assert download.location == f'/repos/{repo.id}' + assert download.error is None + + +@pytest.mark.asyncio +async def test_update(test_session, test_directory, git_remote_factory, repos_download_manager): + """An update fetches new commits, and discards local changes (a Repo is a mirror).""" + remote = git_remote_factory() + repo = lib.create_repository(test_session, remote.url) + await repos_download_manager.wait_for_all_downloads() + directory = repo.directory + + # Local changes. + (directory / 'README.md').write_text('local change') + (directory / 'untracked.txt').write_text('untracked') + + new_head = remote.commit({'new.txt': 'new'}, 'New file') + download, = test_session.query(Download).all() + download.renew() + test_session.commit() + await repos_download_manager.wait_for_all_downloads() + test_session.expire_all() + + assert (directory / 'new.txt').read_text() == 'new' + assert (directory / 'README.md').read_text() == '# example\n\nThe example repo.\n' + assert not (directory / 'untracked.txt').exists() + assert repo.head_sha == new_head + assert repo.head_message == 'New file' + + +@pytest.mark.asyncio +async def test_update_keeps_history(test_session, git_remote_factory, repos_download_manager): + """Branches deleted upstream are kept, and history rewritten by a force push is saved in a backup ref.""" + remote = git_remote_factory() + remote.git('branch', 'feature') + old_head = remote.commit({'a.txt': 'a'}, 'Will be rewritten') + repo = lib.create_repository(test_session, remote.url) + await repos_download_manager.wait_for_all_downloads() + directory = repo.directory + assert 'origin/feature' in git(directory, 'branch', '--remotes') + + # Upstream deletes a branch, and rewrites main. + remote.git('branch', '--delete', 'feature') + remote.git('reset', '--hard', 'HEAD~1') + new_head = remote.commit({'b.txt': 'b'}, 'Rewritten') + + download, = test_session.query(Download).all() + download.renew() + test_session.commit() + await repos_download_manager.wait_for_all_downloads() + test_session.expire_all() + + assert repo.head_sha == new_head + assert 'origin/feature' in git(directory, 'branch', '--remotes') + backups = git(directory, 'for-each-ref', '--format=%(objectname)', 'refs/wrolpi/backup/') + assert backups == old_head + + +@pytest.mark.asyncio +async def test_snapshot(test_session, git_remote_factory, repos_download_manager): + """A snapshot only has the latest commit; switching to full fetches the whole history.""" + remote = git_remote_factory() + remote.commit({'a.txt': 'a'}, 'Second') + repo = lib.create_repository(test_session, remote.url, mode='snapshot') + await repos_download_manager.wait_for_all_downloads() + directory = repo.directory + assert (directory / '.git/shallow').is_file() + assert git(directory, 'rev-list', '--count', 'HEAD') == '1' + + # Snapshot updates stay shallow. + remote.commit({'b.txt': 'b'}, 'Third') + download, = test_session.query(Download).all() + download.renew() + test_session.commit() + await repos_download_manager.wait_for_all_downloads() + assert (directory / 'b.txt').is_file() + assert git(directory, 'rev-list', '--count', 'HEAD') == '1' + + lib.update_repository(test_session, repo.id, mode='full') + download.renew() + test_session.commit() + await repos_download_manager.wait_for_all_downloads() + assert not (directory / '.git/shallow').exists() + assert git(directory, 'rev-list', '--count', 'HEAD') == '3' + + +@pytest.mark.asyncio +async def test_branch(test_session, git_remote_factory, repos_download_manager): + """A Repo can follow a branch other than the default branch.""" + remote = git_remote_factory() + remote.git('checkout', '--quiet', '-b', 'dev') + dev_head = remote.commit({'dev.txt': 'dev'}, 'Dev') + remote.git('checkout', '--quiet', 'main') + + repo = lib.create_repository(test_session, f'{remote.url}/tree/dev') + assert repo.branch == 'dev' + await repos_download_manager.wait_for_all_downloads() + test_session.expire_all() + assert repo.head_sha == dev_head + assert repo.default_branch == 'main' + assert git(repo.directory, 'branch', '--show-current') == 'dev' + + +@pytest.mark.asyncio +async def test_upstream_gone(test_session, git_remote_factory, repos_download_manager): + """When the upstream disappears the download is deferred with git's error; the local copy is kept.""" + remote = git_remote_factory() + repo = lib.create_repository(test_session, remote.url) + await repos_download_manager.wait_for_all_downloads() + directory = repo.directory + head = repo.head_sha + + shutil.rmtree(remote.path) + download, = test_session.query(Download).all() + download.renew() + test_session.commit() + await repos_download_manager.wait_for_all_downloads() + test_session.expire_all() + + assert download.status == DownloadStatus.deferred + assert 'git ls-remote failed' in download.error + assert (directory / 'README.md').is_file() + assert repo.head_sha == head + + +@pytest.mark.asyncio +async def test_symlinks_are_not_followed(test_session, git_remote_factory, repos_download_manager): + """A symlink in a repo is checked out as a plain file, so it cannot expose files outside the repo.""" + remote = git_remote_factory() + (remote.path / 'shadow').symlink_to('/etc/passwd') + remote.git('add', 'shadow') + remote.git('commit', '--quiet', '-m', 'Symlink') + + repo = lib.create_repository(test_session, remote.url) + await repos_download_manager.wait_for_all_downloads() + + shadow = repo.directory / 'shadow' + assert not shadow.is_symlink() + assert shadow.read_text() == '/etc/passwd' + + +@pytest.mark.asyncio +async def test_refuses_non_empty_directory(test_session, test_directory, git_remote_factory, repos_download_manager): + """A Repo is never cloned over existing files.""" + remote = git_remote_factory() + directory = test_directory / 'repos/example' + directory.mkdir(parents=True) + (directory / 'important.txt').write_text('important') + + lib.create_repository(test_session, remote.url) + await repos_download_manager.wait_for_all_downloads() + + download, = test_session.query(Download).all() + assert download.status == DownloadStatus.deferred + assert 'not empty' in download.error + assert (directory / 'important.txt').read_text() == 'important' + assert test_session.query(Repository).one().head_sha is None + + +def test_parse_git_progress(): + assert parse_git_progress('Receiving objects: 45% (123/456), 1.20 MiB | 1.00 MiB/s') == \ + dict(stage='Receiving objects', percent=45) + assert parse_git_progress('remote: Counting objects: 100% (5/5), done.') == \ + dict(stage='Counting objects', percent=100) + assert parse_git_progress("Cloning into 'example'...") is None diff --git a/modules/repos/test/test_lib.py b/modules/repos/test/test_lib.py new file mode 100644 index 00000000..e541f04f --- /dev/null +++ b/modules/repos/test/test_lib.py @@ -0,0 +1,210 @@ +import pytest + +from modules.repos import lib +from modules.repos.errors import InvalidRepo, RepoConflict +from modules.repos.models import Repository +from wrolpi.collections.models import Collection +from wrolpi.common import get_wrolpi_config +from wrolpi.downloader import Download, DownloadFrequency +from wrolpi.errors import UnknownDirectory +from wrolpi.files.models import FileGroup + + +@pytest.mark.parametrize('url,expected', [ + ('https://github.com/kiwix/kiwix-tools', + lib.ParsedRepoURL('https://github.com/kiwix/kiwix-tools', 'github.com', 'kiwix', 'kiwix-tools')), + ('https://GitHub.com/kiwix/kiwix-tools.git/', + lib.ParsedRepoURL('https://github.com/kiwix/kiwix-tools.git', 'github.com', 'kiwix', 'kiwix-tools')), + ('https://github.com/kiwix/kiwix-tools/tree/feature/x', + lib.ParsedRepoURL('https://github.com/kiwix/kiwix-tools', 'github.com', 'kiwix', 'kiwix-tools', 'feature/x')), + ('https://gitlab.com/group/sub/project/-/tree/dev', + lib.ParsedRepoURL('https://gitlab.com/group/sub/project', 'gitlab.com', 'group/sub', 'project', 'dev')), + ('https://git.example.com:8443/project', + lib.ParsedRepoURL('https://git.example.com:8443/project', 'git.example.com', '', 'project')), +]) +def test_parse_repo_url(url, expected): + assert lib.parse_repo_url(url) == expected + + +@pytest.mark.parametrize('url', [ + 'http://github.com/kiwix/kiwix-tools', + 'git@github.com:kiwix/kiwix-tools.git', + 'ssh://git@github.com/kiwix/kiwix-tools', + 'file:///etc', + 'https://user:token@github.com/kiwix/kiwix-tools', + 'https://github.com/kiwix/kiwix-tools?tab=readme', + 'https://github.com', + '', +]) +def test_parse_repo_url_invalid(url): + with pytest.raises(InvalidRepo): + lib.parse_repo_url(url) + + +def test_repo_url_key(): + assert lib.repo_url_key('https://GitHub.com/a/b.git/') == lib.repo_url_key('https://github.com/a/b') + assert lib.repo_url_key('https://github.com/a/b') != lib.repo_url_key('https://github.com/a/c') + + +def test_git_command_is_restricted(): + cmd = lib.git_command('clone', 'https://example.com/a') + assert 'protocol.allow=never' in cmd + assert 'protocol.https.allow=always' in cmd + assert 'core.symlinks=false' in cmd + assert 'core.hooksPath=/dev/null' in cmd + assert cmd[-2:] == ('clone', 'https://example.com/a') + assert lib.git_env()['GIT_TERMINAL_PROMPT'] == '0' + + +@pytest.mark.asyncio +async def test_create_repository(test_session, test_directory, test_wrolpi_config, async_client): + repo = lib.create_repository(test_session, 'https://github.com/kiwix/kiwix-tools', tag_name='software') + + collection = test_session.query(Collection).one() + assert collection.kind == 'repo' + assert collection.name == 'kiwix-tools' + assert collection.tag_name == 'software' + assert collection.directory == test_directory / 'repos/software/kiwix-tools' + assert repo.collection_id == collection.id + assert (repo.url, repo.host, repo.owner, repo.mode, repo.branch) == \ + ('https://github.com/kiwix/kiwix-tools', 'github.com', 'kiwix', 'full', None) + + # Repos are always kept up to date; weekly by default. + download = test_session.query(Download).one() + assert download.url == repo.url + assert download.downloader == 'git' + assert download.frequency == DownloadFrequency.weekly + assert download.collection_id == collection.id + assert repo.download == download + + # Without a tag. + repo = lib.create_repository(test_session, 'https://github.com/kiwix/libkiwix') + assert repo.directory == test_directory / 'repos/libkiwix' + + +@pytest.mark.asyncio +async def test_create_repository_conflicts(test_session, test_wrolpi_config, async_client): + lib.create_repository(test_session, 'https://github.com/a/utils') + + # The same repo, even with `.git`. + with pytest.raises(RepoConflict): + lib.create_repository(test_session, 'https://github.com/a/utils.git') + + # Another owner's repo with the same name; a new name is suggested. + with pytest.raises(RepoConflict) as e: + lib.create_repository(test_session, 'https://github.com/b/utils') + assert "'b-utils'" in str(e.value) + test_session.rollback() + + repo = lib.create_repository(test_session, 'https://github.com/b/utils', name='b-utils') + assert repo.name == 'b-utils' + assert test_session.query(Repository).count() == 2 + + +@pytest.mark.asyncio +async def test_create_repository_invalid(test_session, test_wrolpi_config, async_client): + with pytest.raises(InvalidRepo): + lib.create_repository(test_session, 'http://github.com/a/b') + with pytest.raises(Exception): + lib.create_repository(test_session, 'https://github.com/a/b', mode='bare') + with pytest.raises(Exception): + lib.create_repository(test_session, 'https://github.com/a/b', frequency=0) + + +@pytest.mark.asyncio +async def test_repos_destination(test_session, test_directory, test_wrolpi_config, async_client): + """The repos destination can use the repo's owner and host.""" + get_wrolpi_config().repos_destination = 'repos/%(repo_host)s/%(repo_owner)s/%(repo_name)s' + repo = lib.create_repository(test_session, 'https://gitlab.com/group/sub/project') + assert repo.directory == test_directory / 'repos/gitlab.com/group⧸sub/project' + + get_wrolpi_config().repos_destination = 'repos/%(tag_name)s/%(repo_name)s' + repo = lib.create_repository(test_session, 'https://github.com/a/b', tag_name='Tag') + assert repo.directory == test_directory / 'repos/Tag/b' + + +@pytest.mark.asyncio +async def test_update_repository(test_session, test_wrolpi_config, async_client): + repo = lib.create_repository(test_session, 'https://github.com/a/b', branch='dev') + lib.update_repository(test_session, repo.id, description='My repo', frequency=DownloadFrequency.daily, + mode='snapshot', branch='') + assert repo.collection.description == 'My repo' + assert repo.download.frequency == DownloadFrequency.daily + assert repo.mode == 'snapshot' + # An empty branch follows the default branch. + assert repo.branch is None + + +@pytest.mark.asyncio +async def test_delete_repository(test_session, test_directory, test_wrolpi_config, await_background_tasks, + async_client): + keep = lib.create_repository(test_session, 'https://github.com/a/keep') + delete = lib.create_repository(test_session, 'https://github.com/a/delete') + for repo in (keep, delete): + repo.directory.mkdir(parents=True) + (repo.directory / 'README.md').write_text('readme') + keep_directory, delete_directory = keep.directory, delete.directory + + await lib.delete_repository(test_session, keep.id) + await lib.delete_repository(test_session, delete.id, delete_files=True) + await await_background_tasks() + + assert test_session.query(Repository).count() == 0 + assert test_session.query(Collection).count() == 0 + assert test_session.query(Download).count() == 0 + # Files are kept by default. + assert (keep_directory / 'README.md').is_file() + assert not delete_directory.exists() + + +@pytest.mark.asyncio +async def test_list_repo_tree(test_session, test_directory, test_wrolpi_config, async_client): + repo = lib.create_repository(test_session, 'https://github.com/a/b') + with pytest.raises(UnknownDirectory): + lib.list_repo_tree(repo) + + root = repo.directory + (root / '.git').mkdir(parents=True) + (root / 'src/lib').mkdir(parents=True) + (root / 'src/Readme.rst').write_text('src') + (root / 'README.md').write_text('# B') + (root / 'a.txt').write_text('aaa') + (root / 'Docs').mkdir() + + tree = lib.list_repo_tree(repo) + assert tree == dict( + path='', + readme_path='README.md', + entries=[ + dict(name='Docs', path='Docs', is_dir=True, size=None), + dict(name='src', path='src', is_dir=True, size=None), + dict(name='a.txt', path='a.txt', is_dir=False, size=3), + dict(name='README.md', path='README.md', is_dir=False, size=3), + ], + ) + + tree = lib.list_repo_tree(repo, '/src/') + assert tree['path'] == 'src' + assert tree['readme_path'] == 'src/Readme.rst' + assert [i['path'] for i in tree['entries']] == ['src/lib', 'src/Readme.rst'] + + with pytest.raises(InvalidRepo): + lib.list_repo_tree(repo, '../..') + with pytest.raises(UnknownDirectory): + lib.list_repo_tree(repo, 'missing') + + +@pytest.mark.asyncio +async def test_repos_directory_is_ignored(test_session, test_directory, test_wrolpi_config, refresh_files): + """Files in the repos directory are never indexed, even when an old config does not ignore it.""" + config = get_wrolpi_config() + config.ignored_directories = ['config'] + config.import_config() + assert 'repos' in config.ignored_directories + + (test_directory / 'repos/a/b').mkdir(parents=True) + (test_directory / 'repos/a/b/README.md').write_text('# B') + (test_directory / 'other.txt').write_text('other') + await refresh_files() + + assert [i.primary_path.name for i in test_session.query(FileGroup)] == ['other.txt'] diff --git a/wrolpi/cmd.py b/wrolpi/cmd.py index 76895932..c024ebee 100644 --- a/wrolpi/cmd.py +++ b/wrolpi/cmd.py @@ -67,6 +67,7 @@ CPUFREQ_SET_BIN = which('cpufreq-set', '/usr/bin/cpufreq-set') # Files WGET_BIN = which('wget', '/usr/bin/wget') +GIT_BIN = which('git', '/usr/bin/git') # Map BASH_BIN = which('bash', '/bin/bash') @@ -184,7 +185,7 @@ TESTING_RUN_COMMAND_RESULT = None async def run_command(cmd: tuple[str | pathlib.Path, ...], cwd: pathlib.Path | str = None, timeout: int = 600, log_command: bool = True, stdout_callback: callable = None, env: dict = None, - start_new_session: bool = False) -> CommandResult: + start_new_session: bool = False, merge_stderr: bool = False) -> CommandResult: """Run a shell command, return the results (stdout/stderr/return code). When stdout_callback is provided, stdout is piped and each line is passed to the callback @@ -196,6 +197,8 @@ async def run_command(cmd: tuple[str | pathlib.Path, ...], cwd: pathlib.Path | s :param start_new_session: Run the command in its own session/process group; when it finishes (or is killed by timeout/cancel), the whole group is killed. Use for commands that may leave children behind (e.g. single-file's browser). + :param merge_stderr: Send stderr to stdout (and so to `stdout_callback`); `stderr` will be empty. Use for + commands that write progress to stderr (e.g. git). """ if not isinstance(cmd, (list, tuple)): raise RuntimeError('Command must be a list or tuple') @@ -233,7 +236,7 @@ async def run_command(cmd: tuple[str | pathlib.Path, ...], cwd: pathlib.Path | s proc = await asyncio.create_subprocess_exec( *cmd, stdout=stdout_arg, - stderr=stderr_fh, + stderr=asyncio.subprocess.STDOUT if merge_stderr else stderr_fh, cwd=cwd, env=env, start_new_session=start_new_session, diff --git a/wrolpi/collections/lib.py b/wrolpi/collections/lib.py index 837ef872..37267bf0 100644 --- a/wrolpi/collections/lib.py +++ b/wrolpi/collections/lib.py @@ -54,6 +54,10 @@ def _activate_config_save(kind: str): elif kind == 'playlist': from .config import save_playlists_config save_playlists_config.activate_switch() + elif kind == 'repo': + # Local import to avoid circular import: collections -> repos -> collections + from modules.repos.lib import save_repos_config + save_repos_config.activate_switch() def get_collections(session: Session, kind: Optional[str] = None) -> List[dict]: diff --git a/wrolpi/collections/models.py b/wrolpi/collections/models.py index 881c9edc..42f3eef9 100644 --- a/wrolpi/collections/models.py +++ b/wrolpi/collections/models.py @@ -1021,6 +1021,8 @@ class Collection(ModelHelper, Base): template = config.videos_destination elif self.kind == 'domain': template = config.archive_destination + elif self.kind == 'repo': + template = config.repos_destination else: template = '%(kind)s/%(tag)s/%(name)s' @@ -1037,7 +1039,15 @@ class Collection(ModelHelper, Base): # Backward compatibility aliases for archives domain=escaped_name, domain_tag=tag_name or '', + # Repos + repo_name=escaped_name, + repo_tag=tag_name or '', + tag_name=tag_name or '', ) + if self.kind == 'repo': + # Local import to avoid circular import: collections -> repos -> collections + from modules.repos.lib import repo_destination_variables + variables.update(repo_destination_variables(self)) destination = template % variables return get_media_directory() / destination.lstrip('/') @@ -1076,6 +1086,9 @@ class Collection(ModelHelper, Base): elif self.kind == 'channel': from modules.videos.lib import save_channels_config save_channels_config.activate_switch() + elif self.kind == 'repo': + from modules.repos.lib import save_repos_config + save_repos_config.activate_switch() return destination @@ -1146,7 +1159,11 @@ class Collection(ModelHelper, Base): raise finally: session.commit() - if old_directory.exists() and not next(iter(old_directory.iterdir()), None): + # The move keeps each moved directory (e.g. a repo's `.git`), even when emptied; delete the old + # directory when only empty directories remain. + if old_directory.exists() and not any(not i.is_dir() for i in old_directory.rglob('*')): + for directory in sorted(old_directory.rglob('*'), key=lambda i: len(i.parts), reverse=True): + delete_directory(directory) delete_directory(old_directory) else: # Files already moved, just send event diff --git a/wrolpi/collections/types.py b/wrolpi/collections/types.py index 151f59d4..1bbec209 100644 --- a/wrolpi/collections/types.py +++ b/wrolpi/collections/types.py @@ -141,3 +141,9 @@ collection_type_registry.register( validate_channel_name, # Permissive: any non-empty name. 'Playlist name must be a non-empty string' ) + +collection_type_registry.register( + 'repo', + validate_channel_name, # Permissive: any non-empty name. + 'Repo name must be a non-empty string' +) diff --git a/wrolpi/common.py b/wrolpi/common.py index 42ba5acd..a8e37bf5 100644 --- a/wrolpi/common.py +++ b/wrolpi/common.py @@ -43,7 +43,7 @@ from wrolpi.dates import now, from_timestamp from wrolpi.errors import WROLModeEnabled, NativeOnly, LogLevelError, InvalidConfig, \ ValidationError from wrolpi.log_levels import TRACE_LEVEL -from wrolpi.vars import PYTEST, DOCKERIZED, CONFIG_DIR, MEDIA_DIRECTORY, DEFAULT_HTTP_HEADERS +from wrolpi.vars import PYTEST, DOCKERIZED, CONFIG_DIR, MEDIA_DIRECTORY, DEFAULT_HTTP_HEADERS, REPOS_DIRECTORY def add_logging_level(level_name: str, level_int: int, methodName=None): @@ -445,7 +445,7 @@ def get_media_directory() -> Path: DB_CONFIG_FILE_NAMES = {'tags.yaml', 'channels.yaml', 'domains.yaml', 'download_manager.yaml', - 'playlists.yaml'} + 'playlists.yaml', 'repos.yaml'} class ConfigFile: @@ -1109,6 +1109,7 @@ class WROLPiConfigValidator: map_destination: str = None nav_color: str = None playlists_destination: str = None + repos_destination: str = None require_cookies_unlocked: bool = None require_media_mounted: bool = None save_ffprobe_json: bool = None @@ -1177,6 +1178,10 @@ def get_all_configs() -> Dict[str, ConfigFile]: if playlists_config := get_playlists_config(): all_configs[playlists_config.file_name] = playlists_config + from modules.repos.lib import get_repos_config + if repos_config := get_repos_config(): + all_configs[repos_config.file_name] = repos_config + return all_configs @@ -1263,6 +1268,16 @@ async def import_all_db_configs() -> dict[str, bool]: logger.warning(f'Failed to import playlists config: {e}') results['playlists'] = False + # Repos (kind='repo' collections; uses tags, links to downloads) + try: + from modules.repos.lib import import_repos_config + await asyncio.to_thread(import_repos_config) + results['repos'] = True + logger.debug('repos config imported') + except Exception as e: + logger.warning(f'Failed to import repos config: {e}') + results['repos'] = False + # Map pins (YAML-only, no DB) try: from modules.map.pins import get_map_pins_config @@ -1321,12 +1336,13 @@ class WROLPiConfig(ConfigFile): hotspot_ssid='WROLPi', check_for_upgrades=True, ignore_outdated_zims=False, - ignored_directories=['config', 'tags'], + ignored_directories=['config', 'tags', REPOS_DIRECTORY], log_level='info', map_default_location=None, map_destination='map', nav_color='violet', playlists_destination='playlists', + repos_destination='repos/%(repo_tag)s/%(repo_name)s', require_cookies_unlocked=True, require_media_mounted=True, save_ffprobe_json=True, @@ -1373,12 +1389,18 @@ class WROLPiConfig(ConfigFile): self._config['zims_destination'] = self.zims_destination or self.default_config['zims_destination'] self._config['playlists_destination'] = \ self.playlists_destination or self.default_config['playlists_destination'] + self._config['repos_destination'] = self.repos_destination or self.default_config['repos_destination'] # The playlists directory holds WROLPi-managed hardlinks/stubs; never index it. ignored = list(self._config.get('ignored_directories') or []) if self._config['playlists_destination'] not in ignored: ignored.append(self._config['playlists_destination']) self._config['ignored_directories'] = ignored + # Git repositories are browsed through the Repos module; their files are never indexed. + ignored = list(self._config.get('ignored_directories') or []) + if REPOS_DIRECTORY not in ignored: + ignored.append(REPOS_DIRECTORY) + self._config['ignored_directories'] = ignored self.successful_import = True except Exception as e: @@ -1586,6 +1608,14 @@ class WROLPiConfig(ConfigFile): def playlists_destination(self, value: str): self.update({'playlists_destination': value}) + @property + def repos_destination(self) -> str: + return self._config['repos_destination'] + + @repos_destination.setter + def repos_destination(self, value: str): + self.update({'repos_destination': value}) + @property def map_default_location(self) -> dict: return self._config.get('map_default_location') diff --git a/wrolpi/contexts.py b/wrolpi/contexts.py index 86a74b90..e829f646 100644 --- a/wrolpi/contexts.py +++ b/wrolpi/contexts.py @@ -33,6 +33,7 @@ def attach_shared_contexts(app: Sanic): app.shared_ctx.download_manager_config = manager.dict() app.shared_ctx.videos_downloader_config = manager.dict() app.shared_ctx.domains_config = manager.dict() + app.shared_ctx.repos_config = manager.dict() app.shared_ctx.archive_downloader_config = manager.dict() app.shared_ctx.download_cache_config = manager.dict() app.shared_ctx.map_pins_config = manager.dict() @@ -127,6 +128,7 @@ def reset_shared_contexts(app: Sanic): app.shared_ctx.download_manager_config.clear() app.shared_ctx.videos_downloader_config.clear() app.shared_ctx.domains_config.clear() + app.shared_ctx.repos_config.clear() app.shared_ctx.archive_downloader_config.clear() app.shared_ctx.download_cache_config.clear() # Shared dicts. @@ -295,6 +297,12 @@ def initialize_configs_contexts(app: Sanic): except Exception as e: logger.error(f'Failed to initialize in-memory domains config: {e}') + try: + from modules.repos.lib import repos_config + repos_config.initialize(app.shared_ctx.repos_config) + except Exception as e: + logger.error(f'Failed to initialize in-memory repos config: {e}') + try: from modules.archive.lib import ARCHIVE_DOWNLOADER_CONFIG ARCHIVE_DOWNLOADER_CONFIG.initialize(app.shared_ctx.archive_downloader_config) diff --git a/wrolpi/downloader.py b/wrolpi/downloader.py index 5a634f0f..84727acd 100644 --- a/wrolpi/downloader.py +++ b/wrolpi/downloader.py @@ -499,7 +499,7 @@ class Downloader: async def process_runner(self, download: Download, cmd: Tuple[str | pathlib.Path, ...], cwd: pathlib.Path, timeout: int = None, debug: bool = True, stdout_callback: callable = None, env: dict = None, - start_new_session: bool = False, + start_new_session: bool = False, merge_stderr: bool = False, ctx: 'DownloadContext' = None) -> CommandResult: """ Run a subprocess using the provided arguments. This process can be killed by the Download Manager. @@ -522,7 +522,7 @@ class Downloader: timeout = self.timeout coro = ctx.run_command(cmd, cwd=cwd, timeout=timeout, log_command=debug, stdout_callback=stdout_callback, env=env, - start_new_session=start_new_session) + start_new_session=start_new_session, merge_stderr=merge_stderr) result = await self.cancel_wrapper(coro, download, ctx=ctx) if __debug__ and logger.isEnabledFor(TRACE_LEVEL): diff --git a/wrolpi/root_api.py b/wrolpi/root_api.py index 16848326..a178f6e2 100644 --- a/wrolpi/root_api.py +++ b/wrolpi/root_api.py @@ -18,6 +18,7 @@ from modules.docs.api import docs_bp from modules.flasher.api import flasher_bp from modules.inventory import inventory_bp from modules.map.api import map_bp +from modules.repos.api import repos_bp from modules.videos.api import videos_bp from modules.zim.api import zim_bp from wrolpi import flags, schema, dates @@ -64,6 +65,7 @@ api_app.blueprint(flasher_bp) api_app.blueprint(inventory_bp) api_app.blueprint(jobs_bp) api_app.blueprint(map_bp) +api_app.blueprint(repos_bp) api_app.blueprint(speedtest_bp) api_app.blueprint(videos_bp) api_app.blueprint(zim_bp) @@ -192,6 +194,7 @@ def get_settings(_: Request): 'nav_color': wrolpi_config.nav_color, 'media_directory': str(get_media_directory()), # Convert to string to avoid conversion to relative. 'playlists_destination': wrolpi_config.playlists_destination, + 'repos_destination': wrolpi_config.repos_destination, 'tags_directory': wrolpi_config.tags_directory, 'throttle_on_startup': wrolpi_config.throttle_on_startup, 'version': __version__, @@ -277,6 +280,15 @@ async def update_settings(_: Request, body: schema.SettingsRequest): else: new_config['playlists_destination'] = wrolpi_config.default_config['playlists_destination'] + # The Settings page may not send `repos_destination`; only validate it when it is provided. + if body.repos_destination is not None: + if not body.repos_destination: + new_config['repos_destination'] = wrolpi_config.default_config['repos_destination'] + elif pathlib.Path(body.repos_destination).is_absolute(): + raise InvalidConfig('Repos directory must be relative to media directory') + elif '..' in pathlib.Path(body.repos_destination).parts: + raise InvalidConfig('Repos directory must not contain ".."') + # Validate timezone if provided; empty string clears it. if body.timezone is not None: if body.timezone == '': diff --git a/wrolpi/schema.py b/wrolpi/schema.py index 533ce38b..e0c9d831 100644 --- a/wrolpi/schema.py +++ b/wrolpi/schema.py @@ -53,6 +53,7 @@ class SettingsResponse: archive_destination: str = 'archive/%(domain_tag)s/%(domain)s' map_destination: str = 'map' playlists_destination: str = 'playlists' + repos_destination: str = 'repos/%(repo_tag)s/%(repo_name)s' videos_destination: str = 'videos/%(channel_tag)s/%(channel_name)s' zims_destination: str = 'zims' @@ -100,6 +101,7 @@ class SettingsRequest: nav_color: Optional[str] = None media_directory: Optional[str] = None playlists_destination: Optional[str] = None + repos_destination: Optional[str] = None tags_directory: Optional[bool] = None throttle_on: Optional[bool] = None throttle_on_startup: Optional[bool] = None diff --git a/wrolpi/vars.py b/wrolpi/vars.py index 59b1d219..614326fc 100644 --- a/wrolpi/vars.py +++ b/wrolpi/vars.py @@ -62,6 +62,8 @@ CIRCLECI = truthy_arg(os.environ.get('CIRCLECI', '')) # Get the media directory from the environment. DEFAULT_MEDIA_DIRECTORY = Path('/media/wrolpi') +# Git repositories live here; it is always an ignored directory (repo files are never indexed). +REPOS_DIRECTORY = 'repos' MEDIA_DIRECTORY = Path(os.environ.get('MEDIA_DIRECTORY', DEFAULT_MEDIA_DIRECTORY)) CONFIG_DIR: Path = MEDIA_DIRECTORY / 'config'