Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Several fixes for the mdbook-spec preprocessor. #61

Merged
merged 7 commits into from
Jun 27, 2024
Merged
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Convert std links to be relative.
  • Loading branch information
ehuss committed Jun 27, 2024
commit 440272a618d2f4da9350c146ddb7f91aa46fccc1
24 changes: 24 additions & 0 deletions mdbook-spec/src/std_links.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,9 @@ pub fn std_links(chapter: &Chapter) -> String {
// Append the link definitions to the bottom of the chapter.
write!(output, "\n").unwrap();
for ((link, dest), url) in links.iter().zip(urls) {
// Convert links to be relative so that links work offline and
// with the linkchecker.
let url = relative_url(url, chapter);
if let Some(dest) = dest {
write!(output, "[{dest}]: {url}\n").unwrap();
} else {
Expand Down Expand Up @@ -188,3 +191,24 @@ fn run_rustdoc(tmp: &TempDir, links: &[(&str, Option<&str>)], chapter: &Chapter)
process::exit(1);
}
}

static DOC_URL: Lazy<Regex> = Lazy::new(|| {
Regex::new(r"^https://doc.rust-lang.org/(?:nightly|beta|stable|dev|1\.[0-9]+\.[0-9]+)").unwrap()
});

/// Converts a URL to doc.rust-lang.org to be relative.
fn relative_url(url: &str, chapter: &Chapter) -> String {
// Set SPEC_RELATIVE=0 to disable this, which can be useful for working locally.
if std::env::var("SPEC_RELATIVE").as_deref() != Ok("0") {
let Some(url_start) = DOC_URL.shortest_match(url) else {
eprintln!("expected rustdoc URL to start with {DOC_URL:?}, got {url}");
std::process::exit(1);
};
let url_path = &url[url_start..];
let num_dots = chapter.path.as_ref().unwrap().components().count();
let dots = vec![".."; num_dots].join("/");
format!("{dots}{url_path}")
} else {
url.to_string()
}
}