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 <noreply@anthropic.com>
This commit is contained in:
Roland 2026-10-06 18:09:52 -06:00
parent 68880463eb
commit a94261276c
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
9 changed files with 791 additions and 20 deletions

View file

@ -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.');
}

View file

@ -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 `<BackButton`.
expect(found).toBe(12);
// Thirteen renders. Common.js declares it, and a declaration is not a `<BackButton`.
expect(found).toBe(13);
expect(offenders).toEqual([]);
});

View file

@ -24,6 +24,7 @@ import {
import {
APIButton,
BackButton,
DirectorySearch,
encodeMediaPath,
ErrorMessage,
humanFileSize,
@ -45,6 +46,8 @@ import {
getRepo,
getRepoLog,
getRepoTree,
importRepo,
inspectRepoImport,
repoArchiveURL,
tagCollection,
updateRepo,
@ -200,7 +203,10 @@ export function ReposPage() {
onSubmit={null}
inputRef={searchInputRef}
/>
<Button role='primary' component={Link} to='/repos/new'>New Repo</Button>
<Group gap='xs'>
<Button component={Link} to='/repos/import'>Import</Button>
<Button role='primary' component={Link} to='/repos/new'>New Repo</Button>
</Group>
</Group>;
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 <Panel>
<Grid>
<Grid.Col span={{base: 12, sm: 6}}>
<div style={muted}>Origin</div>
<code style={{overflowWrap: 'anywhere'}}>{inspection.origin || 'None'}</code>
</Grid.Col>
<Grid.Col span={{base: 12, sm: 6}}>
<div style={muted}>Branch</div>
<span style={{display: 'inline-flex', alignItems: 'center', gap: '0.3em'}}>
<IconGitBranch size={16}/>{inspection.branch || 'Detached'}
</span>
</Grid.Col>
{inspection.head_sha && <Grid.Col span={12}>
<div style={muted}>Latest commit</div>
<span style={{display: 'inline-flex', alignItems: 'center', gap: '0.5em', flexWrap: 'wrap'}}>
<IconGitCommit size={16}/>
<code>{inspection.head_sha.slice(0, 7)}</code>
<span style={{overflowWrap: 'anywhere'}}>{inspection.head_message}</span>
{inspection.head_date && <span style={muted}>{isoDatetimeToAgoPopup(inspection.head_date)}</span>}
</span>
</Grid.Col>}
</Grid>
{inspection.local_commits > 0 && <Message kind='warning' title={
inspection.local_commits === 1 ? '1 commit is not on the remote' :
`${inspection.local_commits} commits are not on the remote`}>
<p>They will be discarded by the first update. Push them first if you want to keep them.</p>
</Message>}
{inspection.shallow && <Message kind='info' title='This is a shallow clone'>
<p>In Full history mode, the first update downloads the rest of its history.</p>
</Message>}
{inspection.destination_exists
? <Message kind='error' title={`${inspection.destination} already exists`}>
<p>Choose another name or tag.</p>
</Message>
: <p>
{inspection.will_move
? <>It will be moved to <code>{inspection.destination}</code>.</>
: <>It will stay in <code>{inspection.destination}</code>.</>}
</p>}
</Panel>;
}
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 <>
<div className='wrolpi-button-row'><BackButton/></div>
<Panel>
<Header as='h1'>Import Repo</Header>
<p>
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.
</p>
<form onSubmit={handleSubmit}>
<Grid>
<Grid.Col span={12}>
<label style={{display: 'block', marginBottom: 4}}>Directory</label>
<DirectorySearch value={directory} onSelect={handleDirectory}/>
</Grid.Col>
{inspectError && <Grid.Col span={12}>
<Message kind='error' title='Cannot import this directory'><p>{inspectError}</p></Message>
</Grid.Col>}
{inspection && <>
<Grid.Col span={12}><RepoImportSummary inspection={inspection}/></Grid.Col>
<Grid.Col span={12}>
<TextInput
required
label='URL'
description={inspection.url
? 'From the clone\'s origin'
: 'The clone has no https:// origin; enter the URL it was cloned from'}
placeholder='https://github.com/owner/repo'
value={url}
error={url && !urlIsValid ? 'Must be an https:// URL' : null}
onChange={(e) => setUrl(e.currentTarget.value)}
/>
</Grid.Col>
<Grid.Col span={{base: 12, sm: 6}}>
<TextInput
label='Name'
placeholder={inspection.name}
value={name}
onChange={(e) => setName(e.currentTarget.value)}
/>
</Grid.Col>
<Grid.Col span={{base: 12, sm: 6}}>
<label style={{display: 'block', marginBottom: '0.3em'}}>Tag</label>
<TagsSelector
limit={1}
selectedTagNames={tagName ? [tagName] : []}
onAdd={setTagName}
onRemove={() => setTagName(null)}
/>
</Grid.Col>
<RepoSettingsFields frequency={frequency} setFrequency={setFrequency} mode={mode}
setMode={setMode} branch={branch} setBranch={setBranch}
submodules={submodules} setSubmodules={setSubmodules}/>
{inspection.branch && <Grid.Col span={12}>
<small style={{color: 'var(--muted)'}}>
The clone is on <code>{inspection.branch}</code>. Enter it as the Branch to keep
following it; otherwise the repo follows the remote's default branch.
</small>
</Grid.Col>}
<Grid.Col span={12}>
<Checkbox
label='I understand that WROLPi will keep this clone identical to its origin: local
changes, untracked files, and commits which are not on the remote will be
discarded.'
checked={confirm}
onChange={(e) => setConfirm(e.currentTarget.checked)}
/>
</Grid.Col>
<Grid.Col span={12}>
<Button role='save' type='submit' disabled={!canImport}>Import</Button>
</Grid.Col>
</>}
</Grid>
</form>
</Panel>
</>;
}
export function RepoEditPage() {
const {repoId} = useParams();
const {repo, refetch} = useRepo(repoId);
@ -830,6 +1034,7 @@ export function ReposRoute() {
<Routes>
<Route path='/' element={<ReposPage/>}/>
<Route path='new' element={<RepoNewPage/>}/>
<Route path='import' element={<RepoImportPage/>}/>
<Route path=':repoId' element={<RepoViewPage/>}/>
<Route path=':repoId/edit' element={<RepoEditPage/>}/>
</Routes>

View file

@ -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}) => <button type='button' onClick={() => onSelect('code/kiwix-tools')}>
Pick directory
</button>,
}));
// 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(<Routes>
<Route path='/repos/import' element={<RepoImportPage/>}/>
<Route path='/repos/:repoId' element={<div>repo page</div>}/>
</Routes>, {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();
});
});

View file

@ -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() {
<div style={{marginTop: 12}}>
<RepoHistoryTable commits={sampleRepoCommits}/>
</div>
<div style={{marginTop: 12}}>
<RepoImportSummary inspection={{
origin: 'git@github.com:kiwix/kiwix-tools.git', branch: 'main', head_sha: '3f9c2a1e7b',
head_message: 'Local work', head_date: '2026-09-30T14:02:00Z', local_commits: 2,
shallow: true, destination: 'repos/Software/kiwix-tools', will_move: true,
destination_exists: false,
}}/>
</div>
<div style={{marginTop: 12}}>
<RepoSummary repo={sampleFailedRepo}/>
</div>

View file

@ -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',

View file

@ -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<host>[^:/]+):(?P<path>[^/].*)$', 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

View file

@ -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

View file

@ -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'