Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/how-to/repair-validation-errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ linkml-reference-validator repair data <DATA_FILE> --schema <SCHEMA> [OPTIONS]
- `--target-class CLASS` - Target class to validate
- `--dry-run / --no-dry-run` - Show changes without applying (default: dry-run)
- `--auto-fix-threshold FLOAT` - Minimum similarity for auto-fixes (default: 0.95)
- `--output PATH` - Output file path (default: overwrite with backup)
- `--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
- `--config PATH` - Path to repair configuration file
- `--cache-dir PATH` - Directory for caching references
- `--verbose` - Show detailed output
Expand Down
2 changes: 1 addition & 1 deletion docs/reference/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -543,7 +543,7 @@ linkml-reference-validator repair data [OPTIONS] DATA_FILE
- `--target-class TEXT, -t TEXT` - Target class to validate
- `--dry-run / --no-dry-run, -n / -N` - Show changes without applying (default: dry-run)
- `--auto-fix-threshold FLOAT, -a FLOAT` - Minimum similarity for auto-fixes (default: 0.95)
- `--output PATH, -o PATH` - Output file path (default: overwrite with backup)
- `--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
- `--config PATH` - Path to configuration file (.yaml)
- `--cache-dir PATH, -c PATH` - Directory for caching references
- `--verbose, -v` - Verbose output with detailed logging
Expand Down
92 changes: 73 additions & 19 deletions src/linkml_reference_validator/cli/repair.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
from typing_extensions import Annotated

from linkml_reference_validator.models import RepairActionType, RepairConfig
from linkml_reference_validator.plugins.reference_validation_plugin import (
extract_reference_id,
)
from linkml_reference_validator.validation.repairer import SupportingTextRepairer

from .shared import (
Expand Down Expand Up @@ -147,6 +150,8 @@ def data_command(

if not items_to_repair:
typer.echo("No evidence items found to repair.")
if not dry_run:
_copy_unchanged(data_file, output)
raise typer.Exit(0)

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

# Apply repairs if not dry run
if not dry_run and report.auto_fixed_count > 0:
# Create backup
if repair_config.create_backup:
backup_path = data_file.with_suffix(f"{data_file.suffix}.bak")
shutil.copy2(data_file, backup_path)
typer.echo(f"\nBackup created: {backup_path}")

# Apply auto-fixes to data
changes_made = _apply_repairs_to_data(data, report, target_class)

# Write output
output_path = output or data_file
with open(output_path, 'w') as f:
yaml.dump(data, f)

typer.echo(f"\n{'✓' if changes_made else '!'} Wrote {output_path}")
if not dry_run:
changes_made = report.auto_fixed_count > 0 and _apply_repairs_to_data(
data, report, target_class
)
if changes_made:
output_path = output or data_file
# A backup only matters when the input itself is overwritten.
if repair_config.create_backup and _same_file(output_path, data_file):
backup_path = data_file.with_suffix(f"{data_file.suffix}.bak")
shutil.copy2(data_file, backup_path)
typer.echo(f"\nBackup created: {backup_path}")
with open(output_path, 'w') as f:
yaml.dump(data, f)
typer.echo(f"\n✓ Wrote {output_path}")
typer.echo(f" Applied {report.auto_fixed_count} auto-fix(es)")
else:
if report.auto_fixed_count > 0:
typer.echo(
f"\n! {report.auto_fixed_count} auto-fix(es) could not be "
"placed back in the data"
)
_copy_unchanged(data_file, output)

# Exit with appropriate code
if (
Expand Down Expand Up @@ -266,6 +275,35 @@ def text_command(
raise typer.Exit(1)


def _same_file(a: Path, b: Path) -> bool:
"""Whether two paths name the same file, existing or not.

Symlinks are followed, so an output that links to the input is the input.

Examples:
>>> _same_file(Path("a.yaml"), Path("./a.yaml"))
True
>>> _same_file(Path("a.yaml"), Path("b.yaml"))
False
"""
return a.resolve() == b.resolve()


def _copy_unchanged(data_file: Path, output: Optional[Path]) -> None:
"""Write the input, byte for byte, to ``--output`` when nothing was fixed.

A pipeline that reads the output next must find it, and find this run's
data rather than a stale file from an earlier one (#143). Copying, rather
than dumping the parsed YAML, keeps the file identical to the input.
Without ``--output``, or with it naming the input, there is nothing to
write.
"""
if output is None or _same_file(output, data_file):
return
shutil.copyfile(data_file, output)
typer.echo(f"\nWrote {output} (no changes)")


def _load_repair_config(config_file: Optional[Path]) -> RepairConfig:
"""Load repair configuration from file.

Expand Down Expand Up @@ -371,9 +409,25 @@ def _extract_evidence_items(
def _extract_from_dict(d: dict, path: str = ""):
# Look for evidence patterns
if isinstance(d, dict):
# Direct evidence item pattern
ref = d.get("reference") or d.get("reference_id")
if ref:
# Direct evidence item pattern. The reference may be an inlined
# object, whose id is read with the validation plugin's own
# extract_reference_id (#138). Unlike validation, a repair needs
# exactly one source, so a list of references is skipped below, and
# each key is tried in turn, so a reference object with no id does
# not hide a usable reference_id beside it.
ref_value = d.get("reference") or d.get("reference_id")
ref = extract_reference_id(d.get("reference")) or extract_reference_id(
d.get("reference_id")
)
if ref is None and ref_value and _excerpt_keys(d):
# A list of references, or an object with no text id: a
# repair needs the one reference the quote came from.
logger.warning(
"Skipping evidence item at %s: its reference names no single "
"identifier, so its excerpt cannot be repaired",
path or "the top level",
)
if ref is not None:
for text_key in _excerpt_keys(d):
key_path = f"{path}.{text_key}" if path else text_key
items.append((d[text_key], ref, key_path))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,35 @@ class ResolvedReference(NamedTuple):
path: str


def extract_reference_id(reference_value: Any) -> Optional[str]:
"""The identifier a single reference value names, or None.

A string is the identifier; a reference object carries it as ``id`` (or
``reference_id``). Anything else, including a list of references or an
identifier that is not text, names no single reference. Defined outside
the plugin so code that runs without LinkML, such as ``repair data``,
reads references the same way (#138).

Examples:
>>> extract_reference_id("PMID:12345678")
'PMID:12345678'
>>> extract_reference_id({"id": "PMID:12345678", "title": "T"})
'PMID:12345678'
>>> extract_reference_id({"reference_id": "PMID:1"})
'PMID:1'
>>> extract_reference_id({"id": 123}) is None
True
>>> extract_reference_id(["PMID:1", "PMID:2"]) is None
True
"""
if isinstance(reference_value, dict):
reference_value = reference_value.get("id") or reference_value.get("reference_id")
# Only text can be an identifier; {"id": 123} would crash parsing.
if isinstance(reference_value, str) and reference_value:
return reference_value
return None


if _LINKML_AVAILABLE:
# NOTE: `linkml` is optional. We only import LinkML modules when available.
# Ruff's E402 doesn't like imports in blocks, so we silence it per-import.
Expand Down Expand Up @@ -755,14 +784,7 @@ def _extract_reference_id(self, reference_value: Any) -> Optional[str]:
>>> plugin._extract_reference_id({"id": 123}) is None
True
"""
if isinstance(reference_value, dict):
reference_value = reference_value.get("id") or reference_value.get(
"reference_id"
)
# Only text can be an identifier; {"id": 123} would crash parsing.
if isinstance(reference_value, str) and reference_value:
return reference_value
return None
return extract_reference_id(reference_value)

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