Coverage for collectra/pipelines/importing.py: 100.00%
34 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-13 04:26 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-13 04:26 +0000
1"""Name the results folders inputs are imported into, and report what was done."""
3from __future__ import annotations
5from collections.abc import Callable
6from itertools import count
7from pathlib import Path
9from pydantic import BaseModel, Field
12def destination(source: Path, ext: str, taken: Callable[[Path], bool]) -> Path:
13 """The first results folder name for ``source`` that is not taken.
15 The candidates sit next to the source: ``<stem>.<ext>``, then
16 ``<stem>-2.<ext>``, ``<stem>-3.<ext>`` and so on.
18 Args:
19 source: The input file.
20 ext: The pipeline's results folder extension, without the dot.
21 taken: Whether a candidate cannot be used.
23 Returns:
24 The first candidate that is not taken.
25 """
26 for number in count(1):
27 suffix = f"-{number}" if number > 1 else ""
28 candidate = source.parent / f"{source.stem}{suffix}.{ext}"
29 if not taken(candidate):
30 return candidate
33class ImportReport(BaseModel):
34 """What opening a set of inputs did.
36 Attributes:
37 pages: Every results folder created or opened, in the order processed.
38 imported: How many of them were created.
39 existing: How many of them were already results folders.
40 skipped: ``"<name>: <reason>"`` for each file the pipeline does not accept.
41 skipped_folders: ``"<name>: <reason>"`` for each ``<x>.<ext>`` folder
42 that could not be adopted.
43 failed: ``"<name>: <reason>"`` for each input that could not be imported.
44 """
46 pages: list[Path] = Field(default_factory=list)
47 imported: int = 0
48 existing: int = 0
49 skipped: list[str] = Field(default_factory=list)
50 skipped_folders: list[str] = Field(default_factory=list)
51 failed: list[str] = Field(default_factory=list)
53 def summary(self, name: str) -> str:
54 """A one-line notice of what was done.
56 Args:
57 name: The pipeline's name.
59 Returns:
60 The notice, or an empty string when only existing pages were opened.
61 """
62 parts = []
63 if self.imported:
64 parts.append(
65 f"Imported {self.imported} page{'s' if self.imported != 1 else ''}"
66 )
67 if self.existing:
68 parts.append(f"opened {self.existing} existing")
69 if self.skipped:
70 count = len(self.skipped)
71 parts.append(
72 f"skipped {count} file{'s' if count != 1 else ''} "
73 f"{name} doesn't accept"
74 )
75 if self.skipped_folders:
76 count = len(self.skipped_folders)
77 parts.append(
78 f"skipped {count} folder{'s' if count != 1 else ''} "
79 "without exactly one image"
80 )
81 if self.failed:
82 parts.append(f"{len(self.failed)} failed")
83 changes = (self.imported, self.skipped, self.skipped_folders, self.failed)
84 return ", ".join(parts) if any(changes) else ""