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.index.chapter.default

Requirements index · View definition

evidence Valid

Requirement

When a book contains no standalone {requirements-index} directive, habeas mdbook MUST append a new top-level chapter titled “Requirements index” at requirements-index.md, containing the index table, even when the book defines no requirements or examples. The generated chapter MUST have no source file or edit target. Its section number MUST be one greater than the largest numbered top-level chapter, or 1 when no top-level chapter is numbered.

Rationale

The tests adequately cover requirements.index.chapter.default. I judged this from the supplied tests, and I read the implementation only to check how the number is computed. That check is src/index.rs#impl[DetailPlan]/fn[populate], which takes the maximum numbered top-level chapter number and adds 1.

Obligations and the tests that cover them

  • Append a top-level chapter titled “Requirements index” at requirements-index.md when there is no standalone marker.
    • definitions_without_a_marker_get_a_default_index_and_detail_pages checks the name, the path, that it is the last item in book.items, that parent_names is empty, and that the content no longer contains {requirements-index}.
    • mdbook_preprocessor_renders_definitions_between_stdin_and_stdout in tests/repository.rs checks the same name and path through the real habeas mdbook binary over stdin and stdout.
    • default_index_exists_even_without_definitions_or_numbered_chapters runs the case of a book with no chapters and the case of a book whose only chapter is prose.
  • Create the chapter even when the book has no requirements or examples. default_index_exists_even_without_definitions_or_numbered_chapters asserts the chapter exists. It also asserts the content starts with # Requirements index and contains the | Definition | Evidence | table header, which shows the index table is there.
  • A marker that is not standalone does not suppress the default. The same test puts :::{requirements-index} inside a code fence. It still expects the default chapter and leaves the original intro content unchanged.
  • The marker-present branch. index_owns_details_in_book_order_with_badge_icons has an explicit marker and asserts that book.items.len() stays 3. No default chapter is appended there. That test is not marked for this subject, but it does cover the negative side of the condition.
  • No source file or edit target. Every default-chapter test asserts index.source_path.is_none(). Two tests also assert that no md/requirements-index.md file is written to disk.
  • Section number is one more than the largest numbered top-level chapter, or 1 if none is numbered.
    • With no numbered chapters, in both variants of default_index_exists_even_without_definitions_or_numbered_chapters, the number is [1]. The prose variant covers an unnumbered intro.
    • With one numbered chapter, definitions_without_a_marker_get_a_default_index_and_detail_pages expects [3] after a top-level chapter numbered [2].
    • default_index_number_follows_top_level_chapters_across_parts_and_unnumbered_chapters has a part title, a chapter numbered [4] with a child numbered [4,10], a separator, and an unnumbered appendix. It expects [5]. That fixture rules out three wrong behaviours: using the nested child’s number, counting chapters, and taking the number of the last item.

Remaining observations

  • No test has several numbered top-level chapters in non-sequential order, so “largest” is not told apart from “last numbered”. Mdbook numbers top-level chapters sequentially, so I do not count this as a gap.
  • I found no unacknowledged gaps, and the acknowledgment list is empty.

Inputs

Implementation

Input 6: outline src/index.rs impl[DetailPlan]/fn[populate]
    // {impl}`requirements.index.state`
    // {impl}`requirements.examples.index`
    // {impl}`requirements.index.chapter`
    // {impl}`requirements.index.chapter.default`
    // {impl}`requirements.index.detail_pages`
    pub(crate) fn populate(
        &self,
        book: &mut Book,
        root: &Path,
        definitions: &BTreeMap<String, Definition>,
    ) -> io::Result<()> {
        let config = Config::from_disk(root.join("book.toml")).map_err(io::Error::other)?;
        let source_links = SourceLinks::from_config(&config)?;
        let inspection = inspect_repository(root)?;
        let report = &inspection.report;
        let outlines = OutlineCache::default();
        let sources = RenderSources {
            root,
            definitions: &inspection.definitions,
            references: &inspection.references,
            source_links: source_links.as_ref(),
            outlines: &outlines,
        };
        let mut rows = Vec::new();
        let mut pages = BTreeMap::new();
        for (name, detail_path) in &self.detail_paths {
            let evidence_path = root.join("evidence").join(format!("{name}.json"));
            let evidence = LoadedDetailEvidence::load(root, name, report);
            let definition = definitions
                .get(name)
                .expect("every detail page has a definition");
            let detail_href = chapter_href(&self.index_path, detail_path, None);
            rows.push((
                format!("[`{name}`]({detail_href}) ({})", definition.kind.noun()),
                evidence.state().label(),
            ));
            let content = render_detail_page(
                name,
                detail_path,
                Some(&self.index_path),
                definition,
                evidence.borrowed(),
                &sources,
            );
            // {impl}`requirements.index.source_links`
            let source_path = if evidence_path.exists() {
                evidence_edit_path(&config.book.src, name)
            } else {
                definition.path.clone()
            };
            pages.insert(name.clone(), (detail_path.clone(), content, source_path));
        }

        // {impl}`requirements.cli.shared_status_rendering`
        let rows = render_evidence_table(&rows);

        if self.generated_index {
            let number = book
                .items
                .iter()
                .filter_map(|item| match item {
                    BookItem::Chapter(chapter) => chapter.number.as_ref()?.first().copied(),
                    _ => None,
                })
                .max()
                .unwrap_or(0)
                + 1;
            let mut chapter = Chapter::new(
                "Requirements index",
                "# Requirements index\n\n:::{requirements-index}\n:::\n".to_owned(),
                &self.index_path,
                Vec::new(),
            );
            chapter.source_path = None;
            chapter.number = Some(SectionNumber::new(vec![number]));
            book.push_item(chapter);
        }

        // {impl}`requirements.index.navigation`
        let mut index_found = false;
        let mut chapters_found = 0;
        book.for_each_chapter_mut(|chapter| {
            let Some(path) = chapter.path.clone() else {
                return;
            };
            if self.index_path == path {
                index_found = true;
                let ranges = marker_ranges(&chapter.content)
                    .expect("the index directive was checked before the book was changed");
                let range = ranges
                    .into_iter()
                    .next()
                    .expect("the planned index directive is still present");
                chapter.content.replace_range(range, &rows);
            }
            let Some((_, names)) = self.chapters.iter().find(|(chapter, _)| *chapter == path)
            else {
                return;
            };
            chapters_found += 1;
            let mut parent_names = chapter.parent_names.clone();
            parent_names.push(chapter.name.clone());
            let first_number = chapter
                .sub_items
                .iter()
                .filter_map(|item| match item {
                    BookItem::Chapter(child) => child.number.as_ref()?.last().copied(),
                    _ => None,
                })
                .max()
                .unwrap_or(0)
                + 1;
            for (offset, name) in names.iter().enumerate() {
                let (path, content, source_path) = &pages[name];
                let mut page = Chapter::new(name, content.clone(), path, parent_names.clone());
                page.source_path = Some(source_path.clone());
                page.number = chapter.number.as_ref().map(|number| {
                    let mut number = number.to_vec();
                    number.push(first_number + offset as u32);
                    SectionNumber::new(number)
                });
                chapter.sub_items.push(BookItem::Chapter(page));
            }
        });
        if !index_found {
            return Err(invalid_index("the requirements index chapter disappeared"));
        }
        if chapters_found != self.chapters.len() {
            return Err(invalid_index("the requirements index chapter disappeared"));
        }
        Ok(())
    }

Tests

Input 2: outline src/lib.rs mod[tests]/fn[definitions_without_a_marker_get_a_default_index_and_detail_pages]
  • File: src/lib.rs
  • Selector: mod[tests]/fn[definitions_without_a_marker_get_a_default_index_and_detail_pages]
  • Kind: fn
  • src/lib.rs:1050–1185
    // {test}`requirements.index.detail_pages`
    // {test}`requirements.index.chapter`
    // {test}`requirements.index.chapter.default`
    // {test}`requirements.index.navigation`
    // {test}`requirements.examples.index`
    // {test}`requirements.test-coverage.index`
    // {test}`requirements.references.anchors`
    #[test]
    fn definitions_without_a_marker_get_a_default_index_and_detail_pages() {
        let mut book = Book::new();
        let mut chapter = Chapter::new(
            "Rules",
            "# Rules\n\n:::{req} zeta\n:impl: notes.txt\nZeta.\n:::\n\n:::{example} alpha\nAlpha case. {cite}`rules.zeta`\n:::\n\n:::{req} cli.mdbook\nMdbook.\n:::\n".to_owned(),
            "rules.md",
            Vec::new(),
        );
        chapter.number = Some(mdbook_preprocessor::book::SectionNumber::new(vec![2]));
        chapter.sub_items.push(BookItem::Chapter(Chapter::new(
            "Child",
            ":::{req} nested\nNested.\n:::\n".to_owned(),
            "rules/child.md",
            vec!["Rules".to_owned()],
        )));
        book.push_item(chapter);
        let root = book_root();
        preprocess_book(&mut book, root.path()).unwrap();

        let rules = book.chapters().next().unwrap();
        let pages = rules
            .sub_items
            .iter()
            .filter_map(|item| match item {
                BookItem::Chapter(chapter) => Some(chapter),
                _ => None,
            })
            .collect::<Vec<_>>();
        assert_eq!(pages.len(), 1);
        assert_eq!(pages[0].name, "Child");
        assert_eq!(book.items.len(), 2);
        assert_eq!(book.chapters().count(), 8);
        assert!(rules.content.contains("habeas-detail-icon"));
        assert!(!rules.content.contains("See evidence"));
        assert!(!rules.content.contains("notes.txt"));
        for (kind, name) in [("req", "zeta"), ("example", "alpha"), ("req", "cli.mdbook")] {
            assert!(rules.content.contains(&format!(
                "id=\"habeas-{kind}-rules.{name}\" href=\"#habeas-{kind}-rules.{}\"",
                name.replace(".md", "%2Emd")
            )));
        }
        assert!(
            rules
                .content
                .contains("href=\"requirements-index/rules.cli%2Emdbook.html\"")
        );
        assert!(
            pages[0]
                .content
                .contains("href=\"../requirements-index/rules.child.nested.html\"")
        );
        let BookItem::Chapter(index) = book.items.last().unwrap() else {
            panic!("the default index must be a top-level chapter");
        };
        assert_eq!(index.name, "Requirements index");
        assert_eq!(
            index.path.as_deref(),
            Some(Path::new("requirements-index.md"))
        );
        assert!(index.source_path.is_none());
        assert!(index.parent_names.is_empty());
        assert_eq!(index.number.as_deref().map(Vec::as_slice), Some(&[3][..]));
        assert!(!index.content.contains("{requirements-index}"));
        assert!(index.content.contains("(requirement)"));
        assert!(index.content.contains("(example)"));
        assert!(index.content.contains("Missing"));
        let coverage = index
            .sub_items
            .iter()
            .filter_map(|item| match item {
                BookItem::Chapter(chapter) if chapter.name == "Coverage gaps" => Some(chapter),
                _ => None,
            })
            .collect::<Vec<_>>();
        assert_eq!(coverage.len(), 1);
        assert_eq!(
            coverage[0].path.as_deref(),
            Some(Path::new("requirements-index/coverage.md"))
        );
        assert_eq!(coverage[0].parent_names, ["Requirements index"]);
        assert!(
            index
                .content
                .contains("[Coverage gaps](requirements-index/coverage.html)")
        );
        let details = index
            .sub_items
            .iter()
            .filter_map(|item| match item {
                BookItem::Chapter(chapter) if chapter.name != "Coverage gaps" => Some(chapter),
                _ => None,
            })
            .collect::<Vec<_>>();
        assert_eq!(
            details
                .iter()
                .map(|page| page.name.as_str())
                .collect::<Vec<_>>(),
            [
                "rules.zeta",
                "rules.alpha",
                "rules.cli.mdbook",
                "rules.child.nested"
            ]
        );
        for (offset, page) in details.iter().enumerate() {
            assert_eq!(page.parent_names, ["Requirements index"]);
            assert_eq!(
                page.number.as_deref().map(Vec::as_slice),
                Some(&[3, offset as u32 + 2][..])
            );
            assert!(
                page.content
                    .contains("[Requirements index](../requirements-index.html)")
            );
        }
        assert!(
            details[2]
                .content
                .contains("[View definition](../rules.html#habeas-req-rules.cli%2Emdbook)")
        );
        assert!(
            details[3]
                .content
                .contains("[View definition](../rules/child.html#habeas-req-rules.child.nested)")
        );
        assert!(!root.path().join("md/requirements-index.md").exists());
    }
Input 3: outline src/lib.rs mod[tests]/fn[default_index_exists_even_without_definitions_or_numbered_chapters]
  • File: src/lib.rs
  • Selector: mod[tests]/fn[default_index_exists_even_without_definitions_or_numbered_chapters]
  • Kind: fn
  • src/lib.rs:1187–1235
    // {test}`requirements.index.chapter`
    // {test}`requirements.index.chapter.default`
    // {test}`requirements.index.detail_pages`
    #[test]
    fn default_index_exists_even_without_definitions_or_numbered_chapters() {
        for with_prose in [false, true] {
            let mut book = Book::new();
            let prose = "An index marker in a code block is literal.\n\n```text\n:::{requirements-index}\n:::\n```\n";
            if with_prose {
                book.push_item(Chapter::new(
                    "Introduction",
                    prose.into(),
                    "intro.md",
                    vec![],
                ));
            }
            let root = book_root();
            preprocess_book(&mut book, root.path()).unwrap();
            assert_eq!(book.items.len(), usize::from(with_prose) + 1);
            if with_prose {
                let BookItem::Chapter(intro) = &book.items[0] else {
                    panic!("the original introduction must remain a chapter");
                };
                assert_eq!(intro.content, prose);
                assert!(intro.number.is_none());
            }
            let BookItem::Chapter(index) = book.items.last().unwrap() else {
                panic!("the default index must be appended");
            };
            assert_eq!(index.name, "Requirements index");
            assert_eq!(
                index.path.as_deref(),
                Some(Path::new("requirements-index.md"))
            );
            assert_eq!(index.number.as_deref().map(Vec::as_slice), Some(&[1][..]));
            assert!(index.source_path.is_none());
            assert_eq!(index.sub_items.len(), 1);
            let BookItem::Chapter(coverage) = &index.sub_items[0] else {
                unreachable!()
            };
            assert_eq!(coverage.name, "Coverage gaps");
            assert!(coverage.source_path.is_none());
            assert!(index.parent_names.is_empty());
            assert!(index.content.starts_with("# Requirements index\n\n"));
            assert!(index.content.contains("| Definition | Evidence |"));
            assert!(!index.content.contains("{requirements-index}"));
            assert!(!root.path().join("md/requirements-index.md").exists());
        }
    }
Input 4: outline src/lib.rs mod[tests]/fn[default_index_number_follows_top_level_chapters_across_parts_and_unnumbered_chapters]
  • File: src/lib.rs
  • Selector: mod[tests]/fn[default_index_number_follows_top_level_chapters_across_parts_and_unnumbered_chapters]
  • Kind: fn
  • src/lib.rs:1237–1266
    // {test}`requirements.index.chapter.default`
    #[test]
    fn default_index_number_follows_top_level_chapters_across_parts_and_unnumbered_chapters() {
        let mut book = Book::new();
        book.push_item(BookItem::PartTitle("Part".into()));
        let mut chapter = Chapter::new("Chapter", "Text.".into(), "chapter.md", vec![]);
        chapter.number = Some(mdbook_preprocessor::book::SectionNumber::new(vec![4]));
        let mut child = Chapter::new("Child", "Child.".into(), "child.md", vec!["Chapter".into()]);
        child.number = Some(mdbook_preprocessor::book::SectionNumber::new(vec![4, 10]));
        chapter.sub_items.push(BookItem::Chapter(child));
        book.push_item(chapter);
        book.push_item(BookItem::Separator);
        book.push_item(Chapter::new(
            "Appendix",
            "Appendix.".into(),
            "appendix.md",
            vec![],
        ));
        let root = book_root();
        preprocess_book(&mut book, root.path()).unwrap();
        assert_eq!(book.items.len(), 5);
        let BookItem::Chapter(index) = book.items.last().unwrap() else {
            panic!("the default index must follow the appendix");
        };
        assert_eq!(index.number.as_deref().map(Vec::as_slice), Some(&[5][..]));
        assert_eq!(index.sub_items.len(), 1);
        assert!(
            matches!(&index.sub_items[0], BookItem::Chapter(chapter) if chapter.name == "Coverage gaps")
        );
    }
Input 5: outline tests/repository.rs fn[mdbook_preprocessor_renders_definitions_between_stdin_and_stdout]
  • File: tests/repository.rs
  • Selector: fn[mdbook_preprocessor_renders_definitions_between_stdin_and_stdout]
  • Kind: fn
  • tests/repository.rs:160–260
// {test}`requirements.cli.mdbook`
// {test}`requirements.index.chapter.default`
// {test}`requirements.index.detail_pages`
// {test}`requirements.index.navigation`
#[test]
fn mdbook_preprocessor_renders_definitions_between_stdin_and_stdout() {
    let temp = TempDir::new().unwrap();
    let root = temp.path();
    fs::create_dir_all(root.join("md")).unwrap();
    fs::write(root.join("Cargo.toml"), "[package]\nname = \"fixture\"\n").unwrap();
    fs::write(root.join("book.toml"), "[book]\nsrc = \"md\"\n").unwrap();
    let content =
        ":::{req} ready\nReady MUST work.\n:::\n\n:::{req} cites\nSee {cite}`rules.ready`.\n:::\n"
            .to_owned();
    fs::write(root.join("md/rules.md"), &content).unwrap();
    let mut book = Book::new();
    book.push_item(Chapter::new("Rules", content, "rules.md", Vec::new()));
    let context = PreprocessorContext::new(root.to_path_buf(), Config::default(), "html".into());

    let mut child = Command::new(env!("CARGO_BIN_EXE_habeas"))
        .arg("mdbook")
        .current_dir(root)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    child
        .stdin
        .take()
        .unwrap()
        .write_all(&serde_json::to_vec(&(&context, &book)).unwrap())
        .unwrap();
    let output = child.wait_with_output().unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let rendered: Book = serde_json::from_slice(&output.stdout).unwrap();
    let BookItem::Chapter(chapter) = &rendered.items[0] else {
        panic!("{rendered:?}");
    };
    assert!(!chapter.content.contains(":::{req}"), "{}", chapter.content);
    assert!(
        chapter.content.contains("https://img.shields.io/badge/"),
        "{}",
        chapter.content
    );
    assert!(
        chapter.content.contains("cite") && chapter.content.contains("rules.ready"),
        "{}",
        chapter.content
    );
    let badge_rows = chapter
        .content
        .split("<span class=\"habeas-definition-badge\">")
        .skip(1)
        .map(|row| row.split("</span>").next().unwrap())
        .collect::<Vec<_>>();
    assert_eq!(badge_rows.len(), 2, "{}", chapter.content);
    for row in badge_rows {
        assert!(row.contains("<img "), "{row}");
        assert!(row.contains("class=\"habeas-detail-icon\""), "{row}");
        assert_eq!(row.matches("</a>").count(), 2, "{row}");
    }
    assert!(chapter.sub_items.is_empty());
    assert!(
        chapter.content.contains("href=\"#habeas-req-rules.ready\""),
        "{}",
        chapter.content
    );
    assert!(
        chapter
            .content
            .contains("href=\"requirements-index/rules.ready.html\""),
        "{}",
        chapter.content
    );
    assert_eq!(rendered.items.len(), 2);
    let BookItem::Chapter(index) = &rendered.items[1] else {
        panic!("{rendered:?}");
    };
    assert_eq!(index.name, "Requirements index");
    assert_eq!(
        index.path.as_deref(),
        Some(Path::new("requirements-index.md"))
    );
    assert!(index.source_path.is_none());
    assert_eq!(
        index
            .sub_items
            .iter()
            .filter_map(|item| match item {
                BookItem::Chapter(detail) => Some(detail.name.as_str()),
                _ => None,
            })
            .collect::<Vec<_>>(),
        ["Coverage gaps", "rules.ready", "rules.cites"]
    );
}

Other sources

Input 1: requirements selection requirements.index.chapter.default
:::{req} chapter.default
When a book contains no standalone `{requirements-index}` directive, `habeas mdbook` MUST append a new top-level chapter titled "Requirements index" at `requirements-index.md`, containing the index table, even when the book defines no requirements or examples. The generated chapter MUST have no source file or edit target. Its section number MUST be one greater than the largest numbered top-level chapter, or 1 when no top-level chapter is numbered.
:::
Input 7: outline src/lib.rs mod[tests]/fn[index_owns_details_in_book_order_with_badge_icons]
  • File: src/lib.rs
  • Selector: mod[tests]/fn[index_owns_details_in_book_order_with_badge_icons]
  • Kind: fn
  • src/lib.rs:1268–1350
    // {test}`requirements.index.chapter`
    // {test}`requirements.index.detail_pages`
    // {test}`requirements.index.navigation`
    #[test]
    fn index_owns_details_in_book_order_with_badge_icons() {
        let mut book = Book::new();
        book.push_item(Chapter::new(
            "Rules",
            ":::{req} zeta\nZeta.\n:::\n".into(),
            "rules.md",
            vec![],
        ));
        book.push_item(Chapter::new(
            "More",
            ":::{example} cli.mdbook\nExample.\n:::\n".into(),
            "more.md",
            vec![],
        ));
        let mut index = Chapter::new(
            "Index",
            ":::{requirements-index}\n:::\n".into(),
            "appendix/index.md",
            vec![],
        );
        index.number = Some(mdbook_preprocessor::book::SectionNumber::new(vec![3]));
        let mut child = Chapter::new(
            "Existing",
            "Existing.".into(),
            "appendix/existing.md",
            vec!["Index".into()],
        );
        child.number = Some(mdbook_preprocessor::book::SectionNumber::new(vec![3, 1]));
        index.sub_items.push(BookItem::Chapter(child));
        book.push_item(index);
        let root = book_root();
        preprocess_book(&mut book, root.path()).unwrap();
        assert_eq!(
            book.items.len(),
            3,
            "the explicit index keeps its placement"
        );
        let chapters = book.chapters().collect::<Vec<_>>();
        for chapter in &chapters[..2] {
            assert!(chapter.sub_items.is_empty());
            assert!(
                chapter
                    .content
                    .contains("title=\"View evidence\" aria-label=\"View evidence for ")
            );
            assert!(chapter.content.contains("stroke=\"#fff\""));
            assert!(!chapter.content.contains("See evidence"));
        }
        assert!(
            chapters[1]
                .content
                .contains("href=\"appendix/index/more.cli%2Emdbook.html\"")
        );
        let pages = chapters[2]
            .sub_items
            .iter()
            .filter_map(|item| match item {
                BookItem::Chapter(chapter) => Some(chapter),
                _ => None,
            })
            .collect::<Vec<_>>();
        assert_eq!(
            pages
                .iter()
                .map(|page| page.name.as_str())
                .collect::<Vec<_>>(),
            ["Coverage gaps", "Existing", "rules.zeta", "more.cli.mdbook"]
        );
        assert_eq!(pages[3].parent_names, ["Index"]);
        assert_eq!(
            pages[3].number.as_deref().map(Vec::as_slice),
            Some(&[3, 4][..])
        );
        assert!(
            pages[3]
                .content
                .contains("[View definition](../../more.html#habeas-example-more.cli%2Emdbook)")
        );
    }