Skip to content

Commit 7fcb8a8

Browse files
authored
Merge pull request #159 from linkml/ccr-65a5480d-pb91sk
Make repair data always write --output, and read inlined references
2 parents 46dd616 + 4c70efd commit 7fcb8a8

5 files changed

Lines changed: 372 additions & 29 deletions

File tree

‎docs/how-to/repair-validation-errors.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -268,7 +268,7 @@ linkml-reference-validator repair data <DATA_FILE> --schema <SCHEMA> [OPTIONS]
268268
- `--target-class CLASS` - Target class to validate
269269
- `--dry-run / --no-dry-run` - Show changes without applying (default: dry-run)
270270
- `--auto-fix-threshold FLOAT` - Minimum similarity for auto-fixes (default: 0.95)
271-
- `--output PATH` - Output file path (default: overwrite with backup)
271+
- `--output PATH` - Output file path (default: overwrite the input, keeping a `.bak` backup). When given with `--no-dry-run`, it is always written, as an unchanged copy of the input when there is nothing to fix, and the input itself is not touched, so no backup is made
272272
- `--config PATH` - Path to repair configuration file
273273
- `--cache-dir PATH` - Directory for caching references
274274
- `--verbose` - Show detailed output

‎docs/reference/cli.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -543,7 +543,7 @@ linkml-reference-validator repair data [OPTIONS] DATA_FILE
543543
- `--target-class TEXT, -t TEXT` - Target class to validate
544544
- `--dry-run / --no-dry-run, -n / -N` - Show changes without applying (default: dry-run)
545545
- `--auto-fix-threshold FLOAT, -a FLOAT` - Minimum similarity for auto-fixes (default: 0.95)
546-
- `--output PATH, -o PATH` - Output file path (default: overwrite with backup)
546+
- `--output PATH, -o PATH` - Output file path (default: overwrite the input, keeping a `.bak` backup). When given with `--no-dry-run`, it is always written, as an unchanged copy of the input when there is nothing to fix, and the input itself is not touched, so no backup is made
547547
- `--config PATH` - Path to configuration file (.yaml)
548548
- `--cache-dir PATH, -c PATH` - Directory for caching references
549549
- `--verbose, -v` - Verbose output with detailed logging

‎src/linkml_reference_validator/cli/repair.py‎

Lines changed: 73 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@
1414
from typing_extensions import Annotated
1515

1616
from linkml_reference_validator.models import RepairActionType, RepairConfig
17+
from linkml_reference_validator.plugins.reference_validation_plugin import (
18+
extract_reference_id,
19+
)
1720
from linkml_reference_validator.validation.repairer import SupportingTextRepairer
1821

1922
from .shared import (
@@ -147,6 +150,8 @@ def data_command(
147150

148151
if not items_to_repair:
149152
typer.echo("No evidence items found to repair.")
153+
if not dry_run:
154+
_copy_unchanged(data_file, output)
150155
raise typer.Exit(0)
151156

152157
typer.echo(f"Found {len(items_to_repair)} evidence item(s) to process\n")
@@ -158,24 +163,28 @@ def data_command(
158163
typer.echo(repairer.format_report(report, verbose=verbose))
159164

160165
# Apply repairs if not dry run
161-
if not dry_run and report.auto_fixed_count > 0:
162-
# Create backup
163-
if repair_config.create_backup:
164-
backup_path = data_file.with_suffix(f"{data_file.suffix}.bak")
165-
shutil.copy2(data_file, backup_path)
166-
typer.echo(f"\nBackup created: {backup_path}")
167-
168-
# Apply auto-fixes to data
169-
changes_made = _apply_repairs_to_data(data, report, target_class)
170-
171-
# Write output
172-
output_path = output or data_file
173-
with open(output_path, 'w') as f:
174-
yaml.dump(data, f)
175-
176-
typer.echo(f"\n{'✓' if changes_made else '!'} Wrote {output_path}")
166+
if not dry_run:
167+
changes_made = report.auto_fixed_count > 0 and _apply_repairs_to_data(
168+
data, report, target_class
169+
)
177170
if changes_made:
171+
output_path = output or data_file
172+
# A backup only matters when the input itself is overwritten.
173+
if repair_config.create_backup and _same_file(output_path, data_file):
174+
backup_path = data_file.with_suffix(f"{data_file.suffix}.bak")
175+
shutil.copy2(data_file, backup_path)
176+
typer.echo(f"\nBackup created: {backup_path}")
177+
with open(output_path, 'w') as f:
178+
yaml.dump(data, f)
179+
typer.echo(f"\n✓ Wrote {output_path}")
178180
typer.echo(f" Applied {report.auto_fixed_count} auto-fix(es)")
181+
else:
182+
if report.auto_fixed_count > 0:
183+
typer.echo(
184+
f"\n! {report.auto_fixed_count} auto-fix(es) could not be "
185+
"placed back in the data"
186+
)
187+
_copy_unchanged(data_file, output)
179188

180189
# Exit with appropriate code
181190
if (
@@ -266,6 +275,35 @@ def text_command(
266275
raise typer.Exit(1)
267276

268277

278+
def _same_file(a: Path, b: Path) -> bool:
279+
"""Whether two paths name the same file, existing or not.
280+
281+
Symlinks are followed, so an output that links to the input is the input.
282+
283+
Examples:
284+
>>> _same_file(Path("a.yaml"), Path("./a.yaml"))
285+
True
286+
>>> _same_file(Path("a.yaml"), Path("b.yaml"))
287+
False
288+
"""
289+
return a.resolve() == b.resolve()
290+
291+
292+
def _copy_unchanged(data_file: Path, output: Optional[Path]) -> None:
293+
"""Write the input, byte for byte, to ``--output`` when nothing was fixed.
294+
295+
A pipeline that reads the output next must find it, and find this run's
296+
data rather than a stale file from an earlier one (#143). Copying, rather
297+
than dumping the parsed YAML, keeps the file identical to the input.
298+
Without ``--output``, or with it naming the input, there is nothing to
299+
write.
300+
"""
301+
if output is None or _same_file(output, data_file):
302+
return
303+
shutil.copyfile(data_file, output)
304+
typer.echo(f"\nWrote {output} (no changes)")
305+
306+
269307
def _load_repair_config(config_file: Optional[Path]) -> RepairConfig:
270308
"""Load repair configuration from file.
271309
@@ -371,9 +409,25 @@ def _extract_evidence_items(
371409
def _extract_from_dict(d: dict, path: str = ""):
372410
# Look for evidence patterns
373411
if isinstance(d, dict):
374-
# Direct evidence item pattern
375-
ref = d.get("reference") or d.get("reference_id")
376-
if ref:
412+
# Direct evidence item pattern. The reference may be an inlined
413+
# object, whose id is read with the validation plugin's own
414+
# extract_reference_id (#138). Unlike validation, a repair needs
415+
# exactly one source, so a list of references is skipped below, and
416+
# each key is tried in turn, so a reference object with no id does
417+
# not hide a usable reference_id beside it.
418+
ref_value = d.get("reference") or d.get("reference_id")
419+
ref = extract_reference_id(d.get("reference")) or extract_reference_id(
420+
d.get("reference_id")
421+
)
422+
if ref is None and ref_value and _excerpt_keys(d):
423+
# A list of references, or an object with no text id: a
424+
# repair needs the one reference the quote came from.
425+
logger.warning(
426+
"Skipping evidence item at %s: its reference names no single "
427+
"identifier, so its excerpt cannot be repaired",
428+
path or "the top level",
429+
)
430+
if ref is not None:
377431
for text_key in _excerpt_keys(d):
378432
key_path = f"{path}.{text_key}" if path else text_key
379433
items.append((d[text_key], ref, key_path))

‎src/linkml_reference_validator/plugins/reference_validation_plugin.py‎

Lines changed: 30 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,35 @@ class ResolvedReference(NamedTuple):
3737
path: str
3838

3939

40+
def extract_reference_id(reference_value: Any) -> Optional[str]:
41+
"""The identifier a single reference value names, or None.
42+
43+
A string is the identifier; a reference object carries it as ``id`` (or
44+
``reference_id``). Anything else, including a list of references or an
45+
identifier that is not text, names no single reference. Defined outside
46+
the plugin so code that runs without LinkML, such as ``repair data``,
47+
reads references the same way (#138).
48+
49+
Examples:
50+
>>> extract_reference_id("PMID:12345678")
51+
'PMID:12345678'
52+
>>> extract_reference_id({"id": "PMID:12345678", "title": "T"})
53+
'PMID:12345678'
54+
>>> extract_reference_id({"reference_id": "PMID:1"})
55+
'PMID:1'
56+
>>> extract_reference_id({"id": 123}) is None
57+
True
58+
>>> extract_reference_id(["PMID:1", "PMID:2"]) is None
59+
True
60+
"""
61+
if isinstance(reference_value, dict):
62+
reference_value = reference_value.get("id") or reference_value.get("reference_id")
63+
# Only text can be an identifier; {"id": 123} would crash parsing.
64+
if isinstance(reference_value, str) and reference_value:
65+
return reference_value
66+
return None
67+
68+
4069
if _LINKML_AVAILABLE:
4170
# NOTE: `linkml` is optional. We only import LinkML modules when available.
4271
# Ruff's E402 doesn't like imports in blocks, so we silence it per-import.
@@ -755,14 +784,7 @@ def _extract_reference_id(self, reference_value: Any) -> Optional[str]:
755784
>>> plugin._extract_reference_id({"id": 123}) is None
756785
True
757786
"""
758-
if isinstance(reference_value, dict):
759-
reference_value = reference_value.get("id") or reference_value.get(
760-
"reference_id"
761-
)
762-
# Only text can be an identifier; {"id": 123} would crash parsing.
763-
if isinstance(reference_value, str) and reference_value:
764-
return reference_value
765-
return None
787+
return extract_reference_id(reference_value)
766788

767789
def _extract_title(self, reference_value: Any) -> Optional[str]:
768790
"""Extract title from reference value.

0 commit comments

Comments
 (0)