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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/sourceorigin-standard/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ A repository adopts the standard in four steps:
- `cache-saves`: Every `Swatinem/rust-cache` step's `save-if` is `false` or saves from `refs/heads/main` only, and no composite action, nor workflow run by `pull_request`, `pull_request_target` or `merge_group`, uses `actions/cache`, which saves on a miss: they use `actions/cache/restore`, saving with `actions/cache/save` from `main`.
- `scheduled-audit`: A workflow runs `just audit` (or `cargo deny`) on a `schedule` at least weekly: a cron whose day of the month and month are `*`.
- `pr-template`: `.github/pull_request_template.md` has the headings `## What and why` and `## Testing`.
- `docs-summary`: With a `book.toml`, every Markdown page under its `src` is linked from its `SUMMARY.md`, or included in a page with `{{#include …}}`.
<!-- rules:end -->

Each rule is a variant of [`Rule`]: its name is the one `standard.toml` and
Expand Down
117 changes: 117 additions & 0 deletions crates/sourceorigin-standard/src/rules/docs_summary.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
//! `docs-summary`: every page of the book is reachable from its table of
//! contents.

use std::collections::BTreeSet;
use std::path::{Component, Path, PathBuf};

use serde::Deserialize;

use super::text_file::TextFile;
use super::{Finding, Repository};

/// mdBook's configuration, from the repository's root.
pub(super) const BOOK: &str = "book.toml";

/// `book.toml`, reduced to where the pages are.
#[derive(Deserialize)]
pub(super) struct Book {
book: Option<BookTable>,
}

#[derive(Deserialize)]
struct BookTable {
src: Option<String>,
}

impl Book {
/// The directory of its pages, from the repository's root.
fn src(&self) -> PathBuf {
PathBuf::from(
self.book
.as_ref()
.and_then(|book| book.src.as_deref())
.unwrap_or("src"),
)
}
}

impl TextFile {
/// The pages the file links, with `](…)`, from the repository's root.
fn links(&self) -> Vec<PathBuf> {
let targets = self
.text
.match_indices("](")
.filter_map(|(at, _)| self.text[at + 2..].split([')', '#', ' ']).next());
self.resolve(targets)
}

/// The files the page includes, with `{{#include …}}`, from the
/// repository's root.
fn includes(&self) -> Vec<PathBuf> {
let targets = self
.text
.match_indices("{{#include ")
.filter_map(|(at, directive)| {
self.text[at + directive.len()..].split(['}', ':']).next()
});
self.resolve(targets)
}

/// `targets`, relative to the file, from the repository's root, with
/// their `.` and `..` resolved; URLs and empty targets dropped.
fn resolve<'a>(&self, targets: impl Iterator<Item = &'a str>) -> Vec<PathBuf> {
let dir = self.path.parent().unwrap_or(Path::new(""));
targets
.map(str::trim)
.filter(|target| !target.is_empty() && !target.contains("://"))
.map(|target| {
let mut path = PathBuf::new();
for component in dir.join(target).components() {
match component {
Component::ParentDir => {
path.pop();
}
Component::CurDir => {}
other => path.push(other),
}
}
path
})
.collect()
}
}

impl Repository {
/// Each page under the book's `src` that its `SUMMARY.md` doesn't link
/// and no page includes.
pub(super) fn docs_summary(&self) -> Vec<Finding> {
let Some(book) = &self.book else {
return Vec::new();
};
let src = book.value.src();
let summary = src.join("SUMMARY.md");
let pages: Vec<&TextFile> = self
.markdown
.iter()
.filter(|page| page.path.starts_with(&src))
.collect();
let mut reached: BTreeSet<PathBuf> =
pages.iter().flat_map(|page| page.includes()).collect();
if let Some(summary) = pages.iter().find(|page| page.path == summary) {
reached.extend(summary.links());
}
pages
.iter()
.filter(|page| page.path != summary && !reached.contains(&page.path))
.map(|page| Finding {
path: page.path.clone(),
line: 1,
message: format!(
"no page reaches this one: link it from {}, or include it in a page with \
`{{{{#include …}}}}`",
summary.display()
),
})
.collect()
}
}
11 changes: 11 additions & 0 deletions crates/sourceorigin-standard/src/rules/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ mod clippy_config;
mod comments;
mod config_comments;
mod deny_config;
mod docs_summary;
mod fix;
mod generated_lints;
mod job_timeouts;
Expand Down Expand Up @@ -58,6 +59,7 @@ use agent_files::AgentFiles;
use budget::Budget;
use config_comments::Commented;
use deny_config::DenyConfig;
use docs_summary::Book;
use fix::Checked;
pub use fix::Fix;
use justfile::Justfile;
Expand Down Expand Up @@ -248,6 +250,9 @@ rules! {
/// `.github/pull_request_template.md` has the headings `## What and
/// why` and `## Testing`.
PrTemplate = "pr-template" => pr_template,
/// With a `book.toml`, every Markdown page under its `src` is linked
/// from its `SUMMARY.md`, or included in a page with `{{#include …}}`.
DocsSummary = "docs-summary" => docs_summary,
}

/// Why the rules couldn't be checked.
Expand Down Expand Up @@ -452,6 +457,10 @@ struct Repository {
workflows: Vec<Workflow>,
/// The pull request template.
pr_template: Option<TextFile>,
/// mdBook's `book.toml`.
book: Option<TomlFile<Book>>,
/// Every Markdown file.
markdown: Vec<TextFile>,
}

impl Repository {
Expand Down Expand Up @@ -481,6 +490,8 @@ impl Repository {
t3: T3::load(root)?,
workflows: Workflow::load_all(root)?,
pr_template: TextFile::load_all(root, &[pr_template::PATH])?.pop(),
book: TomlFile::load(root, docs_summary::BOOK)?,
markdown: TextFile::load_all(root, &["*.md"])?,
metadata,
sources,
unparsed,
Expand Down
29 changes: 29 additions & 0 deletions crates/sourceorigin-standard/src/rules/tests/docs_summary.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
use super::{Fixture, INHERITS};
use crate::rules::Rule;

#[test]
fn every_page_of_the_book_is_reachable() {
let fixture = Fixture::new();
fixture
.add_crate("core", INHERITS)
.write("book.toml", "[book]\ntitle = \"Docs\"\nsrc = \"docs\"\n")
.write(
"docs/SUMMARY.md",
"# Summary\n\n- [Guide](./user/guide.md)\n - [Setup](user/setup.md#install)\n",
)
.write(
"docs/user/guide.md",
"# Guide\n\n{{#include ../reference/flags.md:2:}}\n",
)
.write("docs/user/setup.md", "# Setup\n")
.write("docs/reference/flags.md", "- `--flag`\n")
.write("docs/dev/forgotten.md", "# Forgotten\n")
.write("crates/core/README.md", "# Core\n");
assert_eq!(
fixture.violations(Rule::DocsSummary),
[
"docs/dev/forgotten.md:1: no page reaches this one: link it from docs/SUMMARY.md, or \
include it in a page with `{{#include …}}` (docs-summary)"
]
);
}
1 change: 1 addition & 0 deletions crates/sourceorigin-standard/src/rules/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ mod clippy_config;
mod comments;
mod config_comments;
mod deny_config;
mod docs_summary;
mod fix;
mod framework;
mod generated_lints;
Expand Down