requirements.index.source_links
Requirements index · View definition
Requirement
When
output.html.git-repository-urlnames a GitHub repository andoutput.html.edit-url-templateuses that repository’s/edit/<branch>/{path}form, each safely resolved source location displayed for an evidence input MUST link its repository-relative file and inclusive line range to/blob/<branch>/<file>#L<start>-L<end>. A source location MUST remain plain text when a safe URL cannot be derived. A generated detail page MUST use its evidence JSON file as the mdBook edit target when the file exists, or its requirement chapter when the evidence file is missing.
Rationale
The reviewed tests cover each obligation of requirements.index.source_links.
Link derivation when the repository and template match. src/index.rs#mod[tests]/fn[source_links_use_configured_repository_and_branch] builds SourceLinks from a config whose git-repository-url is a GitHub repository and whose edit-url-template uses /edit/release/{path}. It asserts that input_url("src/evidence.rs", 26, 37) returns …/blob/release/src/evidence.rs#L26-L37. That checks the /blob/<branch>/<file>#L<start>-L<end> form and that the branch comes from the template. It also asserts that a path with a space and # is percent-encoded.
Display in a detail page. The same test renders a detail page through render_detail_page, using a real outline input and source_links: Some(&links). It asserts that the page contains <a href="…#L26-L37"><code>src/evidence.rs:26–37</code></a>. That shows the inclusive line range is linked in the displayed location.
Plain text when a safe URL cannot be derived.
- The test asserts
input_urlisNonefor../outside.rsand for a start line of 0. - It asserts that
from_configreturnsNonewhen the template names a different repository (other/project). - It asserts that
from_configreturnsNonefor ajavascript:repository URL and template. - Rendering without links produces plain
<code>file:start–end</code>.src/index.rs#mod[tests]/fn[detail_page_shows_recorded_text_locations_and_first_matching_group]and the other detail-page tests that passsource_links: Noneassert this exact plain form, for example- <code>rules.base</code>: <code>md/rules.md:5–7</code>.render_source_locationfalls back to plain text wheneverinput_urlreturnsNone.
Edit target for a generated detail page.
src/index.rs#mod[tests]/fn[index_shows_evidence_states_and_links_generated_chapters]checks thereadypage, whose evidence JSON exists. It assertssource_path == ../evidence/requirements.core.ready.json.- The same test checks the
absentpage, whose evidence file is missing. It assertssource_path == requirements/core.md, the requirement chapter. source_links_use_configured_repository_and_branchalso assertsevidence_edit_pathfor a nested book source directory (docs/mdgives../../evidence/….json).
Minor untested paths. I did not count these as gaps:
- Wiring
from_configintoDetailPlan::populateis a plain pass-through of the config value. - Requirement and definition input locations go through the same
render_source_locationfunction as the outline input that is tested. - Other malformed-template variants fall under the same “cannot derive a safe URL” outcome that the tests already assert.
The requirement is covered, and no {fixme} acknowledgments are needed.
Inputs
Implementation
Input 5: outline src/index.rs impl[SourceLinks]
- File:
src/index.rs - Selector:
impl[SourceLinks] - Kind:
impl src/index.rs:46–111
impl SourceLinks {
// {impl}`requirements.index.source_links`
fn from_config(config: &Config) -> io::Result<Option<Self>> {
let repository = config
.get::<String>("output.html.git-repository-url")
.map_err(io::Error::other)?;
let edit_template = config
.get::<String>("output.html.edit-url-template")
.map_err(io::Error::other)?;
let (Some(repository), Some(edit_template)) = (repository, edit_template) else {
return Ok(None);
};
let repository = repository.trim_end_matches('/');
let Some(repository_path) = repository.strip_prefix("https://github.com/") else {
return Ok(None);
};
let mut parts = repository_path.split('/');
let (Some(owner), Some(project), None) = (parts.next(), parts.next(), parts.next()) else {
return Ok(None);
};
if owner.is_empty()
|| project.is_empty()
|| !owner
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
|| !project
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_'))
{
return Ok(None);
}
let Some(branch) = edit_template
.strip_prefix(&format!("{repository}/edit/"))
.and_then(|suffix| suffix.strip_suffix("/{path}"))
.filter(|branch| !branch.is_empty())
else {
return Ok(None);
};
Ok(Some(Self {
blob_prefix: format!("{repository}/blob/{branch}"),
}))
}
// {impl}`requirements.index.source_links`
fn input_url(&self, file: &str, start: u64, end: u64) -> Option<String> {
if start == 0 || end < start {
return None;
}
let mut segments = Vec::new();
for component in Path::new(file).components() {
match component {
Component::Normal(segment) => segments.push(encode_url_segment(segment.to_str()?)),
Component::CurDir => {}
_ => return None,
}
}
if segments.is_empty() {
return None;
}
Some(format!(
"{}/{}#L{start}-L{end}",
self.blob_prefix,
segments.join("/")
))
}
}
Input 6: outline src/index.rs fn[render_source_location]
- File:
src/index.rs - Selector:
fn[render_source_location] - Kind:
fn src/index.rs:929–957
// {impl}`requirements.index.source_links`
// {impl}`requirements.index.detail_format`
fn render_source_location(
content: &mut String,
range: &SourceRange,
source_links: Option<&SourceLinks>,
) {
let location = format!("{}:{}–{}", range.file, range.line_start, range.line_end);
let url = source_links.and_then(|links| {
links.input_url(&range.file, range.line_start as u64, range.line_end as u64)
});
content.push_str("- ");
if let Some(name) = &range.name {
content.push_str("<code>");
content.push_str(&escape_html(name));
content.push_str("</code>: ");
}
if let Some(url) = url {
content.push_str("<a href=\"");
content.push_str(&escape_html(&url));
content.push_str("\"><code>");
content.push_str(&escape_html(&location));
content.push_str("</code></a>\n");
} else {
content.push_str("<code>");
content.push_str(&escape_html(&location));
content.push_str("</code>\n");
}
}
Input 7: outline src/index.rs impl[DetailPlan]/fn[populate]
- File:
src/index.rs - Selector:
impl[DetailPlan]/fn[populate] - Kind:
fn src/index.rs:361–492
// {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(())
}
Input 8: outline src/index.rs fn[render_input]
- File:
src/index.rs - Selector:
fn[render_input] - Kind:
fn src/index.rs:842–927
// {impl}`requirements.index.source_links`
// {impl}`requirements.index.detail_format`
// {impl}`requirements.definitions.inputs`
// {impl}`requirements.ci.outline_inputs`
fn render_input(
content: &mut String,
index: usize,
input: &Value,
location: &InputLocation,
sources: &RenderSources<'_>,
) {
content.push_str(&format!(
"<details class=\"habeas-input\">\n<summary id=\"habeas-input-{index}\"><strong>Input {index}</strong>"
));
if let Some(selector) = &location.selector {
let label = match selector {
InputSelector::Outline { file, item } if item.is_empty() => {
format!("outline {file} (whole file)")
}
InputSelector::Outline { file, item } => format!("outline {file} {item}"),
InputSelector::Definition { definition } => format!("definition {definition}"),
InputSelector::Requirements { requirements } => {
format!("requirements selection {requirements}")
}
};
content.push_str(": <code>");
content.push_str(&escape_html(&label));
content.push_str("</code>");
}
content.push_str("</summary>\n\n");
match &location.resolved {
Some(Ok(resolved)) => {
if let (Some(InputSelector::Outline { file, item }), Some(node)) =
(&location.selector, &resolved.node)
{
content.push_str(&format!(
"- File: <code>{}</code>\n- Selector: <code>{}</code>\n- Kind: <code>{}</code>\n",
escape_html(file),
escape_html(if item.is_empty() { "(root)" } else { item }),
escape_html(node.kind)
));
}
for range in &resolved.ranges {
render_source_location(content, range, sources.source_links);
}
content.push('\n');
if let Some(node) = &resolved.node {
if input.get("hash").and_then(Value::as_str) != Some(node.hash.as_str()) {
content.push_str(
"**The recorded hash no longer matches this source; the input is stale.**\n\n",
);
}
let file = match &location.selector {
Some(InputSelector::Outline { file, .. }) => Some(file.as_str()),
_ => None,
};
push_code_block(content, &resolved.text.join("\n"), code_language(file));
content.push_str("\n</details>\n\n");
return;
}
}
Some(Err(error)) => {
content.push_str(&format!("Unresolved selector: {}\n\n", escape_html(error)));
}
None => {}
}
if let Some(lines) = input
.get("text")
.and_then(Value::as_array)
.and_then(|lines| lines.iter().map(Value::as_str).collect::<Option<Vec<_>>>())
{
let file = match &location.selector {
Some(InputSelector::Requirements { .. } | InputSelector::Definition { .. }) => {
Some("requirements.md")
}
_ => None,
};
let text = crate::redaction::redact_text(&lines.join("\n")).into_owned();
push_code_block(content, &text, code_language(file));
} else {
let raw = serde_json::to_string_pretty(input).expect("JSON values can be serialized");
push_code_block(content, &crate::redaction::redact_text(&raw), "json");
}
content.push_str("\n</details>\n\n");
}
Tests
Input 2: outline src/index.rs mod[tests]/fn[index_shows_evidence_states_and_links_generated_chapters]
- File:
src/index.rs - Selector:
mod[tests]/fn[index_shows_evidence_states_and_links_generated_chapters] - Kind:
fn src/index.rs:1101–1306
// {test}`requirements.index.chapter`
// {test}`requirements.index.state`
// {test}`requirements.index.navigation`
// {test}`requirements.index.source_links`
// {test}`requirements.cli.shared_status_rendering`
// {test}`requirements.index.detail_format`
// {test}`requirements.index.invalid_detail`
// {test}`requirements.test-coverage.index`
// {test}`requirements.index.detail_pages`
#[test]
fn index_shows_evidence_states_and_links_generated_chapters() {
let temp = TempDir::new().unwrap();
fs::create_dir_all(temp.path().join("md/requirements")).unwrap();
fs::create_dir_all(temp.path().join("evidence")).unwrap();
fs::create_dir_all(temp.path().join("src")).unwrap();
fs::write(temp.path().join("book.toml"), "[book]\nsrc = \"md\"\n").unwrap();
let requirements = [
("ready", "Ready MUST work."),
("pending", "Pending MUST work."),
("changed", "Changed MUST work."),
("absent", "Absent MUST work."),
("uncovered", "Uncovered MUST work."),
];
let mut source = String::from("# Requirements\n\n");
for (name, body) in requirements {
source.push_str(&format!(":::{{req}} {name}\n{body}\n:::\n\n"));
}
fs::write(temp.path().join("md/requirements/core.md"), &source).unwrap();
fs::write(
temp.path().join("src/main.rs"),
"// {test}`requirements.core.uncovered`\n",
)
.unwrap();
for (name, body, determination) in [
("ready", "Ready MUST work.", true),
("pending", "Pending MUST work.", false),
("changed", "Old requirement.", true),
("uncovered", "Uncovered MUST work.", true),
] {
fs::write(
temp.path()
.join(format!("evidence/requirements.core.{name}.json")),
json!({
"requirement": body,
"determination": determination,
"rationale": "The fixture records the evidence state.",
"inputs": []
})
.to_string(),
)
.unwrap();
}
let mut book = Book::new();
let mut definition_chapter =
Chapter::new("Requirements", source, "requirements/core.md", Vec::new());
definition_chapter.number = Some(SectionNumber::new(vec![3]));
book.push_item(definition_chapter);
let mut index_chapter = Chapter::new(
"Requirements index",
"# Requirements index\n\n:::{requirements-index}\n:::\n".to_owned(),
"appendix/requirements-index.md",
Vec::new(),
);
index_chapter.number = Some(SectionNumber::new(vec![4]));
book.push_item(index_chapter);
crate::evidence::tests::stamp_reference_sets(temp.path());
preprocess_book(&mut book, temp.path()).unwrap();
let definition = book.chapters().next().unwrap();
assert!(definition.content.contains(
"id=\"habeas-req-requirements.core.ready\" href=\"#habeas-req-requirements.core.ready\""
));
let index = book
.chapters()
.find(|chapter| chapter.name == "Requirements index")
.unwrap();
assert!(!index.content.contains("{requirements-index}"));
for (name, state) in [
("ready", "Valid"),
("pending", "Determination false"),
("changed", "Invalid"),
("absent", "Missing"),
("uncovered", "Invalid"),
] {
let link = format!(
"| [`requirements.core.{name}`](requirements-index/requirements.core.{name}.html)"
);
let row = index
.content
.lines()
.find(|line| line.starts_with(&link))
.unwrap_or_else(|| panic!("missing {link} in:\n{}", index.content));
assert_eq!(row.split('|').nth(2).unwrap().trim(), state);
}
let table = index
.content
.lines()
.skip_while(|line| !line.starts_with("| "))
.take_while(|line| line.starts_with("| "))
.collect::<Vec<_>>();
let pipes = table[0]
.match_indices('|')
.map(|(position, _)| position)
.collect::<Vec<_>>();
assert_eq!(pipes.len(), 3);
assert!(table.iter().all(|line| {
line.match_indices('|')
.map(|(position, _)| position)
.collect::<Vec<_>>()
== pipes
}));
for column in 0..2 {
let widest = table
.iter()
.map(|line| line.split('|').nth(column + 1).unwrap().trim().len())
.max()
.unwrap();
assert_eq!(pipes[column + 1] - pipes[column] - 3, widest);
}
assert!(definition.sub_items.is_empty());
assert_eq!(index.sub_items.len(), 6);
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("appendix/requirements-index/coverage.md"))
);
assert_eq!(coverage[0].parent_names, ["Requirements index"]);
assert!(
index
.content
.contains("[Coverage gaps](requirements-index/coverage.html)")
);
let ready = index
.sub_items
.iter()
.find_map(|item| match item {
BookItem::Chapter(chapter) if chapter.name == "requirements.core.ready" => {
Some(chapter)
}
_ => None,
})
.unwrap();
assert_eq!(
ready.source_path.as_deref(),
Some(Path::new("../evidence/requirements.core.ready.json"))
);
assert_eq!(
ready.number.as_deref().map(Vec::as_slice),
Some(&[4, 2][..])
);
assert_eq!(
ready.path.as_deref(),
Some(Path::new(
"appendix/requirements-index/requirements.core.ready.md"
))
);
assert!(ready.content.contains(
"[View definition](../../requirements/core.html#habeas-req-requirements.core.ready)"
));
assert!(
ready
.content
.contains("[Requirements index](../requirements-index.html) · [View definition]")
);
assert!(
ready
.content
.contains("img.shields.io/badge/evidence-Valid-237346")
);
assert!(ready.content.contains("> Ready MUST work."));
assert!(!ready.content.contains("## Evidence record"));
let changed = index
.sub_items
.iter()
.find_map(|item| match item {
BookItem::Chapter(chapter) if chapter.name == "requirements.core.changed" => {
Some(chapter)
}
_ => None,
})
.unwrap();
assert!(changed.content.contains("requirement text changed"));
let absent = index
.sub_items
.iter()
.find_map(|item| match item {
BookItem::Chapter(chapter) if chapter.name == "requirements.core.absent" => {
Some(chapter)
}
_ => None,
})
.unwrap();
assert_eq!(
absent.source_path.as_deref(),
Some(Path::new("requirements/core.md"))
);
}
Input 3: outline src/index.rs mod[tests]/fn[source_links_use_configured_repository_and_branch]
- File:
src/index.rs - Selector:
mod[tests]/fn[source_links_use_configured_repository_and_branch] - Kind:
fn src/index.rs:1551–1625
// {test}`requirements.index.source_links`
#[test]
fn source_links_use_configured_repository_and_branch() {
let config: Config = "[output.html]\ngit-repository-url = \"https://github.com/example/project\"\nedit-url-template = \"https://github.com/example/project/edit/release/{path}\"\n"
.parse()
.unwrap();
let links = SourceLinks::from_config(&config).unwrap().unwrap();
assert_eq!(
links.input_url("src/evidence.rs", 26, 37).as_deref(),
Some("https://github.com/example/project/blob/release/src/evidence.rs#L26-L37")
);
assert_eq!(
links.input_url("src/a b#c.rs", 1, 1).as_deref(),
Some("https://github.com/example/project/blob/release/src/a%20b%23c.rs#L1-L1")
);
assert!(links.input_url("../outside.rs", 1, 2).is_none());
assert!(links.input_url("src/main.rs", 0, 2).is_none());
assert_eq!(
evidence_edit_path(Path::new("docs/md"), "requirements.core.ready"),
Path::new("../../evidence/requirements.core.ready.json")
);
let definition = Definition {
path: Path::new("requirements/core.md").to_path_buf(),
text: "Ready MUST work.".to_owned(),
kind: DefinitionKind::Requirement,
};
let temp = tempfile::tempdir().unwrap();
fs::create_dir_all(temp.path().join("src")).unwrap();
fs::write(
temp.path().join("src/evidence.rs"),
format!(
"{}pub fn validate_repository() {{\n{}}}\n",
"\n".repeat(25),
" let _ = ();\n".repeat(10)
),
)
.unwrap();
let record = json!({
"rationale": "Checked.",
"inputs": [crate::inputs::outline_input(temp.path(), "src/evidence.rs", "fn[validate_repository]").unwrap()]
})
.to_string();
let page = render_detail_page(
"requirements.core.ready",
Path::new("appendix/requirements-index/requirements.core.ready.md"),
Some(Path::new("appendix/requirements-index.md")),
&definition,
DetailEvidence {
state: EvidenceState::Valid,
record: Some(&record),
errors: &[],
fixme_entries: &[],
},
&RenderSources {
root: temp.path(),
definitions: &BTreeMap::new(),
references: &[],
source_links: Some(&links),
outlines: &crate::inputs::OutlineCache::default(),
},
);
assert!(page.contains(
"<a href=\"https://github.com/example/project/blob/release/src/evidence.rs#L26-L37\"><code>src/evidence.rs:26–37</code></a>"
));
let other_config: Config = "[output.html]\ngit-repository-url = \"https://github.com/example/project\"\nedit-url-template = \"https://github.com/other/project/edit/main/{path}\"\n"
.parse()
.unwrap();
assert!(SourceLinks::from_config(&other_config).unwrap().is_none());
let unsafe_config: Config = "[output.html]\ngit-repository-url = \"javascript:alert(1)\"\nedit-url-template = \"javascript:alert(1)/edit/main/{path}\"\n"
.parse()
.unwrap();
assert!(SourceLinks::from_config(&unsafe_config).unwrap().is_none());
}
Input 4: outline src/index.rs mod[tests]/fn[detail_page_shows_recorded_text_locations_and_first_matching_group]
- File:
src/index.rs - Selector:
mod[tests]/fn[detail_page_shows_recorded_text_locations_and_first_matching_group] - Kind:
fn src/index.rs:2210–2314
// {test}`requirements.index.detail_format`
// {test}`requirements.definitions.inputs`
// {test}`requirements.ci.requirements_inputs`
// {test}`requirements.index.source_links`
#[test]
fn detail_page_shows_recorded_text_locations_and_first_matching_group() {
let temp = TempDir::new().unwrap();
let root = temp.path();
for dir in ["md", "evidence", "src"] {
fs::create_dir_all(root.join(dir)).unwrap();
}
fs::write(root.join("book.toml"), "[book]\nsrc = \"md\"\n").unwrap();
let source = ":::{req} ready\nReady uses {term}`rules.term`.\n:::\n\n:::{req} base\nBase.\n:::\n\n:::{definition} term\n:phrase: term\n\nA term.\n:::\n".to_owned();
fs::write(root.join("md/rules.md"), &source).unwrap();
fs::write(
root.join("src/lib.rs"),
"// {impl}`rules.ready`\n// {test}`rules.ready`\nfn both() {}\n",
)
.unwrap();
let inputs = json!([
{"requirements": "rules.*", "matches": ["rules.base", "rules.ready"], "text": ["recorded base", "", "recorded ready"]},
{"definition": "rules.term", "text": ["recorded term"]},
{"requirements": "missing.*", "matches": ["missing.x"], "text": ["recorded missing"]},
crate::inputs::outline_input(root, "src/lib.rs", "fn[both]").unwrap(),
]);
fs::write(
root.join("evidence/rules.ready.json"),
json!({
"requirement": "Ready uses {term}`rules.term`.",
"determination": true,
"rationale": "Checked.",
"inputs": inputs,
})
.to_string(),
)
.unwrap();
let mut book = Book::new();
book.push_item(Chapter::new("Rules", source, "rules.md", Vec::new()));
book.push_item(Chapter::new(
"Index",
":::{requirements-index}\n:::\n".into(),
"requirements-index.md",
Vec::new(),
));
preprocess_book(&mut book, root).unwrap();
let page = book
.chapters()
.find(|chapter| chapter.name == "rules.ready")
.unwrap();
let content = &page.content;
let position = |needle: &str| {
content
.find(needle)
.unwrap_or_else(|| panic!("missing {needle:?} in:\n{content}"))
};
// The state badge has alt text naming the state.
let badge =
position("<img class=\"habeas-shield\" src=\"https://img.shields.io/badge/evidence-");
assert!(
content[badge..].contains("alt=\"evidence Invalid\""),
"{content}"
);
// A requirements input lists each match's name, file, and inclusive
// range, then its recorded text.
let selection = position("<code>requirements selection rules.*</code>");
let base = position("- <code>rules.base</code>: <code>md/rules.md:5–7</code>\n");
let ready = position("- <code>rules.ready</code>: <code>md/rules.md:1–3</code>\n");
let recorded = position("```markdown\nrecorded base\n\nrecorded ready\n```");
assert!(
selection < base && base < ready && ready < recorded,
"{content}"
);
// A definition input shows its name, location, and recorded text.
let definition = position("<code>definition rules.term</code>");
let location = position("- <code>rules.term</code>: <code>md/rules.md:9–13</code>\n");
let text = position("```markdown\nrecorded term\n```");
assert!(definition < location && location < text, "{content}");
let referenced = position("style=\"display: inline\">Referenced definitions</h3>");
let other = position("style=\"display: inline\">Other sources</h3>");
assert!(referenced < definition && definition < other, "{content}");
// An unresolved selector is reported and its recorded text kept.
let unresolved = position("Unresolved selector: ");
let missing = position("```markdown\nrecorded missing\n```");
assert!(unresolved < missing, "{content}");
// A source reached by both an implementation and a test edge appears
// once, in the first group that applies.
let implementation = position("style=\"display: inline\">Implementation</h3>");
let both = position("<code>outline src/lib.rs fn[both]</code>");
assert!(implementation < both, "{content}");
assert!(
!content.contains("style=\"display: inline\">Tests</h3>"),
"{content}"
);
assert_eq!(
content.matches("outline src/lib.rs fn[both]").count(),
1,
"{content}"
);
}
Other sources
Input 1: requirements selection requirements.index.source_links
requirements.index.source_links:md/requirements/index/README.md:34–36
:::{req} source_links
When `output.html.git-repository-url` names a GitHub repository and `output.html.edit-url-template` uses that repository's `/edit/<branch>/{path}` form, each safely resolved source location displayed for an evidence input MUST link its repository-relative file and inclusive line range to `/blob/<branch>/<file>#L<start>-L<end>`. A source location MUST remain plain text when a safe URL cannot be derived. A generated detail page MUST use its evidence JSON file as the mdBook edit target when the file exists, or its requirement chapter when the evidence file is missing.
:::