From a94261276c0455f6590625da01c800c959bb22af Mon Sep 17 00:00:00 2001 From: Roland Date: Tue, 6 Oct 2026 18:09:52 -0600 Subject: [PATCH] repos: import an existing git clone as a Repo POST /api/repos/import/inspect reports what importing a clone in the media directory would do, without changing it: its origin (an SSH or git:// origin is converted to https://), branch, latest commit, commits not on the remote, whether it is shallow, and where it will be moved. It refuses special directories, Collections' directories, `.git` files/links, bare repos, and partial clones. It runs no git command which could run a program from the clone's config (the latest commit is read with cat-file, not log). POST /api/repos/import (confirmed, with a URL that is the clone's origin) moves the clone into the Repos directory (the old location is refreshed away), sanitizes its config, points origin at the URL, marks it as WROLPi's, and creates the Repo and its Download. The Repo shows the clone's commit and README at once; its first update makes it a mirror (local work is discarded, and the page warns of local commits). The Repos page has an Import button; the Import page inspects the chosen directory, then imports. Co-Authored-By: Claude Opus 5.5 --- app/src/api.js | 19 +++ app/src/components/Common.test.js | 6 +- app/src/components/Repos.js | 207 ++++++++++++++++++++++++- app/src/components/Repos.test.js | 88 ++++++++++- app/src/components/ThemeSamplePage.js | 12 +- modules/repos/api.py | 38 +++++ modules/repos/lib.py | 211 ++++++++++++++++++++++++-- modules/repos/schema.py | 21 +++ modules/repos/test/test_import.py | 209 +++++++++++++++++++++++++ 9 files changed, 791 insertions(+), 20 deletions(-) create mode 100644 modules/repos/test/test_import.py diff --git a/app/src/api.js b/app/src/api.js index 4b2eaca1..4699819f 100644 --- a/app/src/api.js +++ b/app/src/api.js @@ -2596,3 +2596,22 @@ export async function getRepoLog(repoId, offset = 0, limit = 50) { export function repoArchiveURL(repoId) { return `${REPOS_API}/${repoId}/archive.zip`; } + +// What importing the git clone in `directory` (relative to the media directory) would do. Changes nothing. +export async function inspectRepoImport(directory, name, tagName) { + const body = {directory, name: name || null, tag_name: tagName || null}; + const response = await apiPost(`${REPOS_API}/import/inspect`, body); + if (response.ok) { + return {inspection: (await response.json())['inspection']}; + } + return {error: await getErrorMessage(response, 'Cannot import this directory.')}; +} + +// Import an existing git clone as a Repo. `repo`: {directory, confirm, url?, name?, tag_name?, frequency?, ...} +export async function importRepo(repo) { + const response = await apiPost(`${REPOS_API}/import`, repo); + if (response.ok) { + return (await response.json())['repo']; + } + await reposError(response, 'Failed to import the repo.'); +} diff --git a/app/src/components/Common.test.js b/app/src/components/Common.test.js index 74ea1f8d..14559845 100644 --- a/app/src/components/Common.test.js +++ b/app/src/components/Common.test.js @@ -1121,7 +1121,7 @@ describe('a row of buttons', () => { * the two had been inline before. * * A row fixes it without touching the stack: the row is the stretched child, and it lays - * its buttons out at their own width. Twelve sites, so this scan rather than twelve + * its buttons out at their own width. Thirteen sites, so this scan rather than thirteen * assertions -- and a scan because a stretched button is still a working button. */ const offenders = []; @@ -1140,8 +1140,8 @@ describe('a row of buttons', () => { } } - // Twelve renders. Common.js declares it, and a declaration is not a ` - + + + + ; return <> @@ -682,6 +688,204 @@ export function RepoSettingsFields({ ; } +/** What importing a clone would do: its origin, latest commit, and where it will be moved. */ +export function RepoImportSummary({inspection}) { + const muted = {color: 'var(--muted)'}; + return + + +
Origin
+ {inspection.origin || 'None'} +
+ +
Branch
+ + {inspection.branch || 'Detached'} + +
+ {inspection.head_sha && +
Latest commit
+ + + {inspection.head_sha.slice(0, 7)} + {inspection.head_message} + {inspection.head_date && {isoDatetimeToAgoPopup(inspection.head_date)}} + +
} +
+ {inspection.local_commits > 0 && +

They will be discarded by the first update. Push them first if you want to keep them.

+
} + {inspection.shallow && +

In Full history mode, the first update downloads the rest of its history.

+
} + {inspection.destination_exists + ? +

Choose another name or tag.

+
+ :

+ {inspection.will_move + ? <>It will be moved to {inspection.destination}. + : <>It will stay in {inspection.destination}.} +

} +
; +} + +export function RepoImportPage() { + useTitle('Import Repo'); + const navigate = useNavigate(); + const wrolMode = useWROLMode(); + const [directory, setDirectory] = useState(''); + const [inspection, setInspection] = useState(null); + const [inspectError, setInspectError] = useState(null); + const [url, setUrl] = useState(''); + const [name, setName] = useState(''); + const [tagName, setTagName] = useState(null); + const [frequency, setFrequency] = useState(String(weeklyOption.value)); + const [mode, setMode] = useState('full'); + const [branch, setBranch] = useState(''); + const [submodules, setSubmodules] = useState(false); + const [confirm, setConfirm] = useState(false); + const [submitting, setSubmitting] = useState(false); + + // Inspect the directory again whenever it, the name, or the Tag change (they decide where it will be moved). + useEffect(() => { + if (!directory) { + setInspection(null); + setInspectError(null); + return; + } + let current = true; + const timer = setTimeout(async () => { + const {inspection: newInspection, error} = await inspectRepoImport(directory, name.trim(), tagName); + if (!current) return; + setInspection(newInspection || null); + setInspectError(error || null); + if (newInspection && !url) { + setUrl(newInspection.url || ''); + } + }, 300); + return () => { + current = false; + clearTimeout(timer); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [directory, name, tagName]); + + const handleDirectory = (value) => { + setDirectory(value || ''); + setUrl(''); + setConfirm(false); + }; + + const urlIsValid = !!safeRepoHref(url.trim()); + const canImport = inspection && !inspection.destination_exists && urlIsValid && confirm && !submitting + && !wrolMode; + + const handleSubmit = async (e) => { + e.preventDefault(); + if (!canImport) return; + setSubmitting(true); + try { + const repo = await importRepo({ + directory, + confirm, + url: url.trim(), + name: name.trim() || null, + tag_name: tagName, + frequency: parseInt(frequency), + mode, + branch: branch.trim() || null, + submodules, + }); + toast({type: 'success', title: 'Repo imported', description: repo.name, time: 3000}); + navigate(`/repos/${repo.id}`); + } catch (e) { + // Error toast already shown by the API client. + } finally { + setSubmitting(false); + } + }; + + return <> +
+ +
Import Repo
+

+ Import a git clone that is already in your media directory. WROLPi moves it into the Repos + directory and keeps it up to date, as a mirror of its origin. +

+
+ + + + + + {inspectError && +

{inspectError}

+
} + {inspection && <> + + + setUrl(e.currentTarget.value)} + /> + + + setName(e.currentTarget.value)} + /> + + + + setTagName(null)} + /> + + + {inspection.branch && + + The clone is on {inspection.branch}. Enter it as the Branch to keep + following it; otherwise the repo follows the remote's default branch. + + } + + setConfirm(e.currentTarget.checked)} + /> + + + + + } +
+
+
+ ; +} + export function RepoEditPage() { const {repoId} = useParams(); const {repo, refetch} = useRepo(repoId); @@ -830,6 +1034,7 @@ export function ReposRoute() { }/> }/> + }/> }/> }/> diff --git a/app/src/components/Repos.test.js b/app/src/components/Repos.test.js index aba557e5..e8b3b325 100644 --- a/app/src/components/Repos.test.js +++ b/app/src/components/Repos.test.js @@ -3,13 +3,17 @@ import {Route, Routes} from 'react-router'; import {act, fireEvent, render, screen, within} from '../test-utils'; import { RepoEditPage, + RepoImportPage, repoNameFromURL, RepoNewPage, ReposPage, RepoViewPage, safeRepoHref, } from './Repos'; -import {createRepo, deleteRepo, fetchRepos, getFile, getRepo, getRepoLog, getRepoTree, updateRepo} from '../api'; +import { + createRepo, deleteRepo, fetchRepos, getFile, getRepo, getRepoLog, getRepoTree, importRepo, inspectRepoImport, + updateRepo, +} from '../api'; import {FilePreviewContext} from './FilePreview'; jest.mock('../api', () => ({ @@ -21,9 +25,19 @@ jest.mock('../api', () => ({ getRepo: jest.fn(), getRepoLog: jest.fn(), getRepoTree: jest.fn(), + importRepo: jest.fn(), + inspectRepoImport: jest.fn(), updateRepo: jest.fn(), })); +// The directory picker searches the server; picking a directory is all these specs need. +jest.mock('./Common', () => ({ + ...jest.requireActual('./Common'), + DirectorySearch: ({onSelect}) => , +})); + // The README is fetched from the media server; its rendering is MarkdownPreview's own spec. jest.mock('./MarkdownPreview', () => ({ ...jest.requireActual('./MarkdownPreview'), @@ -279,3 +293,75 @@ describe('RepoEditPage', () => { expect(screen.getByText('repos page')).toBeInTheDocument(); }); }); + +describe('RepoImportPage', () => { + const inspection = (overrides = {}) => ({ + directory: 'code/kiwix-tools', origin: 'git@github.com:kiwix/kiwix-tools.git', + url: 'https://github.com/kiwix/kiwix-tools', name: 'kiwix-tools', branch: 'main', + head_sha: 'abcdef1234', head_message: 'Local work', head_date: '2026-09-30T14:02:00Z', local_commits: 2, + shallow: false, destination: 'repos/kiwix-tools', will_move: true, destination_exists: false, + ...overrides, + }); + + function renderImportPage() { + return render( + }/> + repo page}/> + , {route: '/repos/import'}); + } + + it('inspects the directory, warns about local commits, and imports once confirmed', async () => { + inspectRepoImport.mockResolvedValue({inspection: inspection()}); + importRepo.mockResolvedValue(repoFixture({id: 9})); + renderImportPage(); + + fireEvent.click(screen.getByText('Pick directory')); + expect(await screen.findByText('2 commits are not on the remote')).toBeInTheDocument(); + expect(inspectRepoImport).toHaveBeenCalledWith('code/kiwix-tools', '', null); + expect(screen.getByText('git@github.com:kiwix/kiwix-tools.git')).toBeInTheDocument(); + expect(screen.getByText('repos/kiwix-tools')).toBeInTheDocument(); + // The URL comes from the origin. + expect(screen.getByLabelText(/^URL/)).toHaveValue('https://github.com/kiwix/kiwix-tools'); + + const button = screen.getByText('Import').closest('button'); + expect(button).toBeDisabled(); + fireEvent.click(screen.getByLabelText(/I understand/)); + expect(button).toBeEnabled(); + fireEvent.click(button); + await flush(); + + expect(importRepo).toHaveBeenCalledWith({ + directory: 'code/kiwix-tools', confirm: true, url: 'https://github.com/kiwix/kiwix-tools', name: null, + tag_name: null, frequency: 604800, mode: 'full', branch: null, submodules: false, + }); + expect(screen.getByText('repo page')).toBeInTheDocument(); + }); + + it('asks for the URL when the clone has no https origin', async () => { + inspectRepoImport.mockResolvedValue({inspection: inspection({origin: null, url: null, local_commits: 0})}); + renderImportPage(); + fireEvent.click(screen.getByText('Pick directory')); + expect(await screen.findByText(/no https:\/\/ origin/)).toBeInTheDocument(); + fireEvent.click(screen.getByLabelText(/I understand/)); + expect(screen.getByText('Import').closest('button')).toBeDisabled(); + fireEvent.change(screen.getByLabelText(/^URL/), {target: {value: 'https://github.com/kiwix/kiwix-tools'}}); + expect(screen.getByText('Import').closest('button')).toBeEnabled(); + }); + + it('explains a directory which cannot be imported', async () => { + inspectRepoImport.mockResolvedValue({error: 'code/kiwix-tools is not a git clone'}); + renderImportPage(); + fireEvent.click(screen.getByText('Pick directory')); + expect(await screen.findByText('code/kiwix-tools is not a git clone')).toBeInTheDocument(); + expect(screen.queryByText('Import')).not.toBeInTheDocument(); + }); + + it('refuses a destination which already exists', async () => { + inspectRepoImport.mockResolvedValue({inspection: inspection({destination_exists: true})}); + renderImportPage(); + fireEvent.click(screen.getByText('Pick directory')); + expect(await screen.findByText('repos/kiwix-tools already exists')).toBeInTheDocument(); + fireEvent.click(screen.getByLabelText(/I understand/)); + expect(screen.getByText('Import').closest('button')).toBeDisabled(); + }); +}); diff --git a/app/src/components/ThemeSamplePage.js b/app/src/components/ThemeSamplePage.js index 93cc18bb..1859dcdb 100644 --- a/app/src/components/ThemeSamplePage.js +++ b/app/src/components/ThemeSamplePage.js @@ -49,7 +49,9 @@ import {contrastingColor} from './Common'; import {navBarStyle, navColorNames, useNavColors} from '../themes/navColors'; import {IconMenu2} from '@tabler/icons-react'; import {BookmarkAddForms, BookmarkMenuItems, BookmarkTable} from './Bookmarks'; -import {RepoBreadcrumb, RepoHistoryTable, RepoStatusIcon, RepoSummary, RepoTreeTable} from './Repos'; +import { + RepoBreadcrumb, RepoHistoryTable, RepoImportSummary, RepoStatusIcon, RepoSummary, RepoTreeTable, +} from './Repos'; /* * A gallery of every component in the library, in the current theme. @@ -1167,6 +1169,14 @@ export function ThemeSamplePage() {
+
+ +
diff --git a/modules/repos/api.py b/modules/repos/api.py index d20c7892..9650ac48 100644 --- a/modules/repos/api.py +++ b/modules/repos/api.py @@ -46,6 +46,44 @@ async def post_repo(request: Request, body: schema.RepoCreateRequest): return json_response(dict(repo=repo.__json__()), status=HTTPStatus.CREATED) +@repos_bp.post('/import/inspect') +@openapi.definition( + summary='What importing an existing git clone (in the media directory) as a Repo would do. Changes nothing.', + body=schema.RepoImportInspectRequest, + validate=True, +) +async def post_inspect_import(request: Request, body: schema.RepoImportInspectRequest): + info = lib.inspect_import(request.ctx.session, body.directory, body.name or None, body.tag_name or None) + return json_response(dict(inspection=info)) + + +@repos_bp.post('/import') +@openapi.definition( + summary='Import an existing git clone as a Repo. It is moved into the Repos directory, and becomes a mirror of ' + 'its origin (local changes are discarded by its updates).', + body=schema.RepoImportRequest, + validate=True, +) +@wrol_mode_check +async def post_import(request: Request, body: schema.RepoImportRequest): + session = request.ctx.session + repo = await lib.import_repository( + session, + body.directory, + url=body.url or None, + confirm=body.confirm, + 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, + submodules=body.submodules, + 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.post('/search') @openapi.definition( summary='Search git Repos by their name and README, and/or by Tag', diff --git a/modules/repos/lib.py b/modules/repos/lib.py index 2569d529..4e1a5642 100644 --- a/modules/repos/lib.py +++ b/modules/repos/lib.py @@ -9,6 +9,7 @@ import socket import stat import subprocess from dataclasses import dataclass, field +from datetime import datetime, timedelta, timezone from typing import List, NamedTuple, Optional, Tuple from urllib.parse import urlparse @@ -33,13 +34,14 @@ from .models import Repository, REPO_MODES logger = logger.getChild(__name__) __all__ = ['ParsedRepoURL', 'parse_repo_url', 'repo_url_key', 'git_command', 'git_env', 'REPO_MARKER', - 'clone_ownership_error', 'mark_clone', 'sanitize_git_config', 'create_repository', 'update_repository', - 'delete_repository', 'get_repositories', 'list_repo_tree', 'find_readme', 'repos_destination_root', - 'validate_repos_destination', 'is_valid_branch', 'submodule_url_error', 'HostAddresses', - 'resolve_repo_addresses', 'pin_config', 'is_public_address', 'submodule_fetch_config', 'read_readme_text', - 'search_repos', 'count_repos', 'search_repos_by_name', 'get_repo_log', 'get_repo_root', - 'repo_archive_name', 'stream_repo_archive', 'ReposConfig', 'repos_config', 'get_repos_config', - 'save_repos_config', 'import_repos_config', 'DEFAULT_REPO_FREQUENCY'] + 'clone_ownership_error', 'mark_clone', 'sanitize_git_config', 'create_repository', 'remote_url_key', + 'remote_https_url', 'resolve_import_directory', 'inspect_import', 'import_repository', + 'update_repository', 'delete_repository', 'get_repositories', 'list_repo_tree', 'find_readme', + 'repos_destination_root', 'validate_repos_destination', 'is_valid_branch', 'submodule_url_error', + 'HostAddresses', 'resolve_repo_addresses', 'pin_config', 'is_public_address', 'submodule_fetch_config', + 'read_readme_text', 'search_repos', 'count_repos', 'search_repos_by_name', 'get_repo_log', + 'get_repo_root', 'repo_archive_name', 'stream_repo_archive', 'ReposConfig', 'repos_config', + 'get_repos_config', 'save_repos_config', 'import_repos_config', 'DEFAULT_REPO_FREQUENCY'] DEFAULT_REPO_FREQUENCY = DownloadFrequency.weekly.value @@ -592,9 +594,29 @@ def create_repository(session: Session, url: str, tag_name: str = None, frequenc mode: str = 'full', branch: str = None, name: str = None, description: str = None, directory: pathlib.Path = None, submodules: bool = False) -> Repository: """Create a Repo (Collection + Repository + recurring Download). The download clones it.""" + _validate_frequency(frequency) + repo = _create_repository_records(session, url, tag_name, mode, branch, name, description, directory, submodules) + _create_repository_download(session, repo, frequency) + return repo + + +def _create_repository_download(session: Session, repo: Repository, frequency: int): + """Create the recurring Download which keeps the Repo up to date, and save the Repo.""" + download = repo.collection.get_or_create_download(session, repo.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() + + +def _create_repository_records(session: Session, url: str, tag_name: str, mode: str, branch: Optional[str], + name: Optional[str], description: Optional[str], directory: Optional[pathlib.Path], + submodules: bool) -> Repository: + """Create (but do not commit) a Repo's Collection and Repository, in their directory.""" parsed = parse_repo_url(url) _validate_mode(mode) - _validate_frequency(frequency) branch = branch or parsed.branch or None _validate_branch(branch) name = (name or parsed.name).strip() @@ -623,14 +645,175 @@ def create_repository(session: Session, url: str, tag_name: str = None, frequenc relative = get_relative_to_media_directory(directory) raise RepoConflict(f'Another collection already uses the directory {relative}') collection.directory = directory + return repo - 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() +def remote_url_key(url: str) -> Optional[str]: + """`host/path` of a git remote URL in any form (https://, ssh://, git://, or `user@host:path`), to compare remotes. + None for a local path.""" + url = (url or '').strip() + if re.match(r'^[A-Za-z][A-Za-z0-9+.-]*://', url): + parsed = urlparse(url) + host, path = parsed.hostname, parsed.path + elif match := re.match(r'^(?:[^@/]+@)?(?P[^:/]+):(?P[^/].*)$', url): + host, path = match.group('host'), match.group('path') + else: + return None + if not host: + return None + return f'{host.lower()}/{path.strip("/").removesuffix(".git")}' + + +def remote_https_url(url: str) -> Optional[str]: + """The https:// URL of a git remote URL (e.g. `git@codeberg.org:owner/repo.git`), if it has one.""" + url = (url or '').strip() + if url.startswith('https://'): + return url + if url.startswith(('ssh://', 'git://')) or re.match(r'^(?:[^@/]+@)?[^:/]+:[^/]', url): + key = remote_url_key(url) + return f'https://{key}' if key else None + return None + + +def resolve_import_directory(session: Session, directory: str) -> pathlib.Path: + """The absolute directory of a git clone in the media directory which may be imported as a Repo.""" + media_directory = get_media_directory().resolve() + relative = pathlib.Path((directory or '').strip()) + if not str(relative) or relative.is_absolute() or '..' in relative.parts: + raise InvalidRepo('The directory must be relative to the media directory') + path = media_directory / relative + if path.is_symlink() or not path.is_dir(): + raise UnknownDirectory(f'No directory {directory!r}') + path = path.resolve() + if path == media_directory or media_directory not in path.parents: + raise InvalidRepo('The directory must be in the media directory') + + # Imported repos are moved, so no special directory (or anything holding one) may be imported. + from wrolpi.files.lib import get_special_directories + for special in (*get_special_directories(), media_directory / 'config', media_directory / 'tags'): + special = special.resolve() + if path == special or path in special.parents: + raise InvalidRepo(f'{get_relative_to_media_directory(special)} cannot be imported') + + for other in session.query(Collection.directory).filter(Collection.directory.isnot(None)): + other = pathlib.Path(other[0]).resolve() + if path == other or other in path.parents or path in other.parents: + raise RepoConflict(f'{directory} is (or holds, or is in) the directory of a Collection') + + git_dir = path / '.git' + if git_dir.is_symlink() or not git_dir.is_dir(): + raise InvalidRepo(f'{directory} is not a git clone (it has no .git directory)') + return path + + +def _git_output_sync(directory: pathlib.Path, *args) -> Optional[str]: + result = subprocess.run(git_command(*args), cwd=directory, env=git_env(), capture_output=True) + return result.stdout.decode(errors='replace').strip() if result.returncode == 0 else None + + +def _read_head_commit(directory: pathlib.Path) -> dict: + """The sha, date and message of a clone's HEAD. Reads the commit object itself (`git log` could run programs + from the clone's config, e.g. gpg).""" + sha = _git_output_sync(directory, 'rev-parse', '--verify', '--quiet', 'HEAD^{commit}') + if not sha: + return dict(head_sha=None, head_date=None, head_message=None) + raw = _git_output_sync(directory, 'cat-file', 'commit', sha) or '' + headers, _, message = raw.partition('\n\n') + head_date = None + for line in headers.splitlines(): + if line.startswith('committer ') and (match := re.search(r' (\d+) ([+-])(\d\d)(\d\d)$', line)): + offset = (int(match.group(3)) * 60 + int(match.group(4))) * (1 if match.group(2) == '+' else -1) + head_date = datetime.fromtimestamp(int(match.group(1)), timezone(timedelta(minutes=offset))) + return dict(head_sha=sha, head_date=head_date, head_message=message.strip().split('\n')[0] or None) + + +def inspect_import(session: Session, directory: str, name: str = None, tag_name: str = None) -> dict: + """What importing the git clone in `directory` as a Repo would do. Changes nothing.""" + path = resolve_import_directory(session, directory) + entries = _git_config_entries(path / '.git/config') + keys = {key.lower() for key, _ in entries} + if 'core.bare' in keys and any(k.lower() == 'core.bare' and v.lower() == 'true' for k, v in entries): + raise InvalidRepo(f'{directory} is a bare repository') + if 'extensions.partialclone' in keys or any(re.match(r'^remote\..+\.promisor$', k, re.I) for k in keys): + # Its missing objects would have to be fetched from the network. + raise InvalidRepo(f'{directory} is a partial clone, which cannot be imported') + origins = [v for k, v in entries if k.lower() == 'remote.origin.url'] + origin = origins[0] if len(origins) == 1 else None + + url = remote_https_url(origin) if origin else None + parsed = None + if url: + try: + parsed = parse_repo_url(url) + url = parsed.url + except InvalidRepo: + url = None + name = (name or (parsed.name if parsed else path.name)).strip() + destination = format_repo_destination(name, tag_name, parsed.owner if parsed else None, + parsed.host if parsed else None) + + head = (path / '.git/HEAD').read_text(errors='replace').strip() if (path / '.git/HEAD').is_file() else '' + branch = head[len('ref: refs/heads/'):] if head.startswith('ref: refs/heads/') else None + local_commits = _git_output_sync(path, 'rev-list', '--count', 'HEAD', '--not', '--remotes') + return dict( + directory=str(get_relative_to_media_directory(path)), + origin=origin, + url=url, + name=name, + branch=branch if branch and is_valid_branch(branch) else None, + **_read_head_commit(path), + local_commits=int(local_commits) if local_commits and local_commits.isdigit() else None, + shallow=(path / '.git/shallow').is_file(), + destination=str(get_relative_to_media_directory(destination)), + will_move=destination.resolve() != path, + destination_exists=destination.resolve() != path and destination.exists(), + ) + + +async def import_repository(session: Session, directory: str, url: str = None, confirm: bool = False, + tag_name: str = None, frequency: int = DEFAULT_REPO_FREQUENCY, mode: str = 'full', + branch: str = None, submodules: bool = False, name: str = None, + description: str = None) -> Repository: + """Import the git clone in `directory` as a Repo: it is moved into the Repos directory, and from then on is a + mirror of `url` (which must be the clone's origin). Local changes and commits are discarded by its updates.""" + _validate_frequency(frequency) + info = inspect_import(session, directory, name, tag_name) + source = resolve_import_directory(session, directory) + url = (url or info['url'] or '').strip() + if not url: + raise InvalidRepo("Enter the repo's https:// URL") + parsed = parse_repo_url(url) + if info['origin'] and remote_url_key(info['origin']) != remote_url_key(parsed.url): + raise InvalidRepo(f"The URL is not this clone's origin ({info['origin']})") + if not confirm: + raise ValidationError('Confirm that this clone will become a mirror, and its local changes discarded') + + # Like a new Repo, an imported one follows the remote's default branch unless a branch is chosen. + repo = _create_repository_records(session, parsed.url, tag_name, mode, branch, info['name'], description, None, + submodules) + destination = repo.directory + if destination.resolve() != source: + if source in destination.resolve().parents: + raise InvalidRepo('A repo cannot be moved into itself') + if destination.exists(): + raise RepoConflict(f'{get_relative_to_media_directory(destination)} already exists') + destination.parent.mkdir(parents=True, exist_ok=True) + await asyncio.to_thread(shutil.move, source, destination) + logger.info(f'Imported repo moved from {source} to {destination}') + # Forget the files that were indexed in the old location. + from wrolpi.files.worker import file_worker + file_worker.queue_refresh([source]) + + await asyncio.to_thread(sanitize_git_config, destination) + await asyncio.to_thread(_git_output_sync, destination, 'config', '--replace-all', 'remote.origin.url', parsed.url) + mark_clone(destination, parsed.url) + + for key, value in _read_head_commit(destination).items(): + setattr(repo, key, value) + repo.readme_path = find_readme(destination) + repo.readme_text = read_readme_text(destination / repo.readme_path) if repo.readme_path else None + repo.size = await asyncio.to_thread(get_repo_size, destination) + _create_repository_download(session, repo, frequency) return repo diff --git a/modules/repos/schema.py b/modules/repos/schema.py index dd67d6a9..85163f32 100644 --- a/modules/repos/schema.py +++ b/modules/repos/schema.py @@ -29,3 +29,24 @@ class RepoUpdateRequest: mode: Optional[str] = None branch: Optional[str] = None submodules: Optional[bool] = None + + +@dataclass +class RepoImportInspectRequest: + directory: str + name: Optional[str] = None + tag_name: Optional[str] = None + + +@dataclass +class RepoImportRequest: + directory: str + confirm: bool = False + url: Optional[str] = None + tag_name: Optional[str] = None + frequency: Optional[int] = None + mode: Optional[str] = None + branch: Optional[str] = None + submodules: bool = False + name: Optional[str] = None + description: Optional[str] = None diff --git a/modules/repos/test/test_import.py b/modules/repos/test/test_import.py new file mode 100644 index 00000000..612f9867 --- /dev/null +++ b/modules/repos/test/test_import.py @@ -0,0 +1,209 @@ +import json +import subprocess +from http import HTTPStatus + +import pytest + +from modules.repos import lib +from modules.repos.errors import InvalidRepo, RepoConflict +from modules.repos.models import Repository +from wrolpi.downloader import Download, DownloadStatus +from wrolpi.errors import UnknownDirectory, ValidationError +from wrolpi.files.models import FileGroup + + +def git(directory, *args) -> str: + env = dict(GIT_AUTHOR_NAME='t', GIT_AUTHOR_EMAIL='t@t', GIT_COMMITTER_NAME='t', GIT_COMMITTER_EMAIL='t@t', + PATH='/usr/bin:/bin:/usr/local/bin:/opt/homebrew/bin') + return subprocess.run(['git', '-c', 'safe.directory=*', *args], cwd=directory, check=True, env=env, + capture_output=True).stdout.decode().strip() + + +@pytest.fixture +def user_clone(test_directory, git_remote_factory): + """A clone the user made themselves, in their media directory, with an `origin`.""" + + def factory(relative='code/kiwix-tools', remote=None): + remote = remote or git_remote_factory('kiwix-tools', owner='kiwix', files={'README.md': '# Kiwix tools'}) + directory = test_directory / relative + directory.parent.mkdir(parents=True, exist_ok=True) + git(directory.parent, 'clone', '--quiet', str(remote.path), directory.name) + git(directory, 'remote', 'set-url', 'origin', remote.url) + return directory, remote + + return factory + + +@pytest.mark.parametrize('origin,expected', [ + ('https://github.com/kiwix/kiwix-tools', 'https://github.com/kiwix/kiwix-tools'), + ('https://github.com/kiwix/kiwix-tools.git', 'https://github.com/kiwix/kiwix-tools.git'), + ('git@github.com:kiwix/kiwix-tools.git', 'https://github.com/kiwix/kiwix-tools'), + ('ssh://git@github.com:22/kiwix/kiwix-tools.git', 'https://github.com/kiwix/kiwix-tools'), + ('git://github.com/kiwix/kiwix-tools', 'https://github.com/kiwix/kiwix-tools'), + ('/home/user/kiwix-tools', None), + ('../kiwix-tools', None), +]) +def test_remote_https_url(origin, expected): + assert lib.remote_https_url(origin) == expected + + +def test_remote_url_key(): + assert lib.remote_url_key('git@GitHub.com:kiwix/kiwix-tools.git') == \ + lib.remote_url_key('https://github.com/kiwix/kiwix-tools/') == 'github.com/kiwix/kiwix-tools' + assert lib.remote_url_key('https://github.com/kiwix/other') != lib.remote_url_key('https://github.com/kiwix/x') + assert lib.remote_url_key('/local/path') is None + + +@pytest.mark.asyncio +async def test_inspect_import(test_session, async_client, test_wrolpi_config, user_clone): + """Inspecting a clone reports what an import would do, and changes nothing.""" + directory, remote = user_clone() + git(directory, 'commit', '--quiet', '--allow-empty', '-m', 'Local work') + config_before = (directory / '.git/config').read_text() + + request, response = await async_client.post('/api/repos/import/inspect', + content=json.dumps(dict(directory='code/kiwix-tools', + tag_name='Software'))) + assert response.status_code == HTTPStatus.OK, response.json + info = response.json['inspection'] + assert info['directory'] == 'code/kiwix-tools' + assert info['origin'] == remote.url + assert info['url'] == remote.url + assert info['name'] == 'kiwix-tools' + assert info['branch'] == 'main' + assert info['head_message'] == 'Local work' + assert info['head_sha'] == git(directory, 'rev-parse', 'HEAD') + assert info['head_date'] + assert info['local_commits'] == 1 + assert info['shallow'] is False + assert info['destination'] == 'repos/Software/kiwix-tools' + assert info['will_move'] is True + assert info['destination_exists'] is False + + assert (directory / '.git/config').read_text() == config_before + assert not (directory / '.git' / lib.REPO_MARKER).exists() + + +@pytest.mark.asyncio +async def test_inspect_import_refuses(test_session, test_directory, async_client, test_wrolpi_config, user_clone): + (test_directory / 'not-git').mkdir() + with pytest.raises(InvalidRepo): + lib.inspect_import(test_session, 'not-git') + with pytest.raises(UnknownDirectory): + lib.inspect_import(test_session, 'missing') + for directory in ('', '/etc', '../outside', 'config', 'tags', 'videos'): + (test_directory / 'videos').mkdir(exist_ok=True) + with pytest.raises((InvalidRepo, UnknownDirectory)): + lib.inspect_import(test_session, directory) + + # `.git` must be the clone's own directory. + (test_directory / 'gitfile').mkdir() + (test_directory / 'gitfile/.git').write_text('gitdir: /etc\n') + with pytest.raises(InvalidRepo): + lib.inspect_import(test_session, 'gitfile') + + # A partial clone's missing objects would come from the network. + directory, _ = user_clone('code/partial') + git(directory, 'config', 'remote.origin.promisor', 'true') + with pytest.raises(InvalidRepo, match='partial clone'): + lib.inspect_import(test_session, 'code/partial') + + # Already a Repo, or inside one. + repo = lib.create_repository(test_session, 'https://github.com/a/b') + repo.directory.mkdir(parents=True) + git(repo.directory, 'init', '--quiet') + with pytest.raises(RepoConflict): + lib.inspect_import(test_session, 'repos/b') + + +@pytest.mark.asyncio +async def test_import(test_session, test_directory, async_client, test_wrolpi_config, user_clone, + repos_download_manager, refresh_files): + """An imported clone is moved into the Repos directory, owned by WROLPi, and updated like any Repo.""" + directory, remote = user_clone() + (directory / 'local-note.txt').write_text('untracked') + with (directory / '.git/config').open('a') as fh: + fh.write('[http]\n\tproxy = http://127.0.0.1:9\n[user]\n\tname = Someone\n') + # The clone was indexed where it was. + await refresh_files() + assert test_session.query(FileGroup).filter(FileGroup.primary_path.contains('code/kiwix-tools')).count() + + body = dict(directory='code/kiwix-tools', tag_name='Software', confirm=True, frequency=86400) + request, response = await async_client.post('/api/repos/import', content=json.dumps(body)) + assert response.status_code == HTTPStatus.CREATED, response.json + imported = response.json['repo'] + assert imported['name'] == 'kiwix-tools' + assert imported['url'] == remote.url + assert imported['directory'] == 'repos/Software/kiwix-tools' + assert imported['tag_name'] == 'Software' + assert imported['frequency'] == 86400 + assert imported['branch'] is None # Follows the default branch, like a new Repo. + assert imported['head_sha'] == remote.head + assert imported['readme_path'] == 'README.md' + + new_directory = test_directory / 'repos/Software/kiwix-tools' + assert not directory.exists() + assert (new_directory / 'README.md').is_file() + assert (new_directory / '.git' / lib.REPO_MARKER).is_file() + config = (new_directory / '.git/config').read_text() + assert 'proxy' not in config and 'Someone' not in config + # The old location is forgotten; the new one is never indexed. + await refresh_files() + assert test_session.query(FileGroup).filter(FileGroup.primary_path.contains('kiwix-tools')).count() == 0 + + # From now on it is a mirror: an update fetches the origin, and discards local files. + await repos_download_manager.wait_for_all_downloads() + head = remote.commit({'new.txt': 'new'}, 'New upstream') + download = test_session.query(Download).one() + download.renew() + test_session.commit() + await repos_download_manager.wait_for_all_downloads() + test_session.expire_all() + download = test_session.query(Download).one() + assert download.status == DownloadStatus.complete, download.error + assert test_session.query(Repository).one().head_sha == head + assert (new_directory / 'new.txt').is_file() + assert not (new_directory / 'local-note.txt').exists() + + +@pytest.mark.asyncio +async def test_import_in_place(test_session, test_directory, async_client, test_wrolpi_config, user_clone): + """A clone already where its Repo would be is not moved.""" + directory, remote = user_clone('repos/kiwix-tools') + repo = await lib.import_repository(test_session, 'repos/kiwix-tools', confirm=True) + assert repo.directory == directory + assert (directory / '.git' / lib.REPO_MARKER).is_file() + + +@pytest.mark.asyncio +async def test_import_refuses(test_session, test_directory, async_client, test_wrolpi_config, user_clone, + git_remote_factory): + directory, remote = user_clone() + + # Without confirmation. + with pytest.raises(ValidationError): + await lib.import_repository(test_session, 'code/kiwix-tools') + # A URL which is not the clone's origin. + with pytest.raises(InvalidRepo, match="not this clone's origin"): + await lib.import_repository(test_session, 'code/kiwix-tools', url='https://github.com/evil/other', + confirm=True) + # The destination is taken. + (test_directory / 'repos/kiwix-tools').mkdir(parents=True) + with pytest.raises(RepoConflict): + await lib.import_repository(test_session, 'code/kiwix-tools', confirm=True) + test_session.rollback() + assert test_session.query(Repository).count() == 0 + assert (directory / '.git').is_dir() + assert not (directory / '.git' / lib.REPO_MARKER).exists() + + # Without an https origin, the URL must be given (and must still be the origin). + other, _ = user_clone('code/ssh-clone', remote=git_remote_factory('library')) + git(other, 'remote', 'set-url', 'origin', 'git@git.example.com:owner/library.git') + assert lib.inspect_import(test_session, 'code/ssh-clone')['url'] == 'https://git.example.com/owner/library' + git(other, 'remote', 'remove', 'origin') + assert lib.inspect_import(test_session, 'code/ssh-clone')['url'] is None + with pytest.raises(InvalidRepo, match='https:// URL'): + await lib.import_repository(test_session, 'code/ssh-clone', confirm=True) + repo = await lib.import_repository(test_session, 'code/ssh-clone', url='https://git.example.com/owner/library', + confirm=True) + assert repo.url == 'https://git.example.com/owner/library'