requirements.integration.report_api
Requirements index · View definition
Requirement
habeas::validate_repository(root)MUST return a report with the number of discovered requirements, the number of discovered examples, the number of evidence files, and all validation errors for the supplied project. Ordinary invalid evidence MUST be reported in that report; an inaccessible project root MUST return an I/O error.
Rationale
I found no gaps. The text has three obligations. validate_repository must return the counts and all validation errors. Ordinary invalid evidence must be reported in the report. An inaccessible root must return an I/O error.
Code
src/evidence.rs#fn[validate_repository]returnsinspect_repository(root)?.report. It callsinspect_repository_with_progress, whichinspect_repositorywraps.src/evidence.rs#struct[EvidenceReport]carriesrequirements,examples,evidence_filesanderrors.src/evidence.rs#fn[inspect_repository_with_progress]fills those fields:- It counts definitions of kind
Requirementand kindExampleseparately. - It sets
evidence_filesto the number of discovered evidence files. - It pushes every validation finding into
errors. This covers config, book and definition errors, per-file evidence errors, orphan evidence, missing evidence, reference, citation, site and coverage errors. - It does not return
Errfor invalid evidence.
- It counts definitions of kind
- The root is opened with
fs::canonicalize(root)?as the first step. An inaccessible root therefore returnsErr, while ordinary evidence problems stay inerrors.
Tests
- Counts and an empty
errors:validates_full_names_requirement_text_and_input_linesandcited_example_with_a_test_and_matching_evidence_validates. The latter asserts 1 requirement, 1 example and 2 evidence files. - Errors collected in the report:
collects_missing_orphan_format_false_and_changed_line_errorsasserts a long list of error messages.cited_example_with_a_test_and_matching_evidence_validatesasserts further errors after each mutation. Thetests/evidence_boundaries.rstestdiscovered_external_cargo_outputs_validate_freshness_and_obey_disallowasserts errors for changed and disallowed inputs. - An I/O error for an inaccessible root:
inaccessible_project_root_is_an_io_error_not_a_reportassertsNotFoundfor a missing root. It also asserts that invalid evidence in an accessible root appears inreport.errors. inspection_progress_preserves_validation_and_finishes_each_phaseandfixme_fixtureadd further coverage of the report fields.
I found no unspecified extra behavior in the {impl} items.
Inputs
Implementation
Input 2: outline src/evidence.rs struct[EvidenceReport]
- File:
src/evidence.rs - Selector:
struct[EvidenceReport] - Kind:
struct src/evidence.rs:16–23
// {impl}`requirements.integration.report_api`
#[derive(Debug)]
pub struct EvidenceReport {
pub requirements: usize,
pub examples: usize,
pub evidence_files: usize,
pub errors: Vec<String>,
}
Input 3: outline src/evidence.rs fn[validate_repository]
- File:
src/evidence.rs - Selector:
fn[validate_repository] - Kind:
fn src/evidence.rs:120–123
// {impl}`requirements.integration.report_api`
pub fn validate_repository(root: &Path) -> io::Result<EvidenceReport> {
Ok(inspect_repository(root)?.report)
}
Tests
Input 4: outline src/evidence.rs mod[tests]/fn[inspection_progress_preserves_validation_and_finishes_each_phase]
- File:
src/evidence.rs - Selector:
mod[tests]/fn[inspection_progress_preserves_validation_and_finishes_each_phase] - Kind:
fn src/evidence.rs:2309–2407
// {test}`requirements.authoring.progress`
// {test}`requirements.integration.report_api`
// {test}`requirements.ci.errors`
#[test]
fn inspection_progress_preserves_validation_and_finishes_each_phase() {
let temp = fixture();
let root = temp.path();
fs::write(
root.join("md/requirements.md"),
":::{req} ready\nThe check MUST pass.\n:::\n",
)
.unwrap();
fs::write(
root.join("evidence/requirements.ready.json"),
json!({
"requirement": "The check MUST pass.",
"determination": true,
"rationale": "The inspected file has the expected lines.",
"inputs": [outline(root, "src/main.rs", "")]
})
.to_string(),
)
.unwrap();
for invalid in [false, true] {
if invalid {
fs::write(root.join("evidence/broken.json"), "{").unwrap();
fs::write(root.join("src/broken.rs"), "fn {").unwrap();
fs::write(root.join("src/lib.rs"), "fn retained() {}\n").unwrap();
fs::write(root.join("src/binary.dat"), [0xff]).unwrap();
}
stamp_reference_sets(root);
let expected = super::inspect_repository(root).unwrap();
let mut updates = Vec::new();
let inspected =
super::inspect_repository_with_progress(root, |update| updates.push(update))
.unwrap();
assert_eq!(inspected.report.requirements, expected.report.requirements);
assert_eq!(inspected.report.examples, expected.report.examples);
assert_eq!(
inspected.report.evidence_files,
expected.report.evidence_files
);
assert_eq!(inspected.report.errors, expected.report.errors);
assert_eq!(inspected.discovery_errors, expected.discovery_errors);
assert_eq!(
inspected.definitions.keys().collect::<Vec<_>>(),
expected.definitions.keys().collect::<Vec<_>>()
);
assert_eq!(inspected.report.requirements, 1);
assert_eq!(inspected.report.examples, 0);
if invalid {
let errors = inspected.report.errors.join("\n");
for error in ["invalid JSON", "cannot parse Rust source"] {
assert!(errors.contains(error), "missing {error:?}: {errors}");
}
// An uncovered item is reported, not a validation error.
assert!(!errors.contains("retained"), "{errors}");
assert!(
inspected.uncovered.iter().any(|item| item
.error
.starts_with("src/lib.rs:1: function retained has no recent coverage")),
"{:?}",
inspected.uncovered
);
let discovery = inspected.discovery_errors.join("\n");
assert!(
discovery.contains("src/broken.rs")
&& discovery.contains("cannot parse Rust source"),
"{discovery}"
);
assert!(!discovery.contains("retained"), "{discovery}");
} else {
assert!(inspected.report.errors.is_empty());
}
assert!(updates.iter().any(|update| update.total.is_none()));
assert!(updates.iter().all(|update| {
update
.total
.map_or(update.completed == 0, |total| update.completed <= total)
}));
let expected_counts = [
("evidence files", if invalid { 2 } else { 1 }),
("reference source files", if invalid { 8 } else { 5 }),
("reference coverage", 1),
];
for (stage, total) in expected_counts {
let completed: Vec<_> = updates
.iter()
.filter(|update| update.stage == stage && update.total.is_some())
.map(|update| {
assert_eq!(update.total, Some(total), "{stage}");
update.completed
})
.collect();
assert_eq!(completed, (0..=total).collect::<Vec<_>>(), "{stage}");
}
}
}
Input 5: outline src/evidence.rs mod[tests]/fn[validates_full_names_requirement_text_and_input_lines]
- File:
src/evidence.rs - Selector:
mod[tests]/fn[validates_full_names_requirement_text_and_input_lines] - Kind:
fn src/evidence.rs:2533–2564
// {test}`requirements.integration.report_api`
// {test}`requirements.ci.book_source`
// {test}`requirements.ci.coverage`
// {test}`requirements.ci.requirement_text`
// {test}`requirements.ci.outline_inputs`
// {test}`requirements.ci.identifiers`
// {test}`requirements.ci.span`
#[test]
fn validates_full_names_requirement_text_and_input_lines() {
let temp = fixture();
fs::write(
temp.path().join("md/reqs/foo/bar.md"),
"# Requirements\n\n:::{req} ready\n\n The check MUST pass.\n\n```text\n{req}`example`\n```\n:::\n",
)
.unwrap();
fs::write(
temp.path().join("evidence/foo.bar.ready.json"),
json!({
"requirement": "The check MUST pass.\n\n```text\n{req}`example`\n```",
"determination": true,
"rationale": "The inspected file has the expected lines.",
"inputs": [outline(temp.path(), "src/main.rs", "")]
})
.to_string(),
)
.unwrap();
let report = validate_repository(temp.path()).unwrap();
assert_eq!(report.requirements, 1);
assert_eq!(report.evidence_files, 1);
assert!(report.errors.is_empty(), "{:?}", report.errors);
}
Input 6: outline src/evidence.rs mod[tests]/fn[collects_missing_orphan_format_false_and_changed_line_errors]
- File:
src/evidence.rs - Selector:
mod[tests]/fn[collects_missing_orphan_format_false_and_changed_line_errors] - Kind:
fn src/evidence.rs:2566–2667
// {test}`requirements.integration.report_api`
// {test}`requirements.ci.errors`
// {test}`requirements.ci.diagnostics`
// {test}`requirements.ci.input_containment`
// {test}`requirements.ci.definition_errors`
// {test}`requirements.ci.orphans`
// {test}`requirements.ci.coverage`
// {test}`requirements.ci.determination`
// {test}`requirements.ci.outline_inputs`
// {test}`requirements.ci.requirement_text`
// {test}`requirements.ci.schema`
#[test]
fn collects_missing_orphan_format_false_and_changed_line_errors() {
let temp = fixture();
fs::write(
temp.path().join("md/requirements.md"),
"# Requirements\n\n:::{req} one\nFirst.\n:::\n\n:::{req} two\nSecond.\n:::\n\n:::{req} three\nThird.\n:::\n\n:::{req} one\nDuplicate.\n:::\n\n:::{req} empty\n \n:::\n",
)
.unwrap();
fs::write(
temp.path().join("evidence/requirements.one.json"),
json!({
"requirement": "Old text.",
"determination": false,
"rationale": "Work remains.",
"inputs": [
{
"file": "src/main.rs",
"item": "",
"hash": "0".repeat(64)
},
{
"file": "",
"item": 0,
"hash": "ABC"
},
{
"file": "src/main.rs",
"item": "fn[missing]",
"hash": "0".repeat(64)
},
{
"file": "src/main.rs",
"line_start": 1,
"line_end": 1,
"text": ["// first line"]
},
{
"requirements": "requirements.two",
"matches": ["requirements.two"],
"text": [1]
}
]
})
.to_string(),
)
.unwrap();
fs::write(
temp.path().join("evidence/requirements.three.json"),
json!({"requirement": 3, "inputs": {}}).to_string(),
)
.unwrap();
fs::write(
temp.path().join("evidence/ghost.json"),
json!({
"requirement": "Ghost.",
"determination": true,
"rationale": "A valid but orphaned file.",
"inputs": []
})
.to_string(),
)
.unwrap();
fs::write(temp.path().join("evidence/broken.json"), "{").unwrap();
let report = validate_repository(temp.path()).unwrap();
let errors = report.errors.join("\n");
for detail in [
"no matching requirement",
"invalid JSON",
"missing for requirement",
"requirement text changed",
"- Old text.",
"+ First.",
"determination is false",
"inputs[0]: outline input changed: src/main.rs <root> (now lines 1-2) no longer has the recorded hash",
"inputs[1]: file must be a nonempty path",
"inputs[1]: item must be a string",
"inputs[1]: hash must be a lowercase hexadecimal SHA-256 digest",
"inputs[2]: src/main.rs: no outline node matches \"fn[missing]\"",
"inputs[3]: unexpected field \"line_start\"",
"inputs[3]: missing field \"item\"",
"inputs[4]: text[0] must be a string",
"requirement must be a string",
"missing field \"determination\"",
"inputs must be an array",
"duplicate requirement requirements.one; first declared at md/requirements.md:3",
"requirement requirements.empty has no text",
] {
assert!(errors.contains(detail), "missing {detail:?} in:\n{errors}");
}
}
Input 7: outline src/evidence.rs mod[tests]/fn[cited_example_with_a_test_and_matching_evidence_validates]
- File:
src/evidence.rs - Selector:
mod[tests]/fn[cited_example_with_a_test_and_matching_evidence_validates] - Kind:
fn src/evidence.rs:3498–3632
// {test}`requirements.examples.definition`
// {test}`requirements.examples.evidence`
// {test}`requirements.integration.report_api`
// {test}`requirements.ci.schema`
// {test}`requirements.references.evidence_coverage`
// {test}`requirements.ci.requirements_inputs`
// {test}`requirements.ci.orphans`
#[test]
fn cited_example_with_a_test_and_matching_evidence_validates() {
let temp = fixture();
let chapter = "# Rules\n\n:::{req} ready\nReady.\n:::\n\n:::{example} case\nGiven ready, it succeeds. {cite}`rules.ready` {test}`rules.ready`\n:::\n";
fs::write(temp.path().join("md/rules.md"), chapter).unwrap();
let test_source = "// {test}`rules.case`\n#[test]\nfn checks_case() { assert!(true); }\n";
fs::write(temp.path().join("src/main.rs"), test_source).unwrap();
fs::write(
temp.path().join("evidence/rules.ready.json"),
json!({
"requirement": "Ready.",
"determination": true,
"rationale": "The example cites this rule.",
"inputs": crate::inputs::outline_inputs_for_lines(temp.path(), "md/rules.md", 8, 8)
.unwrap()
})
.to_string(),
)
.unwrap();
let example_path = temp.path().join("evidence/rules.case.json");
fs::write(
&example_path,
json!({
"example": "Given ready, it succeeds. {cite}`rules.ready` {test}`rules.ready`",
"determination": true,
"rationale": "checks_case sets up ready and asserts the result.",
"inputs": [
outline(temp.path(), "src/main.rs", "fn[checks_case]"),
{
"requirements": "rules.*",
"matches": ["rules.case", "rules.ready"],
"text": [
chapter.lines().nth(6).unwrap(),
chapter.lines().nth(7).unwrap(),
chapter.lines().nth(8).unwrap(),
"",
chapter.lines().nth(2).unwrap(),
chapter.lines().nth(3).unwrap(),
chapter.lines().nth(4).unwrap()
]
}
]
})
.to_string(),
)
.unwrap();
let report = validate_repository(temp.path()).unwrap();
assert_eq!(report.requirements, 1);
assert_eq!(report.examples, 1);
assert_eq!(report.evidence_files, 2);
assert!(report.errors.is_empty(), "{:?}", report.errors);
let ready_path = temp.path().join("evidence/rules.ready.json");
let ready = fs::read_to_string(&ready_path).unwrap();
let mut missing: Value = serde_json::from_str(&ready).unwrap();
missing["inputs"] = json!([]);
fs::write(&ready_path, missing.to_string()).unwrap();
let errors = validate_repository(temp.path()).unwrap().errors;
assert!(
errors.iter().any(|error| error.contains("no input covers")
&& error.contains("{test}")
&& error.contains("rules.ready")
&& error.contains("md/rules.md:8")),
"{errors:?}"
);
fs::write(ready_path, ready).unwrap();
let old = fs::read_to_string(&example_path).unwrap();
let mut uncovered: serde_json::Value = serde_json::from_str(&old).unwrap();
uncovered["inputs"] = json!([]);
fs::write(&example_path, uncovered.to_string()).unwrap();
let errors = validate_repository(temp.path()).unwrap().errors.join("\n");
assert!(errors.contains("no input covers"), "{errors}");
assert!(errors.contains("src/main.rs:1"), "{errors}");
fs::write(&example_path, &old).unwrap();
fs::write(
temp.path().join("src/main.rs"),
test_source.replace("assert!(true)", "assert!(false)"),
)
.unwrap();
let errors = validate_repository(temp.path()).unwrap().errors.join("\n");
assert!(
errors.contains(
"outline input changed: src/main.rs fn[checks_case] (now lines 1-3) no longer has the recorded hash"
),
"{errors}"
);
fs::write(temp.path().join("src/main.rs"), test_source).unwrap();
fs::write(
temp.path().join("md/rules.md"),
format!("{chapter}\n:::{req} added\nAdded.\n:::\n", req = "{req}"),
)
.unwrap();
let errors = validate_repository(temp.path()).unwrap().errors.join("\n");
assert!(
errors.contains(
"requirements glob \"rules.*\" matches changed; added [\"rules.added\"], removed []"
),
"{errors}"
);
let mut evidence: serde_json::Value = serde_json::from_str(&old).unwrap();
evidence["example"] = "Outdated.".into();
fs::write(&example_path, evidence.to_string()).unwrap();
let errors = validate_repository(temp.path()).unwrap().errors.join("\n");
assert!(errors.contains("example text changed"), "{errors}");
assert!(errors.contains("- Outdated."), "{errors}");
let mut wrong_field: serde_json::Value = serde_json::from_str(&old).unwrap();
let example_text = wrong_field
.as_object_mut()
.unwrap()
.remove("example")
.unwrap();
wrong_field["requirement"] = example_text;
fs::write(&example_path, wrong_field.to_string()).unwrap();
let errors = validate_repository(temp.path()).unwrap().errors.join("\n");
assert!(errors.contains("missing field \"example\""), "{errors}");
assert!(
errors.contains("unexpected field \"requirement\""),
"{errors}"
);
fs::remove_file(&example_path).unwrap();
let errors = validate_repository(temp.path()).unwrap().errors.join("\n");
assert!(errors.contains("missing for example"), "{errors}");
}
Input 8: outline tests/commands.rs fn[fixme_fixture]
- File:
tests/commands.rs - Selector:
fn[fixme_fixture] - Kind:
fn tests/commands.rs:119–221
// {test}`requirements.ci.outcomes`
// {test}`requirements.ci.determination`
// {test}`requirements.ci.schema`
// {test}`requirements.integration.report_api`
fn fixme_fixture() -> TempDir {
let temp = TempDir::new().unwrap();
fs::create_dir(temp.path().join("md")).unwrap();
fs::create_dir(temp.path().join("evidence")).unwrap();
fs::write(
temp.path().join("Cargo.toml"),
"[package]\nname = 'fixture'\n",
)
.unwrap();
fs::write(temp.path().join("book.toml"), "[book]\nsrc = 'md'\n").unwrap();
let example = "A concrete case. {cite}`rules.alpha`.";
let declarations = [
(
"req",
"alpha",
"Alpha MUST work.",
vec![
"example/app#123",
"rust-lang/rust#456",
"Unlinked extra detail",
],
),
(
"req",
"beta",
"Beta MUST work.",
vec![
"example/app#123",
"example/app#45",
"Rust-Lang/rust#456",
"An unrelated note",
],
),
("example", "case", example, vec!["example/app#45"]),
(
"req",
"unlinked",
"Unlinked MUST work.",
vec![
"No ticket for <script>alert(1)</script>",
"#123 is not a qualified issue",
"https://github.com/rust-lang/rust/issues/456",
],
),
];
let source: String = declarations
.iter()
.map(|(kind, name, text, _)| format!(":::{{{kind}}} {name}\n{text}\n:::\n\n"))
.collect();
fs::write(temp.path().join("md/rules.md"), &source).unwrap();
// Each judgment's strings come from the `{fixme}` references to it: one
// naming its issues, and one per gap without an issue.
let mut gaps = String::new();
for (_, name, _, entries) in &declarations {
let (issues, others): (Vec<&str>, Vec<&str>) = entries
.iter()
.partition(|entry| entry.contains('/') && !entry.contains(' ') && !entry.contains(':'));
if !issues.is_empty() {
gaps.push_str(&format!(":::{{fixme}} rules.{name}\n"));
for issue in issues {
gaps.push_str(&format!(":github: {issue}\n"));
}
gaps.push_str("Tracked gaps.\n:::\n\n");
}
for other in others {
gaps.push_str(&format!(":::{{fixme}} rules.{name}\n{other}\n:::\n\n"));
}
}
fs::write(temp.path().join("gaps.txt"), gaps).unwrap();
let input = habeas::outline_input(temp.path(), "md/rules.md", "").unwrap();
let gaps_input = habeas::outline_input(temp.path(), "gaps.txt", "").unwrap();
for (kind, name, text, references) in declarations {
let subject_key = if kind == "example" {
"example"
} else {
"requirement"
};
fs::write(
temp.path().join(format!("evidence/rules.{name}.json")),
json!({
subject_key: text,
"determination": {"FIXME": references},
"rationale": "The fixture records acknowledged implementation gaps.",
"references": habeas::reference_set_digest_for(
temp.path(),
&format!("rules.{name}")
)
.unwrap(),
"inputs": [input, gaps_input]
})
.to_string(),
)
.unwrap();
}
common::coverage_setup(temp.path());
let report = habeas::validate_repository(temp.path()).unwrap();
assert!(report.errors.is_empty(), "{:?}", report.errors);
temp
}
Input 9: outline tests/evidence_boundaries.rs fn[discovered_external_cargo_outputs_validate_freshness_and_obey_disallow]
- File:
tests/evidence_boundaries.rs - Selector:
fn[discovered_external_cargo_outputs_validate_freshness_and_obey_disallow] - Kind:
fn tests/evidence_boundaries.rs:535–595
// {test}`requirements.authoring.generated_inputs`
// {test}`requirements.configuration.evidence_paths`
// {test}`requirements.ci.input_containment`
// {test}`requirements.ci.outline_inputs`
// {test}`requirements.integration.report_api`
#[test]
fn discovered_external_cargo_outputs_validate_freshness_and_obey_disallow() {
let temp = fixture();
let root = temp.path().join("project");
fs::write(
root.join("Cargo.toml"),
"[package]\nname = 'fixture'\nversion = '0.1.0'\n",
)
.unwrap();
fs::write(
root.join("Cargo.lock"),
"version = 4\n\n[[package]]\nname = 'fixture'\nversion = '0.1.0'\n",
)
.unwrap();
fs::write(root.join("src/lib.rs"), "").unwrap();
fs::create_dir(root.join(".cargo")).unwrap();
let build = temp.path().join("external-build");
let target = temp.path().join("external-target");
fs::write(
root.join(".cargo/config.toml"),
format!(
"[build]\nbuild-dir = {}\ntarget-dir = {}\n",
toml::Value::String(build.display().to_string()),
toml::Value::String(target.display().to_string()),
),
)
.unwrap();
let out = build.join("debug/build/fixture-hash/out");
fs::create_dir_all(&out).unwrap();
fs::write(
out.parent().unwrap().join("root-output"),
out.to_str().unwrap(),
)
.unwrap();
let generated = out.join("generated.rs");
fs::write(&generated, "pub fn generated() {}\n").unwrap();
{
fs::write(root.join("habeas.toml"), "version = 1\n").unwrap();
let input = outline(&root, generated.to_str().unwrap(), "fn[generated]");
write_inputs(&root, vec![input]);
let report = validate_repository(&root).unwrap();
assert!(report.errors.is_empty(), "{:?}", report.errors);
fs::write(&generated, "pub fn generated() { changed(); }\n").unwrap();
let errors = validate_repository(&root).unwrap().errors.join("\n");
assert!(errors.contains("outline input changed"), "{errors}");
fs::write(&generated, "pub fn generated() {}\n").unwrap();
fs::write(
root.join("habeas.toml"),
"version = 1\n[evidence]\ndisallow = ['../external-build']\n",
)
.unwrap();
let errors = validate_repository(&root).unwrap().errors.join("\n");
assert!(errors.contains("disallowed"), "{errors}");
}
assert!(!target.exists(), "metadata must not run a build");
}
Input 10: outline tests/evidence_boundaries.rs fn[inaccessible_project_root_is_an_io_error_not_a_report]
- File:
tests/evidence_boundaries.rs - Selector:
fn[inaccessible_project_root_is_an_io_error_not_a_report] - Kind:
fn tests/evidence_boundaries.rs:597–618
// {test}`requirements.integration.report_api`
#[test]
fn inaccessible_project_root_is_an_io_error_not_a_report() {
let temp = tempfile::tempdir().unwrap();
let missing = temp.path().join("missing");
let error = validate_repository(&missing).unwrap_err();
assert_eq!(error.kind(), std::io::ErrorKind::NotFound, "{error}");
// Ordinary invalid evidence in an accessible root is reported instead.
let project = fixture();
let root = project.path().join("project");
fs::write(root.join("evidence/unknown.thing.json"), "{broken").unwrap();
let report = validate_repository(&root).unwrap();
assert!(
report
.errors
.iter()
.any(|error| error.contains("unknown.thing.json")),
"{:#?}",
report.errors
);
}
Other sources
Input 1: requirements selection requirements.integration.report_api
requirements.integration.report_api:md/requirements/integration.md:94–96
:::{req} report_api
`habeas::validate_repository(root)` MUST return a report with the number of discovered requirements, the number of discovered examples, the number of evidence files, and all validation errors for the supplied project. Ordinary invalid evidence MUST be reported in that report; an inaccessible project root MUST return an I/O error.
:::
Input 11: outline src/evidence.rs fn[inspect_repository_with_progress]
- File:
src/evidence.rs - Selector:
fn[inspect_repository_with_progress] - Kind:
fn src/evidence.rs:185–386
// {impl}`requirements.ci.errors`
// {impl}`requirements.examples.evidence`
// {impl}`requirements.configuration.workspace_location`
// {impl}`requirements.configuration.workspace_structure`
// {impl}`requirements.configuration.loading`
// {impl}`requirements.ci.book_source`
// {impl}`requirements.definitions.declaration`
// {impl}`requirements.references.builtin_definitions`
// {impl}`requirements.ci.determination`
pub(crate) fn inspect_repository_with_progress(
root: &Path,
mut progress: impl FnMut(InspectionProgress),
) -> io::Result<RepositoryInspection> {
let root = fs::canonicalize(root)?;
progress(InspectionProgress {
stage: "discovering requirements",
completed: 0,
total: None,
});
let mut errors = Vec::new();
if let Err(error) = crate::config::load_workspace_evidence(&root) {
errors.push(error.to_string());
}
let md_root = book_source_dir(&root, &mut errors);
let definitions = collect_definitions(&root, &md_root, &mut errors);
let mut discovery_errors = errors.clone();
// {impl}`requirements.test-coverage.setup.validation`
// {impl}`requirements.test-coverage.setup.validation.static`
if let Err(error) = crate::execution_coverage::validate_setup(&root) {
errors.push(error.to_string());
}
// Only the coverage report uses `[coverage]`, so an invalid table is a
// finding but not a discovery failure, and authoring still proceeds.
if let Some(error) = crate::config::coverage_error(&root) {
errors.push(error.to_string());
}
let evidence_root = root.join("evidence");
let listing_errors = errors.len();
let evidence_files = if evidence_root.is_dir() {
files_with_extension(&root, &evidence_root, "json", &mut errors)
} else {
Vec::new()
};
let evidence_listed = errors.len() == listing_errors;
let mut present = BTreeSet::new();
let outlines = OutlineCache::default();
// Citation reviews are validated against their source items below.
let (review_files, ordinary_files): (Vec<_>, Vec<_>) = evidence_files
.iter()
.partition(|file| crate::citations::is_review_path(&evidence_root, file));
let review_files: Vec<PathBuf> = review_files.into_iter().cloned().collect();
// Site reviews are validated against the sites of their requirements.
// {impl}`requirements.ci.orphans`
let (site_files, ordinary_files): (Vec<_>, Vec<_>) = ordinary_files
.into_iter()
.partition(|file| crate::sites::is_review_path(&evidence_root, file));
let site_files: Vec<PathBuf> = site_files.into_iter().cloned().collect();
// {impl}`requirements.ci.orphans`
for (completed, file) in ordinary_files.iter().enumerate() {
progress(InspectionProgress {
stage: "evidence files",
completed,
total: Some(ordinary_files.len()),
});
let relative = file
.strip_prefix(&evidence_root)
.expect("evidence file is inside evidence directory");
let label = display_path(&root, file);
let name = if relative.components().count() == 1 {
relative
.file_name()
.and_then(|part| part.to_str())
.and_then(|part| part.strip_suffix(".json"))
} else {
None
};
let expected = name
.and_then(|name| definitions.get(name))
.filter(|d| d.kind != DefinitionKind::Term);
if let Some(name) = name.filter(|_| expected.is_some()) {
present.insert(name.to_owned());
} else {
errors.push(format!("{label}: no matching requirement or example"));
}
validate_evidence_file(&root, file, expected, &definitions, &outlines, &mut errors);
}
progress(InspectionProgress {
stage: "evidence files",
completed: ordinary_files.len(),
total: Some(ordinary_files.len()),
});
// {impl}`requirements.ci.coverage`
// Missing evidence is reported as a validation error; inspection never
// starts authoring.
// {impl}`requirements.authoring.deterministic_validation`
for (name, definition) in &definitions {
if definition.kind != DefinitionKind::Term && !present.contains(name) {
errors.push(format!(
"evidence/{name}.json: missing for {} at {}",
definition.kind.noun(),
definition.source
));
}
}
// Unreadable reference sources are discovery failures: a batch must not
// treat a partial scan as complete.
let scanned = errors.len();
progress(InspectionProgress {
stage: "discovering source references",
completed: 0,
total: None,
});
let files = discovered_files(&root, &mut errors);
let references = collect_references_with_progress(&root, &files, &mut errors, &mut progress);
discovery_errors.extend(errors[scanned..].iter().cloned());
validate_committed_credentials(&root, &mut errors);
// {impl}`requirements.references.distributed`
let sites = crate::sites::discover(
&root,
&definitions,
&files,
&outlines,
&mut errors,
&mut discovery_errors,
);
validate_references(
&root,
&definitions,
&references,
&sites,
&outlines,
&mut errors,
&mut progress,
);
crate::citations::validate(
&root,
&definitions,
&references,
&outlines,
&review_files,
&mut errors,
&mut progress,
);
crate::sites::validate(
&root,
&definitions,
&references,
&sites,
&outlines,
&site_files,
&mut errors,
&mut progress,
);
crate::rust_coverage::validate_cargo_examples(
&root,
&files,
&definitions,
&references,
&mut errors,
);
// An item an evidence record or review read is covered.
// {impl}`requirements.references.rust_item_coverage`
let reads = crate::rust_coverage::EvidenceReads::load(&evidence_files);
let uncovered = crate::rust_coverage::validate_rust_functions(
&root,
&files,
&definitions,
&reads,
&mut errors,
&mut discovery_errors,
&mut progress,
);
let examples = definitions
.values()
.filter(|definition| definition.kind == DefinitionKind::Example)
.count();
let requirements = definitions
.values()
.filter(|definition| definition.kind == DefinitionKind::Requirement)
.count();
Ok(RepositoryInspection {
root: root.clone(),
report: EvidenceReport {
requirements,
examples,
evidence_files: evidence_files.len(),
errors,
},
definitions,
references,
sites,
uncovered,
evidence_files,
evidence_listed,
discovery_errors,
})
}