Coverage for src/somesy/commands/sync.py: 94%
160 statements
« prev ^ index » next coverage.py v7.16.0, created at 2026-11-09 13:08 +0000
« prev ^ index » next coverage.py v7.16.0, created at 2026-11-09 13:08 +0000
1"""Sync selected metadata files with given input file."""
3import json
4import logging
5import xml.etree.ElementTree as ET
6from collections.abc import Mapping
7from pathlib import Path
8from typing import Any, NamedTuple
10from pydantic import ValidationError
11from rich.markup import escape
12from rich.pretty import pretty_repr
14from somesy.cff.writer import CFF
15from somesy.codemeta import CodeMeta
16from somesy.core.core import INPUT_FILES_ORDERED, atomic_write
17from somesy.core.log import VERBOSE
18from somesy.core.models import ProjectMetadata, SomesyConfig, SomesyInput
19from somesy.core.writer import ProjectMetadataWriter
20from somesy.fortran.writer import Fortran
21from somesy.julia.writer import Julia
22from somesy.mkdocs import MkDocs
23from somesy.package_json.writer import PackageJSON
24from somesy.pom_xml.writer import POM
25from somesy.pom_xml.xmlproxy import XMLProxy
26from somesy.pyproject.writer import Pyproject
27from somesy.rust import Rust
29logger = logging.getLogger("somesy")
32class SyncTarget(NamedTuple):
33 """A metadata file type that somesy can sync.
35 The config attributes are `no_sync_<key>` and `<key>_file`.
36 """
38 key: str
39 writer: type[Any] # a ProjectMetadataWriter subclass
40 label: str # name shown in the CLI log
41 create_if_missing: bool = False # create the file if it does not exist
42 codemeta_source: bool = False # enriches codemeta.json under the same key
43 log_gap: bool = False # CLI log: blank line after this entry
46# in sync order
47SYNC_TARGETS = [
48 SyncTarget("pyproject", Pyproject, "pyproject.toml", codemeta_source=True),
49 SyncTarget("package_json", PackageJSON, "package.json", codemeta_source=True),
50 SyncTarget("julia", Julia, "Project.toml", codemeta_source=True, log_gap=True),
51 SyncTarget("fortran", Fortran, "fpm.toml(fortran)", codemeta_source=True),
52 SyncTarget("pom_xml", POM, "pom.xml", codemeta_source=True, log_gap=True),
53 SyncTarget("mkdocs", MkDocs, "mkdocs.yml"),
54 SyncTarget("rust", Rust, "Cargo.toml", codemeta_source=True),
55 SyncTarget("cff", CFF, "CITATION.cff", create_if_missing=True),
56 SyncTarget(
57 "codemeta", CodeMeta, "codemeta.json", create_if_missing=True, log_gap=True
58 ),
59]
62def _semantic_data(data: Any) -> Any:
63 """Return format-neutral data without formatting trivia."""
64 if isinstance(data, XMLProxy):
65 xml = ET.tostring(data._node, encoding="unicode")
66 return ET.canonicalize(xml, strip_text=True)
67 if unwrap := getattr(data, "unwrap", None):
68 data = unwrap()
69 if isinstance(data, Mapping):
70 return {key: _semantic_data(value) for key, value in data.items()}
71 if isinstance(data, (list, tuple)):
72 return [_semantic_data(value) for value in data]
73 return data
76class _PendingSave(NamedTuple):
77 """A synced writer whose file still has to be written."""
79 file: Path
80 writer: ProjectMetadataWriter
82 def save(self) -> None:
83 """Write the file."""
84 self.writer.save(self.file)
85 logger.log(VERBOSE, f"Saved synced '{self.file.name}'.\n")
88def _prepare_file(
89 metadata: ProjectMetadata,
90 file: Path,
91 writer_cls: type[ProjectMetadataWriter],
92 merge_codemeta: bool | None = False,
93 pass_validation: bool | None = False,
94 codemeta_sources: dict[str, Path | list[Path] | None] | None = None,
95 codemeta_root: Path | None = None,
96 codemeta_project_root: Path | None = None,
97):
98 """Sync metadata to a file in memory, return the pending save if it changed."""
99 logger.log(VERBOSE, f"Loading '{file.name}' ...")
100 existed = file.exists()
101 if writer_cls == CodeMeta:
102 enrich_root = codemeta_root or file.parent
103 writer: ProjectMetadataWriter = CodeMeta(
104 file,
105 merge=merge_codemeta,
106 pass_validation=pass_validation,
107 enrich_sources=codemeta_sources,
108 enrich_root=enrich_root,
109 enrich_project_root=codemeta_project_root or enrich_root,
110 )
111 else:
112 writer = writer_cls(file, pass_validation=pass_validation)
113 logger.log(VERBOSE, f"Syncing '{file.name}' ...")
114 original_data = _semantic_data(writer._data)
115 if writer_cls == CodeMeta and existed:
116 # the writer may already have upgraded a legacy file in memory:
117 # compare against what is actually on disk
118 try:
119 original_data = _semantic_data(json.loads(file.read_text(encoding="utf-8")))
120 except (OSError, ValueError):
121 pass
122 writer.sync(metadata)
123 if not existed or _semantic_data(writer._data) != original_data:
124 return _PendingSave(file, writer)
125 return None
128def _sync_file(*args, **kwargs) -> None:
129 """Sync metadata to a file using the provided writer and save it if changed."""
130 if pending := _prepare_file(*args, **kwargs):
131 pending.save()
134def _sync_files(
135 metadata,
136 files,
137 writer_class,
138 pending: list[_PendingSave],
139 create_if_missing: bool = False,
140 **kwargs,
141):
142 """Sync metadata to files in memory using the provided writer.
144 Files that need saving are appended to `pending`.
146 Args:
147 metadata: Project metadata to sync
148 files: Path or list of paths to sync
149 writer_class: Writer class to use
150 pending: Collects the saves of changed or missing files
151 create_if_missing: Whether to create the file if it doesn't exist
152 **kwargs: Additional arguments passed to the writer
154 """
155 if isinstance(files, Path):
156 files = [files]
157 for file in files:
158 if (file.is_file() or create_if_missing) and (
159 save := _prepare_file(metadata, file, writer_class, **kwargs)
160 ):
161 pending.append(save)
164def _describe_error(error: Exception) -> str:
165 """Return a short one-line description of a package loading error."""
166 if isinstance(error, ValidationError):
167 return "; ".join(
168 f"{'.'.join(str(part) for part in err['loc'])}: {err['msg']}"
169 for err in error.errors()
170 )
171 return str(error) or type(error).__name__
174def sync(
175 somesy_input: SomesyInput,
176 is_package: bool = False,
177 project_root: Path | None = None,
178):
179 """Sync selected metadata files with given input file.
181 All targets of the project and its packages are synced in memory first;
182 files are only written if that succeeded for every one of them.
184 Args:
185 somesy_input: The input configuration and metadata to sync
186 is_package: Whether this is a package (subfolder) being synced
187 project_root: Root of the overall project, differs from the base
188 directory for packages of a multi-package repository. Files shared
189 by all packages, such as a lock file, are looked up from here.
191 """
192 pending: list[_PendingSave] = []
193 _collect(somesy_input, pending, is_package, project_root)
194 _save_all(pending)
197def _save_all(pending: list[_PendingSave]) -> None:
198 """Save all pending files; if one fails, restore the others and re-raise."""
199 # original bytes per real path (None: did not exist); first occurrence wins
200 originals: dict[Path, bytes | None] = {}
201 for save in pending:
202 path = save.file.resolve()
203 if path not in originals:
204 originals[path] = path.read_bytes() if path.is_file() else None
205 try:
206 for save in pending:
207 save.save()
208 except BaseException:
209 failed = []
210 for path, data in originals.items():
211 try:
212 if data is not None:
213 if not path.is_file() or path.read_bytes() != data:
214 atomic_write(path, data)
215 else:
216 path.unlink(missing_ok=True)
217 except OSError:
218 failed.append(str(path))
219 if failed:
220 logger.error(
221 "Could not restore these files after a failed save: "
222 + ", ".join(failed)
223 )
224 raise
227def _collect(
228 somesy_input: SomesyInput,
229 pending: list[_PendingSave],
230 is_package: bool = False,
231 project_root: Path | None = None,
232) -> None:
233 """Sync the project and its packages in memory, collecting the pending saves."""
234 conf, metadata = somesy_input.config, somesy_input.project
236 # Get the base directory from the input file's location
237 if somesy_input._origin is None:
238 logger.warning(
239 "No origin found for somesy input, using current working directory."
240 )
241 base_dir = Path.cwd()
242 else:
243 base_dir = somesy_input._origin.parent
245 # Resolve all paths in the config relative to the base directory
246 conf.resolve_paths(base_dir)
248 if is_package:
249 logger.info("\n[bold green]Synchronizing package metadata...[/bold green]")
250 else:
251 logger.info("\n[bold green]Synchronizing root project metadata...[/bold green]")
253 pp_metadata = pretty_repr(metadata.model_dump(exclude_defaults=True))
254 logger.debug(f"Project metadata: {pp_metadata}")
256 # First sync the current project
257 _sync_root_project(conf, metadata, base_dir, project_root or base_dir, pending)
259 # Then sync each package if defined
260 if conf.packages:
261 packages = [conf.packages] if isinstance(conf.packages, Path) else conf.packages
262 skipped: list[Path] = []
263 for package in packages:
264 logger.info(f"\n[bold blue]Processing package {package}...[/bold blue]")
266 # Try all possible input files in order of priority
267 config_files = [package / file for file in INPUT_FILES_ORDERED]
268 package_input = None
269 config_file: Path | None = None
270 load_error: Exception | None = None
272 for config_file in config_files:
273 try:
274 package_input = SomesyInput.from_input_file(
275 config_file, allow_incomplete=bool(conf.pass_validation)
276 )
277 logger.debug(f"Found config file: {config_file}")
278 break
279 except (FileNotFoundError, RuntimeError):
280 continue
281 except (ValueError, KeyError, OSError) as error: # invalid config
282 load_error = error
283 break
285 if package_input is None:
286 if load_error is not None:
287 logger.warning(
288 f"Skipping package {package}: cannot load '{config_file}': "
289 f"{escape(_describe_error(load_error))}"
290 )
291 else:
292 logger.warning(
293 f"No valid somesy config found in package {package} "
294 f"(tried: {', '.join(str(f) for f in config_files)})"
295 )
296 skipped.append(package)
297 continue
299 # The package's own config is the base; only options explicitly
300 # passed on the root CLI override it (nothing is inherited from the
301 # root config file or defaults).
302 cli_overrides = {
303 key: value
304 for key, value in conf._cli_overrides.items()
305 if key.startswith("no_sync_")
306 or key in ("merge_codemeta", "pass_validation")
307 }
308 package_input.config = SomesyConfig(
309 **{
310 **package_input.config.model_dump(),
311 **cli_overrides,
312 "input_file": config_file,
313 "packages": None, # avoid recursive package handling
314 }
315 )
317 # CFF and CodeMeta paths are resolved relative to the package
318 # directory; unset ones fall back to the config defaults.
320 # Recursively call sync on the package
321 _collect(
322 package_input,
323 pending,
324 is_package=True,
325 project_root=project_root or base_dir,
326 )
328 if skipped:
329 logger.warning(
330 f"Skipped {len(skipped)} package(s) that could not be loaded: "
331 f"{', '.join(str(p) for p in skipped)}"
332 )
335def _sync_root_project(
336 conf: SomesyConfig,
337 metadata: ProjectMetadata,
338 base_dir: Path,
339 project_root: Path,
340 pending: list[_PendingSave],
341) -> None:
342 """Sync metadata files for the root project in memory."""
343 for target in SYNC_TARGETS:
344 if getattr(conf, f"no_sync_{target.key}"):
345 continue
346 files = getattr(conf, f"{target.key}_file")
347 # targets that are not created by default are updated only if they exist
348 if not (files or target.create_if_missing):
349 continue
350 kwargs: dict[str, Any] = {}
351 if target.writer is CodeMeta:
352 kwargs = {
353 "merge_codemeta": conf.merge_codemeta,
354 "codemeta_root": base_dir,
355 "codemeta_project_root": project_root,
356 "codemeta_sources": {
357 t.key: (
358 None
359 if getattr(conf, f"no_sync_{t.key}")
360 else getattr(conf, f"{t.key}_file")
361 )
362 for t in SYNC_TARGETS
363 if t.codemeta_source
364 },
365 }
366 _sync_files(
367 metadata,
368 files,
369 target.writer,
370 pending,
371 create_if_missing=target.create_if_missing,
372 pass_validation=conf.pass_validation,
373 **kwargs,
374 )