Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

requirements.ci.book_source

Requirements index · View definition

evidence Valid

Requirement

Validation MUST read the mdBook source directory from [book].src in book.toml, using src when the setting is absent. It MUST report an unreadable or malformed book configuration and reject an empty, absolute, or parent-traversing source path.

Rationale

I found no gaps. Each obligation maps to code in book_source_dir and to the test book_source_defaults_only_when_absent_and_reports_invalid_configuration.

Reachability. book_source_dir in src/evidence.rs carries out every obligation. It has no book_source marker of its own. It is reached from two marked roots: src/evidence.rs#fn[load_definitions] and src/evidence.rs#fn[inspect_repository_with_progress]. Both call it to get the source directory, so it needs no reference of its own.

Obligations

  1. Read the source directory from [book].src in book.toml. book_source_dir parses book.toml, reads book.src as a string, and joins it onto the root.

  2. Use src when the setting is absent. If book or book.src is missing, the source is "src". The test covers an empty file and a [book] table without src. It also covers src = 'docs' and the inline form book = { src = 'docs' }.

  3. Report an unreadable configuration. A read_to_string failure pushes “book.toml: cannot read book configuration”. The test removes the file and asserts that message.

  4. Report a malformed configuration. Three cases push an error:

    • Invalid TOML pushes “invalid TOML”.
    • A non-table book pushes “book must be a table”.
    • A non-string book.src pushes “book.src must be a string”.

    The test covers all three, including src set to an integer, a boolean, an array, and a table.

  5. Reject an empty source path. An empty src pushes “book.src must be a directory inside the repository”. The test uses src = ''.

  6. Reject an absolute source path. The code accepts only Normal and CurDir path components, so a root component is an error. The test uses /outside.

  7. Reject a parent-traversing source path. A .. component also fails that check. The test uses ../outside and md/../outside.

Tests. src/evidence.rs#mod[tests]/fn[book_source_defaults_only_when_absent_and_reports_invalid_configuration] calls book_source_dir directly and asserts each case above. validates_full_names_requirement_text_and_input_lines also carries a {test} reference and exercises the whole validation path.

Unspecified behavior. After an error the function falls back to md so later checks still run. That is part of reporting the error, not a separate behavior the text must specify. Other book.toml reads (src/index.rs, src/setup.rs, src/authoring/access.rs) are not validation of the source directory.

Inputs

Implementation

Input 2: outline src/evidence.rs fn[load_definitions]
// {impl}`requirements.authoring.mandatory_inputs`
// {impl}`requirements.ci.book_source`
// {impl}`requirements.ci.definition_errors`
pub(crate) fn load_definitions(root: &Path) -> io::Result<BTreeMap<String, Declaration>> {
    let root = fs::canonicalize(root)?;
    // Any failure aborts, so this is not a validation site.
    let mut failures = Vec::new();
    let md_root = book_source_dir(&root, &mut failures);
    let definitions = collect_definitions(&root, &md_root, &mut failures);
    if failures.is_empty() {
        Ok(definitions)
    } else {
        Err(io::Error::new(
            io::ErrorKind::InvalidData,
            failures.join("\n"),
        ))
    }
}
Input 3: outline src/evidence.rs fn[inspect_repository_with_progress]
// {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,
    })
}

Tests

Input 4: outline src/evidence.rs mod[tests]/fn[book_source_defaults_only_when_absent_and_reports_invalid_configuration]
  • File: src/evidence.rs
  • Selector: mod[tests]/fn[book_source_defaults_only_when_absent_and_reports_invalid_configuration]
  • Kind: fn
  • src/evidence.rs:2479–2531
    // {test}`requirements.ci.book_source`
    // {test}`requirements.configuration.loading`
    #[test]
    fn book_source_defaults_only_when_absent_and_reports_invalid_configuration() {
        let temp = TempDir::new().unwrap();
        let root = temp.path();
        let path = root.join("book.toml");
        for (configuration, expected) in [
            ("", "src"),
            ("[book]\ntitle = 'Example'\n", "src"),
            ("[book]\nsrc = 'docs'\n", "docs"),
            ("book = { src = 'docs' }\n", "docs"),
        ] {
            fs::write(&path, configuration).unwrap();
            let mut errors = Vec::new();
            assert_eq!(
                super::book_source_dir(root, &mut errors),
                root.join(expected)
            );
            assert!(errors.is_empty(), "{errors:?}");
        }
        fs::remove_file(&path).unwrap();
        let mut errors = Vec::new();
        super::book_source_dir(root, &mut errors);
        assert!(
            errors
                .iter()
                .any(|error| error.contains("book.toml: cannot read book configuration"))
        );
        for (configuration, expected) in [
            ("[book", "invalid TOML"),
            ("book = 'wrong'", "book must be a table"),
            ("[book]\nsrc = 7", "book.src must be a string"),
            ("[book]\nsrc = false", "book.src must be a string"),
            ("[book]\nsrc = []", "book.src must be a string"),
            ("[book.src]", "book.src must be a string"),
            ("[book]\nsrc = ''", "book.src must be a directory"),
            ("[book]\nsrc = '/outside'", "book.src must be a directory"),
            ("[book]\nsrc = '../outside'", "book.src must be a directory"),
            (
                "[book]\nsrc = 'md/../outside'",
                "book.src must be a directory",
            ),
        ] {
            fs::write(&path, configuration).unwrap();
            let mut errors = Vec::new();
            super::book_source_dir(root, &mut errors);
            assert!(
                errors.iter().any(|error| error.contains(expected)),
                "{configuration:?}: {errors:?}"
            );
        }
    }
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);
    }

Other sources

Input 1: requirements selection requirements.ci.book_source
:::{req} book_source
Validation MUST read the mdBook source directory from `[book].src` in `book.toml`, using `src` when the setting is absent. It MUST report an unreadable or malformed book configuration and reject an empty, absolute, or parent-traversing source path.
:::
Input 6: outline src/evidence.rs fn[book_source_dir]
// {impl}`requirements.configuration.loading`
// A malformed `book.toml` is one failed check: fall back to `md` so
// definition collection and the checks after it still run.
// {impl}`requirements.ci.errors`
pub(crate) fn book_source_dir(root: &Path, errors: &mut Vec<String>) -> PathBuf {
    let path = root.join("book.toml");
    let source = match fs::read_to_string(&path) {
        Ok(content) => match content.parse::<DocumentMut>() {
            Ok(book) => {
                let table = match book.get("book") {
                    Some(item) => match item.as_table_like() {
                        Some(table) => Some(table),
                        None => {
                            errors.push("book.toml: book must be a table".to_owned());
                            return root.join("md");
                        }
                    },
                    None => None,
                };
                match table.and_then(|table| table.get("src")) {
                    Some(item) => match item.as_str() {
                        Some(source) => source.to_owned(),
                        None => {
                            errors.push("book.toml: book.src must be a string".to_owned());
                            return root.join("md");
                        }
                    },
                    None => "src".to_owned(),
                }
            }
            Err(error) => {
                errors.push(format!("book.toml: invalid TOML: {error}"));
                return root.join("md");
            }
        },
        Err(error) => {
            errors.push(format!(
                "book.toml: cannot read book configuration: {error}"
            ));
            return root.join("md");
        }
    };
    let relative = Path::new(&source);
    if source.is_empty()
        || !relative
            .components()
            .all(|part| matches!(part, Component::Normal(_) | Component::CurDir))
    {
        errors.push("book.toml: book.src must be a directory inside the repository".to_owned());
        return root.join("md");
    }
    root.join(relative)
}