repos: choose a Repo's directory; import a clone where it is

A user's repos (like any Collection) may live outside the special
directories, so:

* New Repo has an optional Directory (relative to the media directory,
  empty or new).  Empty still means the Repos directory.  A repo in
  another directory is not ignored: its files are indexed unless the user
  ignores the directory.
* Import keeps the clone where it is (no move); the inspection says
  whether its directory is ignored.  The moved-destination checks are
  gone with the move.

Both share the directory rules: in the media directory, not a special
directory (or one holding one), nothing in config/ or tags/, and not
overlapping another Collection's directory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Roland 2026-10-06 19:24:49 -06:00
parent 89dad0570a
commit 1f71381dad
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
8 changed files with 164 additions and 188 deletions

View file

@ -2529,7 +2529,7 @@ export async function getRepo(repoId) {
await reposError(response, 'Failed to fetch repo.');
}
// `repo`: {url, name?, tag_name?, frequency?, mode?, branch?, description?}
// `repo`: {url, directory?, name?, tag_name?, frequency?, mode?, branch?, description?}
export async function createRepo(repo) {
const response = await apiPost(REPOS_API, repo);
if (response.ok) {
@ -2597,8 +2597,7 @@ export function repoArchiveURL(repoId) {
return `${REPOS_API}/${repoId}/archive.zip`;
}
// What importing the git clone in `directory` (relative to the media directory) would do, with the URL the
// import will use. Changes nothing.
// What importing the git clone in `directory` (relative to the media directory) would do. Changes nothing.
export async function inspectRepoImport(directory, name, tagName, url) {
const body = {directory, name: name || null, tag_name: tagName || null, url: url || null};
const response = await apiPost(`${REPOS_API}/import/inspect`, body);
@ -2608,8 +2607,7 @@ export async function inspectRepoImport(directory, name, tagName, url) {
return {error: await getErrorMessage(response, 'Cannot import this directory.')};
}
// Import an existing git clone as a Repo. `repo`: {directory, destination, confirm, url?, name?, tag_name?, ...}
// `destination` is the inspected one; the server refuses to move the clone anywhere else.
// Import an existing git clone as a Repo; it stays where it is. `repo`: {directory, confirm, url?, name?, ...}
export async function importRepo(repo) {
const response = await apiPost(`${REPOS_API}/import`, repo);
if (response.ok) {

View file

@ -545,6 +545,7 @@ export function RepoNewPage() {
const [branch, setBranch] = useState('');
const [submodules, setSubmodules] = useState(false);
const [description, setDescription] = useState('');
const [directory, setDirectory] = useState('');
const [submitting, setSubmitting] = useState(false);
const urlIsValid = !!safeRepoHref(url.trim());
@ -563,6 +564,7 @@ export function RepoNewPage() {
branch: branch.trim() || null,
submodules,
description: description.trim() || null,
directory: directory.trim() || null,
});
toast({type: 'success', title: 'Repo added', description: repo.name, time: 3000});
navigate(`/repos/${repo.id}`);
@ -617,6 +619,15 @@ export function RepoNewPage() {
<RepoSettingsFields frequency={frequency} setFrequency={setFrequency} mode={mode}
setMode={setMode} branch={branch} setBranch={setBranch}
submodules={submodules} setSubmodules={setSubmodules}/>
<Grid.Col span={12}>
<label style={{display: 'block', marginBottom: 4}}>Directory</label>
<DirectorySearch value={directory} onSelect={(value) => setDirectory(value || '')}/>
<small style={{color: 'var(--muted)'}}>
Optional. Empty saves it in the Repos Directory, whose files are never indexed. The
files of a repo in another directory are indexed (searchable), unless you ignore that
directory in Files. The directory must be empty.
</small>
</Grid.Col>
<Grid.Col span={12}>
<Textarea
label='Description'
@ -688,7 +699,7 @@ export function RepoSettingsFields({
</>;
}
/** What importing a clone would do: its origin, latest commit, and where it will be moved. */
/** What importing a clone would do: its origin, latest commit, and whether its files are indexed. */
export function RepoImportSummary({inspection}) {
const muted = {color: 'var(--muted)'};
return <Panel>
@ -721,15 +732,12 @@ export function RepoImportSummary({inspection}) {
{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>}
<p>
It stays in <code>{inspection.directory}</code>.
{inspection.ignored
? ' Its files are not indexed.'
: ' Its files are indexed (searchable); to keep them out of search, ignore this directory in Files.'}
</p>
</Panel>;
}
@ -750,8 +758,7 @@ export function RepoImportPage() {
const [confirm, setConfirm] = useState(false);
const [submitting, setSubmitting] = useState(false);
// Inspect the directory again whenever it, the URL, the name, or the Tag change (they decide where it will be
// moved).
// Inspect the directory again whenever it, the URL, or the name change.
useEffect(() => {
if (!directory) {
setInspection(null);
@ -774,7 +781,7 @@ export function RepoImportPage() {
clearTimeout(timer);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [directory, name, tagName, url]);
}, [directory, name, url]);
const handleDirectory = (value) => {
setDirectory(value || '');
@ -783,8 +790,7 @@ export function RepoImportPage() {
};
const urlIsValid = !!safeRepoHref(url.trim());
const canImport = inspection && !inspection.destination_exists && urlIsValid && confirm && !submitting
&& !wrolMode;
const canImport = inspection && urlIsValid && confirm && !submitting && !wrolMode;
const handleSubmit = async (e) => {
e.preventDefault();
@ -793,8 +799,6 @@ export function RepoImportPage() {
try {
const repo = await importRepo({
directory,
// Where the inspection said it would go; the server refuses anywhere else.
destination: inspection.destination,
confirm,
url: url.trim(),
name: name.trim() || null,
@ -818,8 +822,8 @@ export function RepoImportPage() {
<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.
Import a git clone that is already in your media directory. It stays where it is, and WROLPi
keeps it up to date, as a mirror of its origin.
</p>
<form onSubmit={handleSubmit}>
<Grid>

View file

@ -242,12 +242,13 @@ describe('RepoNewPage', () => {
fireEvent.change(screen.getByLabelText(/URL/), {target: {value: 'https://github.com/kiwix/kiwix-tools'}});
expect(screen.getByPlaceholderText('kiwix-tools')).toBeInTheDocument();
fireEvent.change(screen.getByLabelText('Branch'), {target: {value: ' dev '}});
fireEvent.click(screen.getByText('Pick directory'));
fireEvent.click(add);
await flush();
expect(createRepo).toHaveBeenCalledWith({
url: 'https://github.com/kiwix/kiwix-tools', name: null, tag_name: null, frequency: 604800,
mode: 'full', branch: 'dev', submodules: false, description: null,
mode: 'full', branch: 'dev', submodules: false, description: null, directory: 'code/kiwix-tools',
});
expect(screen.getByText('repo page')).toBeInTheDocument();
});
@ -299,7 +300,7 @@ describe('RepoImportPage', () => {
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,
shallow: false, ignored: false,
...overrides,
});
@ -322,7 +323,7 @@ describe('RepoImportPage', () => {
await waitFor(() => expect(inspectRepoImport).toHaveBeenCalledWith('code/kiwix-tools', '', null,
'https://github.com/kiwix/kiwix-tools'));
expect(screen.getByText('git@github.com:kiwix/kiwix-tools.git')).toBeInTheDocument();
expect(screen.getByText('repos/kiwix-tools')).toBeInTheDocument();
expect(screen.getByText(/Its files are indexed/)).toBeInTheDocument();
// The URL comes from the origin.
expect(screen.getByLabelText(/^URL/)).toHaveValue('https://github.com/kiwix/kiwix-tools');
@ -334,7 +335,7 @@ describe('RepoImportPage', () => {
await flush();
expect(importRepo).toHaveBeenCalledWith({
directory: 'code/kiwix-tools', destination: 'repos/kiwix-tools', confirm: true, url: 'https://github.com/kiwix/kiwix-tools', name: null,
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();
@ -359,12 +360,10 @@ describe('RepoImportPage', () => {
expect(screen.queryByText('Import')).not.toBeInTheDocument();
});
it('refuses a destination which already exists', async () => {
inspectRepoImport.mockResolvedValue({inspection: inspection({destination_exists: true})});
it('says when the files are not indexed', async () => {
inspectRepoImport.mockResolvedValue({inspection: inspection({ignored: 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();
expect(await screen.findByText(/Its files are not indexed/)).toBeInTheDocument();
});
});

View file

@ -1173,8 +1173,7 @@ export function ThemeSamplePage() {
<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,
shallow: true, directory: 'code/kiwix-tools', ignored: false,
}}/>
</div>
<div style={{marginTop: 12}}>

View file

@ -41,6 +41,7 @@ async def post_repo(request: Request, body: schema.RepoCreateRequest):
name=body.name or None,
description=body.description or None,
submodules=body.submodules,
directory=(body.directory or '').strip() or None,
)
repo = Repository.find_by_id(session, repo.id, options=Repository.json_options())
return json_response(dict(repo=repo.__json__()), status=HTTPStatus.CREATED)
@ -60,8 +61,8 @@ async def post_inspect_import(request: Request, body: schema.RepoImportInspectRe
@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).',
summary='Import an existing git clone as a Repo. It stays where it is, and becomes a mirror of its origin '
'(local changes are discarded by its updates).',
body=schema.RepoImportRequest,
validate=True,
)
@ -80,7 +81,6 @@ async def post_import(request: Request, body: schema.RepoImportRequest):
submodules=body.submodules,
name=body.name or None,
description=body.description or None,
expected_destination=body.destination,
)
repo = Repository.find_by_id(session, repo.id, options=Repository.json_options())
return json_response(dict(repo=repo.__json__()), status=HTTPStatus.CREATED)

View file

@ -693,8 +693,13 @@ 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,
clone_token: str = None) -> Repository:
"""Create a Repo (Collection + Repository + recurring Download). The download clones it."""
"""Create a Repo (Collection + Repository + recurring Download). The download clones it.
`directory` (relative to the media directory) is where the user chose to clone it; otherwise it is in the
Repos directory."""
_validate_frequency(frequency)
if isinstance(directory, str):
directory = resolve_new_repo_directory(session, directory)
repo = _create_repository_records(session, url, tag_name, mode, branch, name, description, directory, submodules,
clone_token)
_create_repository_download(session, repo, frequency)
@ -777,8 +782,9 @@ def remote_https_url(url: str) -> Optional[str]:
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."""
def _resolve_repo_directory(session: Session, directory: str) -> pathlib.Path:
"""A directory (relative to the media directory) a Repo may use: in the media directory, not WROLPi's own
directories, and not overlapping another Collection's. It does not have to be ignored."""
media_directory = get_media_directory().resolve()
relative = pathlib.Path((directory or '').strip())
if not str(relative) or relative.is_absolute() or '..' in relative.parts:
@ -788,20 +794,47 @@ def resolve_import_directory(session: Session, directory: str) -> pathlib.Path:
path = (media_directory / relative).resolve()
if path == media_directory or media_directory not in path.parents:
raise InvalidRepo('The directory must be in the media directory')
if not path.is_dir():
raise UnknownDirectory(f'No directory {directory!r}')
# 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'):
for special in get_special_directories():
special = special.resolve()
if path == special or path in special.parents:
raise InvalidRepo(f'{get_relative_to_media_directory(special)} cannot be imported')
if special != media_directory and (path == special or path in special.parents):
raise InvalidRepo(f'{get_relative_to_media_directory(special)} cannot be used')
for managed in (media_directory / 'config', media_directory / 'tags'):
# WROLPi manages everything in these.
if path == managed or managed in path.parents or path in managed.parents:
raise InvalidRepo(f'{get_relative_to_media_directory(managed)} cannot be used')
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')
return path
def resolve_new_repo_directory(session: Session, directory: str) -> pathlib.Path:
"""The directory a new Repo chose to be cloned into. It must be empty (or not exist yet)."""
path = _resolve_repo_directory(session, directory)
if path.exists():
if not path.is_dir() or path.is_symlink():
raise InvalidRepo(f'{directory} is not a directory')
if next(path.iterdir(), None) is not None:
raise RepoConflict(f'{directory} is not empty. To keep a clone which is already there, import it')
return path
def is_ignored_directory(path: pathlib.Path) -> bool:
"""Are the files in `path` ignored (never indexed)?"""
from wrolpi.files.lib import get_normalized_ignored_directories
path = str(path.resolve())
return any(path == i or path.startswith(f'{i}/') for i in get_normalized_ignored_directories())
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."""
path = _resolve_repo_directory(session, directory)
if not path.is_dir():
raise UnknownDirectory(f'No directory {directory!r}')
git_dir = path / '.git'
if git_dir.is_symlink() or not git_dir.is_dir():
@ -895,8 +928,6 @@ def inspect_import(session: Session, directory: str, name: str = None, tag_name:
except InvalidRepo:
parsed = 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
@ -913,21 +944,17 @@ def inspect_import(session: Session, directory: str, name: str = None, tag_name:
**head_commit,
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(),
# The clone stays where it is; unless it is ignored, its files are indexed (searchable).
ignored=is_ignored_directory(path),
)
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, expected_destination: 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.
`destination` is the directory the inspection said the clone would be moved to; the import is refused if it
would be moved anywhere else."""
description: str = None) -> Repository:
"""Import the git clone in `directory` as a Repo. It stays where it is, 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, url)
source = resolve_import_directory(session, directory)
@ -941,22 +968,10 @@ async def import_repository(session: Session, directory: str, url: str = None, c
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,
repo = _create_repository_records(session, parsed.url, tag_name, mode, branch, info['name'], description, source,
submodules)
destination = repo.directory
relative_destination = str(get_relative_to_media_directory(destination))
if relative_destination != info['destination'] or (
expected_destination is not None and relative_destination != expected_destination):
raise InvalidRepo(f'The repo would be moved to {relative_destination}, not '
f'{expected_destination or info["destination"]}. Inspect it again')
moving = destination.resolve() != source
if moving:
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')
# Everything which can refuse the import happens before the clone is moved.
# Everything which can refuse the import happens before the clone is changed.
if error := await asyncio.to_thread(working_tree_git_error, source):
raise InvalidRepo(f'{directory} cannot be imported: {error}')
try:
@ -964,28 +979,13 @@ async def import_repository(session: Session, directory: str, url: str = None, c
except ValueError as e:
raise InvalidRepo(f'{directory} cannot be imported: {e}')
await asyncio.to_thread(_git_output_sync, source, 'config', '--replace-all', 'remote.origin.url', parsed.url)
mark_clone(source, repo.clone_token)
if moving:
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}')
try:
mark_clone(destination, repo.clone_token)
except BaseException:
if moving:
# Leave the clone where it was found.
await asyncio.to_thread(shutil.move, destination, source)
raise
if moving:
# Forget the files that were indexed in the old location.
from wrolpi.files.worker import file_worker
file_worker.queue_refresh([source])
for key, value in _read_head_commit(destination).items():
for key, value in _read_head_commit(source).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)
repo.readme_path = find_readme(source)
repo.readme_text = read_readme_text(source / repo.readme_path) if repo.readme_path else None
repo.size = await asyncio.to_thread(get_repo_size, source)
_create_repository_download(session, repo, frequency)
return repo

View file

@ -5,6 +5,8 @@ from typing import Optional, List
@dataclass
class RepoCreateRequest:
url: str
# Relative to the media directory; empty clones it into the Repos directory.
directory: Optional[str] = None
tag_name: Optional[str] = None
frequency: Optional[int] = None
mode: Optional[str] = None
@ -42,8 +44,6 @@ class RepoImportInspectRequest:
@dataclass
class RepoImportRequest:
directory: str
# The destination the inspection reported; the import is refused if the clone would be moved anywhere else.
destination: str
confirm: bool = False
url: Optional[str] = None
tag_name: Optional[str] = None

View file

@ -62,8 +62,7 @@ async def test_inspect_import(test_session, async_client, test_wrolpi_config, us
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')))
content=json.dumps(dict(directory='code/kiwix-tools')))
assert response.status_code == HTTPStatus.OK, response.json
info = response.json['inspection']
assert info['directory'] == 'code/kiwix-tools'
@ -76,13 +75,16 @@ async def test_inspect_import(test_session, async_client, test_wrolpi_config, us
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
# The clone stays where it is, where its files are indexed.
assert info['ignored'] is False
assert (directory / '.git/config').read_text() == config_before
assert not (directory / '.git' / lib.REPO_MARKER).exists()
# A clone in the Repos directory is ignored.
user_clone('repos/other', remote=remote)
assert lib.inspect_import(test_session, 'repos/other')['ignored'] is True
@pytest.mark.asyncio
async def test_inspect_import_refuses(test_session, test_directory, async_client, test_wrolpi_config, user_clone):
@ -119,38 +121,36 @@ async def test_inspect_import_refuses(test_session, test_directory, async_client
@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."""
"""An imported clone stays where it is, is owned by WROLPi, and is 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()
indexed = test_session.query(FileGroup).filter(FileGroup.primary_path.contains('code/kiwix-tools')).count()
assert indexed
body = dict(directory='code/kiwix-tools', tag_name='Software', confirm=True, frequency=86400,
destination='repos/Software/kiwix-tools')
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['directory'] == 'code/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 (directory / 'README.md').is_file()
assert (directory / '.git' / lib.REPO_MARKER).is_file()
config = (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.
# It was not moved (or ignored); its files are still indexed.
assert not (test_directory / 'repos').exists()
await refresh_files()
assert test_session.query(FileGroup).filter(FileGroup.primary_path.contains('kiwix-tools')).count() == 0
assert test_session.query(FileGroup).filter(FileGroup.primary_path.contains('code/kiwix-tools')).count()
# From now on it is a mirror: an update fetches the origin, and discards local files.
await repos_download_manager.wait_for_all_downloads()
@ -163,17 +163,8 @@ async def test_import(test_session, test_directory, async_client, test_wrolpi_co
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()
assert (directory / 'new.txt').is_file()
assert not (directory / 'local-note.txt').exists()
@pytest.mark.asyncio
@ -188,13 +179,8 @@ async def test_import_refuses(test_session, test_directory, async_client, test_w
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).
@ -208,78 +194,25 @@ async def test_import_refuses(test_session, test_directory, async_client, test_w
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'
assert repo.directory == other
@pytest.mark.asyncio
async def test_import_checks_before_moving(test_session, test_directory, async_client, test_wrolpi_config,
user_clone):
"""Everything which can refuse an import is checked before the clone is moved."""
async def test_refused_import_changes_nothing(test_session, test_directory, async_client, test_wrolpi_config,
user_clone):
"""Everything which can refuse an import is checked before the clone is changed."""
directory, _ = user_clone()
(directory / 'other').mkdir()
(directory / 'other/.git').write_text(f'gitdir: {test_directory}\n')
config_before = (directory / '.git/config').read_text()
with pytest.raises(InvalidRepo, match='outside'):
await lib.import_repository(test_session, 'code/kiwix-tools', confirm=True)
test_session.rollback()
assert (directory / '.git').is_dir()
assert not (test_directory / 'repos/kiwix-tools').exists()
assert (directory / '.git/config').read_text() == config_before
assert not (directory / '.git' / lib.REPO_MARKER).exists()
assert test_session.query(Repository).count() == 0
@pytest.mark.asyncio
async def test_import_moves_back_on_failure(test_session, test_directory, async_client, test_wrolpi_config,
user_clone):
"""If the import fails after the move, the clone is moved back."""
from mock import mock
directory, _ = user_clone()
with mock.patch('modules.repos.lib.mark_clone', side_effect=OSError('disk full')):
with pytest.raises(OSError):
await lib.import_repository(test_session, 'code/kiwix-tools', confirm=True)
test_session.rollback()
assert (directory / '.git').is_dir()
assert not (test_directory / 'repos/kiwix-tools').exists()
assert test_session.query(Repository).count() == 0
@pytest.mark.asyncio
async def test_import_destination_matches_the_inspection(test_session, test_directory, async_client,
test_wrolpi_config, user_clone, git_remote_factory):
"""With a template using the URL's host and owner, the inspection is made with the URL the import will use, and
the import refuses a destination other than the one inspected."""
from wrolpi.common import get_wrolpi_config
get_wrolpi_config().repos_destination = 'repos/%(repo_host)s/%(repo_owner)s/%(repo_name)s'
directory, _ = user_clone('code/library', remote=git_remote_factory('library'))
git(directory, 'remote', 'remove', 'origin') # The URL must be given.
body = dict(directory='code/library')
request, response = await async_client.post('/api/repos/import/inspect', content=json.dumps(body))
assert response.json['inspection']['destination'] == 'repos/library'
url = 'https://git.example.com/owner/library'
body = dict(directory='code/library', url=url)
request, response = await async_client.post('/api/repos/import/inspect', content=json.dumps(body))
inspected = response.json['inspection']['destination']
assert inspected == 'repos/git.example.com/owner/library'
# An import of what was inspected without the URL is refused.
body = dict(directory='code/library', url=url, confirm=True, destination='repos/library')
request, response = await async_client.post('/api/repos/import', content=json.dumps(body))
assert response.status_code == HTTPStatus.BAD_REQUEST
assert 'Inspect it again' in response.json['error']
assert directory.is_dir()
body = dict(directory='code/library', url=url, confirm=True, destination=inspected)
request, response = await async_client.post('/api/repos/import', content=json.dumps(body))
assert response.status_code == HTTPStatus.CREATED, response.json
assert response.json['repo']['directory'] == inspected
assert (test_directory / inspected / '.git').is_dir()
# The API always checks the destination.
body = dict(directory='code/other', url=url, confirm=True)
request, response = await async_client.post('/api/repos/import', content=json.dumps(body))
assert response.status_code == HTTPStatus.BAD_REQUEST
@pytest.mark.asyncio
async def test_inspect_never_reads_the_clones_config(test_session, test_directory, async_client, test_wrolpi_config,
user_clone):
@ -308,3 +241,46 @@ def test_working_tree_git_file_is_read_like_git(tmp_path):
assert lib.working_tree_git_error(repo)
(repo / 'vendor/library/.git').write_text('gitdir: ../../.git/modules/library\r\n')
assert lib.working_tree_git_error(repo) is None
@pytest.mark.asyncio
async def test_create_repository_in_a_directory(test_session, test_directory, async_client, test_wrolpi_config,
git_remote_factory, repos_download_manager, refresh_files):
"""A Repo can be cloned into a directory the user chooses. It is not ignored: its files are indexed."""
remote = git_remote_factory(files={'README.md': '# Example', 'guide.md': 'A guide'})
body = dict(url=remote.url, directory='projects/example', tag_name='Software')
request, response = await async_client.post('/api/repos', content=json.dumps(body))
assert response.status_code == HTTPStatus.CREATED, response.json
assert response.json['repo']['directory'] == 'projects/example'
await repos_download_manager.wait_for_all_downloads()
directory = test_directory / 'projects/example'
assert (directory / 'guide.md').is_file()
await refresh_files()
assert test_session.query(FileGroup).filter(FileGroup.primary_path.contains('projects/example')).count()
@pytest.mark.parametrize('directory,error', [
('/etc/example', 'relative'),
('../example', 'relative'),
('.', 'media directory'),
('videos', 'cannot be used'),
('config/example', 'cannot be used'),
('tags', 'cannot be used'),
('not-empty', 'not empty'),
('existing-repo/inside', 'Collection'),
])
@pytest.mark.asyncio
async def test_create_repository_directory_refused(test_session, test_directory, async_client, test_wrolpi_config,
directory, error):
(test_directory / 'videos').mkdir()
(test_directory / 'not-empty').mkdir()
(test_directory / 'not-empty/file.txt').write_text('mine')
lib.create_repository(test_session, 'https://github.com/a/existing', directory='existing-repo')
body = dict(url='https://github.com/a/b', directory=directory)
request, response = await async_client.post('/api/repos', content=json.dumps(body))
assert response.status_code in (HTTPStatus.BAD_REQUEST, HTTPStatus.CONFLICT), response.json
assert error in response.json['error'], response.json
assert (test_directory / 'not-empty/file.txt').read_text() == 'mine'