Debian Codegraph @

crates/mdbook-html/src/utils.rs

raw
1 //! Utilities for processing HTML.
2
3 use std::collections::HashSet;
4 use std::path::{Component, Path, PathBuf};
5
6 /// Utility function to normalize path elements like `..`.
7 pub(crate) fn normalize_path(path: &Path) -> PathBuf {
8 let mut components = path.components().peekable();
9 let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() {
10 components.next();
11 PathBuf::from(c.as_os_str())
12 } else {
13 PathBuf::new()
14 };
15
16 for component in components {
17 match component {
18 Component::Prefix(..) => unreachable!(),
19 Component::RootDir => {
20 ret.push(Component::RootDir);
21 }
22 Component::CurDir => {}
23 Component::ParentDir => {
24 if ret.ends_with(Component::ParentDir) {
25 ret.push(Component::ParentDir);
26 } else {
27 let popped = ret.pop();
28 if !popped && !ret.has_root() {
29 ret.push(Component::ParentDir);
30 }
31 }
32 }
33 Component::Normal(c) => {
34 ret.push(c);
35 }
36 }
37 }
38 ret
39 }
40
41 /// Helper trait for converting a [`Path`] to a string suitable for an HTML path.
42 pub(crate) trait ToUrlPath {
43 fn to_url_path(&self) -> String;
44 }
45
46 impl ToUrlPath for Path {
47 fn to_url_path(&self) -> String {
48 // We're generally assuming that all paths we deal with are utf-8.
49 // The replace here is to handle Windows paths.
50 self.to_str().unwrap().replace('\\', "/")
51 }
52 }
53
54 /// Make sure an HTML id is unique.
55 ///
56 /// Keeps a set of all previously returned IDs; if the requested id is already
57 /// used, numeric suffixes (-1, -2, ...) are tried until an unused one is found.
58 pub(crate) fn unique_id(id: &str, used: &mut HashSet<String>) -> String {
59 if used.insert(id.to_string()) {
60 return id.to_string();
61 }
62
63 // This ID is already in use. Generate one that is not by appending a
64 // numeric suffix.
65 let mut counter: u32 = 1;
66 loop {
67 let candidate = format!("{id}-{counter}");
68 if used.insert(candidate.clone()) {
69 return candidate;
70 }
71 counter += 1;
72 }
73 }
74
75 /// Generates an HTML id from the given text.
76 pub(crate) fn id_from_content(content: &str) -> String {
77 // This is intended to be close to how header ID generation is done in
78 // other sites and tools, but is not 100% the same. Not all sites and
79 // tools use the same algorithm. See these for more information:
80 //
81 // - https://docs.github.com/en/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax#section-links
82 // - https://docs.gitlab.com/user/markdown/#heading-ids-and-links
83 // - https://pandoc.org/MANUAL.html#extension-auto_identifiers
84 // - https://kramdown.gettalong.org/converter/html#auto-ids
85 // - https://docs.rs/comrak/latest/comrak/options/struct.Extension.html#structfield.header_ids
86 content
87 .trim()
88 .to_lowercase()
89 .chars()
90 .filter_map(|ch| {
91 if ch.is_alphanumeric() || ch == '_' || ch == '-' {
92 Some(ch)
93 } else if ch.is_whitespace() {
94 Some('-')
95 } else {
96 None
97 }
98 })
99 .collect()
100 }
101
102 #[cfg(test)]
103 mod tests {
104 use super::*;
105
106 #[test]
107 fn it_generates_unique_ids() {
108 let mut id_counter = Default::default();
109
110 assert_eq!(unique_id("", &mut id_counter), "");
111 assert_eq!(unique_id("Über", &mut id_counter), "Über");
112 assert_eq!(unique_id("Über", &mut id_counter), "Über-1");
113 assert_eq!(unique_id("Über", &mut id_counter), "Über-2");
114 }
115
116 #[test]
117 fn it_normalizes_ids() {
118 assert_eq!(
119 id_from_content("`--passes`: add more rustdoc passes"),
120 "--passes-add-more-rustdoc-passes"
121 );
122 assert_eq!(
123 id_from_content("Method-call 🐙 expressions \u{1f47c}"),
124 "method-call--expressions-"
125 );
126 assert_eq!(id_from_content("_-_12345"), "_-_12345");
127 assert_eq!(id_from_content("12345"), "12345");
128 assert_eq!(id_from_content("中文"), "中文");
129 assert_eq!(id_from_content("にほんご"), "にほんご");
130 assert_eq!(id_from_content("한국어"), "한국어");
131 assert_eq!(id_from_content(""), "");
132 assert_eq!(id_from_content("中文標題 CJK title"), "中文標題-cjk-title");
133 assert_eq!(id_from_content("Über"), "über");
134 }
135 }