diff --git a/CHANGES.rst b/CHANGES.rst
index a676842..0d4f67a 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -2,6 +2,10 @@ Unreleased
==========
* Python 3.13 or newer, following `SPEC 0 `__
(tested on 3.13 to 3.15).
+* New internals for ``tfmgr generate`` and ``tfmgr migrate``: ``GitTree`` reads a template
+ from a git commit without checking it out, ``collect_archive`` gathers what the
+ Archive's files and checks need from its templates, and ``renames_problems`` checks a
+ root renames table from its text. The checks report the same issues as before.
26.0.0rc4 (December 3, 2026)
============================
diff --git a/tfmanager/generate.py b/tfmanager/generate.py
index d0baf20..7706cea 100644
--- a/tfmanager/generate.py
+++ b/tfmanager/generate.py
@@ -12,7 +12,13 @@
from __future__ import annotations
+import json
+from collections.abc import Iterable
+from dataclasses import dataclass, field
+
+from .naming import parse
from .tables import NA, Table, dump_json, json_cell, write_tsv
+from .tree import Tree, visible
#: atlases.tsv column -> atlas-_description.json field (BIDS 1.11)
ATLAS_FIELDS = {
@@ -171,3 +177,42 @@ def templates_table(
}
)
return write_tsv(TEMPLATE_COLUMNS, rows)
+
+
+@dataclass
+class ArchiveIndex:
+ """What the Archive-level files and checks need from the templates."""
+
+ descriptions: dict[str, dict] = field(default_factory=dict)
+ """template_description.json of each template, by label."""
+ atlases: dict[str, list[str]] = field(default_factory=dict)
+ """Atlas labels in each template's file names, in order of first appearance."""
+ targets: list[tuple[str, str]] = field(default_factory=list)
+ """``(tpl-/path, value)`` of every ``from`` and ``to`` entity of a transform."""
+
+
+def collect_archive(trees: Iterable[Tree]) -> ArchiveIndex:
+ """Read the templates of the Archive (templates.tsv, TF801 and TF803).
+
+ A template whose template_description.json is missing or not JSON is left out.
+ """
+ index = ArchiveIndex()
+ for tree in trees:
+ data = tree.read_bytes('template_description.json')
+ if data is None:
+ continue
+ try:
+ index.descriptions[tree.label] = json.loads(data)
+ except ValueError:
+ continue
+ for path in visible(tree.files()):
+ f = parse(path)
+ if 'atlas' in f.entities:
+ found = index.atlases.setdefault(tree.label, [])
+ if f.entities['atlas'] not in found:
+ found.append(f.entities['atlas'])
+ if f.suffix == 'xfm':
+ for key in ('from', 'to'):
+ if key in f.entities:
+ index.targets.append((f'{tree.name}/{path}', f.entities[key]))
+ return index
diff --git a/tfmanager/io.py b/tfmanager/io.py
index c9889ea..6f68047 100644
--- a/tfmanager/io.py
+++ b/tfmanager/io.py
@@ -26,3 +26,28 @@ def run_command(
output = (proc.stderr or proc.stdout or '').strip()
raise CommandError(f'`{" ".join(cmd[:2])}` failed: {output}')
return proc
+
+
+def run_git(
+ repo: str | os.PathLike,
+ *args: str,
+ input: bytes | None = None, # noqa: A002 (subprocess's name)
+ env: Mapping[str, str] | None = None,
+) -> bytes:
+ """Run ``git -C repo args`` (no shell) and return its standard output as bytes.
+
+ Output stays binary, so that file names and file contents come back unchanged (use
+ ``-z`` with listing commands). Raise :class:`CommandError` if git fails.
+ """
+ full_env = {**os.environ, **env} if env else None
+ proc = subprocess.run( # noqa: S603
+ ['git', '-C', os.fspath(repo), *args],
+ input=input,
+ capture_output=True,
+ env=full_env,
+ check=False,
+ )
+ if proc.returncode != 0:
+ output = proc.stderr.decode(errors='replace').strip()
+ raise CommandError(f'`git {" ".join(args[:1])}` failed: {output}')
+ return proc.stdout
diff --git a/tfmanager/tests/conftest.py b/tfmanager/tests/conftest.py
index 155fdc0..d379765 100644
--- a/tfmanager/tests/conftest.py
+++ b/tfmanager/tests/conftest.py
@@ -3,9 +3,11 @@
from __future__ import annotations
import json
+import os
import pytest
+from tfmanager.io import run_git
from tfmanager.tables import dump_json
from tfmanager.tree import MappingTree
@@ -93,3 +95,18 @@ def tree() -> MappingTree:
def with_description(**changes) -> MappingTree:
return make_tree(**{'template_description.json': json.dumps(description(**changes))})
+
+
+@pytest.fixture
+def git(monkeypatch):
+ """Run git in a repository, isolated from the user's and the system's configuration."""
+ monkeypatch.setenv('GIT_CONFIG_GLOBAL', os.devnull)
+ monkeypatch.setenv('GIT_CONFIG_NOSYSTEM', '1')
+ for role in ('AUTHOR', 'COMMITTER'):
+ monkeypatch.setenv(f'GIT_{role}_NAME', 'TemplateFlow tests')
+ monkeypatch.setenv(f'GIT_{role}_EMAIL', 'tests@templateflow.invalid')
+
+ def run(repo, *args: str) -> str:
+ return run_git(repo, *args).decode()
+
+ return run
diff --git a/tfmanager/tests/test_archive.py b/tfmanager/tests/test_archive.py
index c7a502a..98ce91a 100644
--- a/tfmanager/tests/test_archive.py
+++ b/tfmanager/tests/test_archive.py
@@ -142,3 +142,43 @@ def test_renames_header(tmp_path):
root = _archive(tmp_path)
(root / 'renames.tsv').write_text('old_path\tnew_path\tdate\n')
assert any('header' in i.message for i in check_archive(root) if i.code == 'TF804')
+
+
+def test_collect_archive():
+ from tfmanager.generate import collect_archive
+ from tfmanager.tree import MappingTree
+
+ index = collect_archive(
+ [
+ MappingTree(
+ 'tpl-A',
+ {
+ 'template_description.json': '{"Name": "A"}',
+ 'tpl-A_res-1_atlas-Z_dseg.nii.gz': None,
+ 'tpl-A_res-1_atlas-B_dseg.nii.gz': None,
+ 'tpl-A_atlas-Z_dseg.tsv': 'index\tname\n',
+ 'tpl-A_from-B+1_mode-image_xfm.h5': None,
+ '.hidden/tpl-A_atlas-H_dseg.tsv': '',
+ },
+ ),
+ MappingTree(
+ 'tpl-B', {'template_description.json': 'not JSON', 'tpl-B_atlas-Q_dseg.tsv': ''}
+ ),
+ MappingTree('tpl-C', {'tpl-C_atlas-Q_dseg.tsv': ''}),
+ ]
+ )
+ assert index.descriptions == {'A': {'Name': 'A'}}
+ assert index.atlases == {'A': ['Z', 'B']}
+ assert index.targets == [('tpl-A/tpl-A_from-B+1_mode-image_xfm.h5', 'B+1')]
+
+
+def test_renames_problems():
+ from tfmanager.validate.archive import renames_problems
+
+ text = 'old_path\tnew_path\ntpl-A/x\ttpl-A/y\n'
+ assert renames_problems(text, lambda path: path == 'tpl-A/x') == [
+ 'row 2: tpl-A/x still exists.',
+ 'row 2: tpl-A/y does not exist.',
+ ]
+ assert renames_problems(text, lambda path: True, installed=lambda template: False) == []
+ assert renames_problems('', lambda path: True) == ['The header must be old_pathnew_path.']
diff --git a/tfmanager/tests/test_tree.py b/tfmanager/tests/test_tree.py
index 2130d9b..70121aa 100644
--- a/tfmanager/tests/test_tree.py
+++ b/tfmanager/tests/test_tree.py
@@ -5,7 +5,11 @@
import os
import zipfile
-from tfmanager.tree import DirectoryTree, ZipTree
+import pytest
+
+from tfmanager import tree as tree_module
+from tfmanager.io import CommandError, run_git
+from tfmanager.tree import DirectoryTree, GitTree, ZipTree
def test_symlinks_are_not_followed(tmp_path):
@@ -40,3 +44,127 @@ def test_zip_tree(tmp_path):
assert trees[0].is_annexed('tpl-X_res-1_T1w.nii.gz')
assert not trees[0].is_annexed('template_description.json')
assert trees[0].read_text('template_description.json') == '{"Identifier": "X"}'
+
+
+KEY = 'MD5E-s1--9dd4e461268c8034f5c8564e155c67a6.nii.gz'
+
+
+def _repo(tmp_path, git):
+ """A template repository: text, an executable, annexed files (locked and unlocked), a
+ symlink that is not annexed and a submodule."""
+ tpl = tmp_path / 'tpl-X'
+ (tpl / 'scripts').mkdir(parents=True)
+ git(tpl, 'init', '-q')
+ (tpl / '.gitattributes').write_text('* annex.largefiles=nothing\n')
+ (tpl / 'template_description.json').write_text('{"Identifier": "X"}')
+ (tpl / 'scripts' / 'run.sh').write_text('#!/bin/sh\n')
+ (tpl / 'scripts' / 'run.sh').chmod(0o755)
+ os.symlink(f'.git/annex/objects/Xx/Yy/{KEY}/{KEY}', tpl / 'tpl-X_res-1_T1w.nii.gz')
+ (tpl / 'tpl-X_res-2_T1w.nii.gz').write_text(f'/annex/objects/{KEY}\n')
+ os.symlink('template_description.json', tpl / 'tpl-X_res-1_T1w.json')
+ git(tpl, 'add', '-A')
+ git(tpl, 'commit', '-q', '-m', 'first')
+ head = git(tpl, 'rev-parse', 'HEAD').strip()
+ git(tpl, 'update-index', '--add', '--cacheinfo', f'160000,{head},sub')
+ git(tpl, 'commit', '-q', '-m', 'submodule')
+ return tpl
+
+
+def test_git_tree(tmp_path, git):
+ tpl = _repo(tmp_path, git)
+ tree = GitTree(tpl)
+ assert tree.name == 'tpl-X'
+ assert list(tree.files()) == [
+ '.gitattributes',
+ 'scripts/run.sh',
+ 'template_description.json',
+ 'tpl-X_res-1_T1w.nii.gz',
+ 'tpl-X_res-2_T1w.nii.gz',
+ ]
+ assert not tree.exists('tpl-X_res-1_T1w.json')
+ assert not tree.exists('sub')
+ assert tree.is_annexed('tpl-X_res-1_T1w.nii.gz')
+ assert tree.is_annexed('tpl-X_res-2_T1w.nii.gz')
+ assert not tree.is_annexed('template_description.json')
+ assert tree.read_bytes('tpl-X_res-1_T1w.nii.gz') is None
+ assert tree.read_text('template_description.json') == '{"Identifier": "X"}'
+ assert tree.read_bytes('missing') is None
+
+
+def test_git_tree_matches_checkout(tmp_path, git):
+ tpl = _repo(tmp_path, git)
+ checkout, tree = DirectoryTree(tpl), GitTree(tpl)
+ (tpl / 'sub').mkdir()
+ assert list(checkout.files()) == list(tree.files())
+ for path in tree.files():
+ assert checkout.is_annexed(path) == tree.is_annexed(path), path
+ assert checkout.read_bytes(path) == tree.read_bytes(path), path
+
+
+def test_git_tree_reads_commits(tmp_path, git, monkeypatch):
+ tpl = _repo(tmp_path, git)
+ (tpl / 'template_description.json').write_text('{"Identifier": "X", "Name": "X"}')
+ git(tpl, 'commit', '-q', '-am', 'second')
+ (tpl / 'template_description.json').write_text('not committed')
+ assert GitTree(tpl, 'HEAD~1').read_text('template_description.json') == '{"Identifier": "X"}'
+ assert GitTree(tpl, 'HEAD', name='tpl-Y').name == 'tpl-Y'
+ monkeypatch.setattr(tree_module, 'MAX_TEXT_BYTES', 20)
+ assert GitTree(tpl).read_bytes('template_description.json') is None
+
+
+def test_git_tree_memory(tmp_path, git, monkeypatch):
+ """Small files are read ahead up to MAX_CACHE_BYTES; others are read and not kept."""
+ tpl = tmp_path / 'tpl-X'
+ tpl.mkdir()
+ git(tpl, 'init', '-q')
+ sizes = {'a.json': 10, 'b.json': 20, 'c.json': 30, 'big.tsv': 80, 'bigger.tsv': 90}
+ (tpl / 'huge.txt').write_text('h' * 95) # over MAX_TEXT_BYTES (90 below): never read
+ for name, size in sizes.items():
+ (tpl / name).write_text(name[0] * size)
+ (tpl / 'pointer.nii.gz').write_text('/annex/objects/' + 'x' * 5000) # too long
+ git(tpl, 'add', '-A')
+ # A link whose target is too long to be an annex link
+ target = run_git(
+ tpl, 'hash-object', '-w', '--stdin', input=b'.git/annex/objects/' + b'x' * 5000
+ )
+ git(tpl, 'update-index', '--add', '--cacheinfo', f'120000,{target.decode().strip()},long')
+ git(tpl, 'commit', '-q', '-m', 'files')
+
+ calls = []
+
+ def counted(repo, *args, **kwargs):
+ calls.append(args[0])
+ return run_git(repo, *args, **kwargs)
+
+ monkeypatch.setattr(tree_module, 'run_git', counted)
+ monkeypatch.setattr(tree_module, 'MAX_TEXT_BYTES', 90)
+ tree = GitTree(tpl)
+ assert not tree.exists('long')
+ assert not tree.is_annexed('pointer.nii.gz')
+
+ # Everything fits: one read of git for every file
+ calls.clear()
+ assert {name: len(tree.read_bytes(name)) for name in sizes} == sizes
+ assert calls == ['cat-file']
+ assert tree.read_bytes('huge.txt') is None
+ assert sum(map(len, tree._blobs.values())) == sum(sizes.values())
+
+ monkeypatch.setattr(tree_module, 'MAX_CACHE_BYTES', 100)
+ tree = GitTree(tpl)
+ assert tree.read_text('bigger.tsv') == 'b' * 90 # kept, with a.json: 100 bytes
+ assert sum(map(len, tree._blobs.values())) == 100
+ calls.clear()
+ assert tree.read_text('a.json') == 'a' * 10
+ assert calls == []
+ for name, size in sizes.items():
+ assert tree.read_text(name) == name[0] * size
+ assert sum(map(len, tree._blobs.values())) == 100
+
+
+def test_run_git(tmp_path, git):
+ tpl = _repo(tmp_path, git)
+ assert (
+ run_git(tpl, 'cat-file', '-p', 'HEAD:template_description.json') == b'{"Identifier": "X"}'
+ )
+ with pytest.raises(CommandError, match='git rev-parse'):
+ run_git(tmp_path, 'rev-parse', 'HEAD')
diff --git a/tfmanager/tree.py b/tfmanager/tree.py
index 58241d1..72ee10c 100644
--- a/tfmanager/tree.py
+++ b/tfmanager/tree.py
@@ -17,8 +17,14 @@
from collections.abc import Iterable, Iterator, Mapping
from pathlib import Path, PurePosixPath
+from .io import run_git
+
#: Largest text file the validator reads (bytes)
MAX_TEXT_BYTES = 8 * 1024 * 1024
+#: Most bytes of file content a GitTree keeps (it reads small files ahead of use)
+MAX_CACHE_BYTES = 32 * 1024 * 1024
+#: Largest symbolic link target, or git-annex pointer file, read from git (bytes)
+MAX_LINK_BYTES = 4096
class Tree:
@@ -156,6 +162,142 @@ def local_path(self, path: str) -> Path | None:
return None
+class GitTree(Tree):
+ """A template as recorded in a git commit (or any tree-ish), read without a checkout.
+
+ The same rules as :class:`DirectoryTree` apply: a symbolic link counts only if it
+ points into the annex (an annexed file), other symbolic links and submodules are left
+ out, and annexed content is never read. This checks a commit before it is checked out
+ (``tfmgr migrate apply``) or one that never is (a pull request's head).
+
+ Memory is bounded: the smallest files are read ahead, together, up to
+ ``MAX_CACHE_BYTES`` (validation reads most of them), and any other file is read when
+ asked and not kept.
+
+ Parameters
+ ----------
+ repo
+ The template's git repository (``.../tpl-``).
+ treeish
+ A commit, branch or tree of that repository.
+ name
+ The template directory name, if not that of ``repo``.
+
+ """
+
+ def __init__(self, repo: str | os.PathLike, treeish: str = 'HEAD', name: str | None = None):
+ self.repo = Path(repo)
+ self.treeish = treeish
+ self.name = name or self.repo.resolve().name
+ self._files: dict[str, tuple[str, str, int]] | None = None
+ self._links: dict[str, str] = {}
+ self._blobs: dict[str, bytes] = {}
+ self._cached = 0
+
+ def _cat(self, shas: Iterable[str]) -> dict[str, bytes]:
+ """Read blobs with one ``git cat-file --batch``."""
+ wanted = sorted(set(shas))
+ if not wanted:
+ return {}
+ out = run_git(
+ self.repo, 'cat-file', '--batch', input=''.join(f'{s}\n' for s in wanted).encode()
+ )
+ blobs = {}
+ pos = 0
+ while pos < len(out):
+ eol = out.index(b'\n', pos)
+ sha, _, size = out[pos:eol].split()
+ start = eol + 1
+ blobs[sha.decode()] = out[start : start + int(size)]
+ pos = start + int(size) + 1
+ return blobs
+
+ def _scan(self) -> dict[str, tuple[str, str, int]]:
+ """``{path: (mode, blob sha, size)}`` of the files that count."""
+ if self._files is not None:
+ return self._files
+ listing = run_git(self.repo, 'ls-tree', '-r', '-z', '-l', '--full-tree', self.treeish)
+ entries = {}
+ for record in listing.split(b'\0'):
+ if not record:
+ continue
+ meta, _, path = record.partition(b'\t')
+ mode, kind, sha, size = meta.split()
+ if kind == b'blob':
+ entries[path.decode('utf-8', 'surrogateescape')] = (
+ mode.decode(),
+ sha.decode(),
+ int(size),
+ )
+ # Annex links are ~140 bytes: longer link targets are not annexed files
+ links = self._cat(
+ sha
+ for mode, sha, size in entries.values()
+ if mode == '120000' and size <= MAX_LINK_BYTES
+ )
+ self._links = {sha: data.decode(errors='replace') for sha, data in links.items()}
+
+ def counts(entry: tuple[str, str, int]) -> bool:
+ mode, sha, _ = entry
+ return mode != '120000' or _annex_target(self._links.get(sha, ''))
+
+ self._files = {path: entry for path, entry in sorted(entries.items()) if counts(entry)}
+ return self._files
+
+ def files(self) -> Iterator[str]:
+ yield from self._scan()
+
+ def exists(self, path: str) -> bool:
+ return path in self._scan()
+
+ def is_annexed(self, path: str) -> bool:
+ entry = self._scan().get(path)
+ if entry is None:
+ return False
+ if entry[0] == '120000':
+ return True
+ # Unlocked annexed files (pointer files) in adjusted branches
+ return entry[2] <= MAX_LINK_BYTES and (self.read_bytes(path) or b'').startswith(
+ b'/annex/objects/'
+ )
+
+ def read_bytes(self, path: str) -> bytes | None:
+ entry = self._scan().get(path)
+ if entry is None or entry[0] == '120000' or entry[2] > MAX_TEXT_BYTES:
+ return None
+ _, sha, size = entry
+ if sha not in self._blobs:
+ self._read_ahead(sha, size)
+ if sha in self._blobs:
+ return self._blobs[sha]
+ return self._cat([sha])[sha] # Over the budget: read, and not kept
+
+ def _read_ahead(self, sha: str, size: int) -> None:
+ """Keep a blob and, in the same ``git`` call, the smallest blobs not read yet, as
+ long as all fit in what is left of ``MAX_CACHE_BYTES``."""
+ budget = MAX_CACHE_BYTES - self._cached
+ if size > budget:
+ return
+ others = sorted(
+ {
+ (n, other)
+ for mode, other, n in self._scan().values()
+ if mode != '120000'
+ and n <= MAX_TEXT_BYTES
+ and other != sha
+ and other not in self._blobs
+ }
+ )
+ batch, total = [sha], size
+ for n, other in others:
+ if total + n > budget:
+ break
+ batch.append(other)
+ total += n
+ self._blobs.update(self._cat(batch))
+ self._cached += total
+
+
class ZipTree(Tree):
"""A template inside a skeleton zip (empty members are annexed stubs)."""
diff --git a/tfmanager/validate/archive.py b/tfmanager/validate/archive.py
index 39a474a..6e5f8ba 100644
--- a/tfmanager/validate/archive.py
+++ b/tfmanager/validate/archive.py
@@ -3,13 +3,12 @@
from __future__ import annotations
import configparser
-import json
+from collections.abc import Callable
from pathlib import Path
-from ..generate import templates_table
-from ..naming import parse
+from ..generate import collect_archive, templates_table
from ..ruleset import load_ruleset
-from ..tree import DirectoryTree, visible
+from ..tree import DirectoryTree
from .core import Issue
@@ -48,31 +47,11 @@ def check_archive(root: str | Path, legacy: bool = False) -> list[Issue]:
what = 'not registered as a subdataset' if name in templates else 'registered but absent'
issues.append(_issue('TF802', name, f'{name} is {what}.', legacy))
- descriptions = {}
- atlases: dict[str, list[str]] = {}
- targets: list[tuple[str, str]] = []
- for name in sorted(templates):
- tree = DirectoryTree(root / name)
- data = tree.read_bytes('template_description.json')
- if data is None:
- continue
- try:
- descriptions[name[4:]] = json.loads(data)
- except ValueError:
- continue
- for path in visible(tree.files()):
- f = parse(path)
- if 'atlas' in f.entities:
- atlases.setdefault(name[4:], [])
- if f.entities['atlas'] not in atlases[name[4:]]:
- atlases[name[4:]].append(f.entities['atlas'])
- if f.suffix == 'xfm':
- for key in ('from', 'to'):
- if key in f.entities:
- targets.append((f'{name}/{path}', f.entities[key]))
+ index = collect_archive(DirectoryTree(root / name) for name in sorted(templates))
+ descriptions = index.descriptions
labels = {n[4:] for n in templates}
- for path, target in targets:
+ for path, target in index.targets:
label, _, cohort = target.partition('+')
if label not in labels:
issues.append(
@@ -83,7 +62,7 @@ def check_archive(root: str | Path, legacy: bool = False) -> list[Issue]:
_issue('TF803', path, f'{target}: tpl-{label} has no cohort {cohort}.', legacy)
)
- expected = templates_table(descriptions, atlases)
+ expected = templates_table(descriptions, index.atlases)
current = root / 'templates.tsv'
if not current.exists():
issues.append(_issue('TF801', 'templates.tsv', 'Missing.', legacy))
@@ -99,51 +78,71 @@ def check_archive(root: str | Path, legacy: bool = False) -> list[Issue]:
def check_renames(root: Path, legacy: bool = False) -> list[Issue]:
- """TF804: the root renames table, which the template action writes.
+ """TF804: the root renames table, which the template action writes."""
+ table = root / 'renames.tsv'
+ if not table.exists():
+ return []
+
+ def exists(path: str) -> bool:
+ return (root / path).is_symlink() or (root / path).exists()
+
+ def installed(template: str) -> bool:
+ return (root / template).is_dir() and any((root / template).iterdir())
+
+ return [
+ _issue('TF804', 'renames.tsv', message, legacy)
+ for message in renames_problems(table.read_text(), exists, installed)
+ ]
+
+
+def renames_problems(
+ text: str,
+ exists: Callable[[str], bool],
+ installed: Callable[[str], bool] = lambda template: True,
+) -> list[str]:
+ r"""The problems of a root renames table (TF804), given its text.
Two columns, ``old_path`` and ``new_path``, with paths that start with the template
directory. ``new_path`` is the file's current path, ``n/a`` (removed from the
template, still served) or ``purge`` (removed from S3). Old paths point at current
names, never at other old paths.
- """
- table = root / 'renames.tsv'
- if not table.exists():
- return []
- issues = []
- def report(message):
- issues.append(_issue('TF804', 'renames.tsv', message, legacy))
+ ``exists(path)`` says whether an Archive path is a current file. Old paths must not
+ exist and new paths must, in the templates for which ``installed(template)`` is true
+ (an uninstalled subdataset has no files to compare).
- lines = table.read_text().splitlines()
+ >>> renames_problems('old_path\tnew_path\ntpl-A/x\ttpl-A/y\n', lambda path: True)
+ ['row 2: tpl-A/x still exists.']
+ """
+ problems: list[str] = []
+ lines = text.splitlines()
if not lines or lines[0].split('\t') != ['old_path', 'new_path']:
- report('The header must be old_pathnew_path.')
- return issues
+ return ['The header must be old_pathnew_path.']
rows: dict[str, str] = {}
for n, line in enumerate(lines[1:], start=2):
cells = line.split('\t')
if len(cells) != 2 or not all(cells):
- report(f'row {n}: needs two non-empty cells.')
+ problems.append(f'row {n}: needs two non-empty cells.')
continue
old, new = cells
if old in rows:
- report(f'row {n}: {old} is listed twice.')
+ problems.append(f'row {n}: {old} is listed twice.')
continue
rows[old] = new
template = old.split('/')[0]
if not template.startswith('tpl-') or '/' not in old:
- report(f'row {n}: {old} does not start with a template directory.')
+ problems.append(f'row {n}: {old} does not start with a template directory.')
continue
if new not in RENAME_KEYWORDS and new.split('/')[0] != template:
- report(f'row {n}: {new} is not a path in {template}, n/a or purge.')
+ problems.append(f'row {n}: {new} is not a path in {template}, n/a or purge.')
continue
- installed = (root / template).is_dir() and any((root / template).iterdir())
- if not installed:
+ if not installed(template):
continue
- if (root / old).is_symlink() or (root / old).exists():
- report(f'row {n}: {old} still exists.')
- if new not in RENAME_KEYWORDS and not ((root / new).is_symlink() or (root / new).exists()):
- report(f'row {n}: {new} does not exist.')
+ if exists(old):
+ problems.append(f'row {n}: {old} still exists.')
+ if new not in RENAME_KEYWORDS and not exists(new):
+ problems.append(f'row {n}: {new} does not exist.')
for old, new in rows.items():
if new in rows:
- report(f'{old}: points at {new}, which is itself an old path.')
- return issues
+ problems.append(f'{old}: points at {new}, which is itself an old path.')
+ return problems