Skip to main content

mant_core/tldr/
cache.rs

1//! Resolves installed-client caches and reads tldr pages without network I/O.
2
3use std::{
4    collections::{BTreeMap, HashSet},
5    env,
6    error::Error,
7    ffi::OsStr,
8    fmt, fs, io,
9    path::{Path, PathBuf},
10};
11
12use mant_ast::TldrDocument;
13
14use crate::executable::{environment_value, find_executable};
15
16use super::parser::{TldrPageLocation, TldrParseError, parse_tldr_page};
17
18const ALL_PLATFORMS: &[&str] = &[
19    "common",
20    "linux",
21    "osx",
22    "macos",
23    "windows",
24    "android",
25    "freebsd",
26    "openbsd",
27    "netbsd",
28    "sunos",
29    "cisco-ios",
30    "dos",
31];
32
33/// Native host families supported by `ManT` distributions.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum HostPlatform {
36    Linux,
37    Macos,
38    Windows,
39}
40
41impl HostPlatform {
42    /// Identify the current build target.
43    ///
44    /// # Errors
45    ///
46    /// Returns [`TldrCacheError::UnsupportedPlatform`] outside supported hosts.
47    pub fn current() -> Result<Self, TldrCacheError> {
48        if cfg!(target_os = "linux") {
49            Ok(Self::Linux)
50        } else if cfg!(target_os = "macos") {
51            Ok(Self::Macos)
52        } else if cfg!(windows) {
53            Ok(Self::Windows)
54        } else {
55            Err(TldrCacheError::UnsupportedPlatform)
56        }
57    }
58}
59
60/// Offline cache discovery or page-read failure.
61#[derive(Debug)]
62pub enum TldrCacheError {
63    UnsupportedPlatform,
64    MissingHomeDirectory,
65    MissingLocalAppData,
66    Read {
67        path: PathBuf,
68        source: io::Error,
69    },
70    Parse {
71        path: PathBuf,
72        source: TldrParseError,
73    },
74}
75
76impl fmt::Display for TldrCacheError {
77    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
78        match self {
79            Self::UnsupportedPlatform => {
80                formatter.write_str("tldr cache lookup is unsupported on this platform")
81            }
82            Self::MissingHomeDirectory => {
83                formatter.write_str("cannot locate a tldr cache without HOME")
84            }
85            Self::MissingLocalAppData => {
86                formatter.write_str("cannot locate a tldr cache without LOCALAPPDATA")
87            }
88            Self::Read { path, source } => {
89                write!(
90                    formatter,
91                    "cannot read cached tldr page {}: {source}",
92                    path.display()
93                )
94            }
95            Self::Parse { path, source } => {
96                write!(
97                    formatter,
98                    "cannot parse cached tldr page {}: {source}",
99                    path.display()
100                )
101            }
102        }
103    }
104}
105
106impl Error for TldrCacheError {
107    fn source(&self) -> Option<&(dyn Error + 'static)> {
108        match self {
109            Self::Read { source, .. } => Some(source),
110            Self::Parse { source, .. } => Some(source),
111            Self::UnsupportedPlatform | Self::MissingHomeDirectory | Self::MissingLocalAppData => {
112                None
113            }
114        }
115    }
116}
117
118/// Resolve the `ManT`-owned fallback checkout for an explicit environment.
119///
120/// # Errors
121///
122/// Returns a platform-specific location error when neither an explicit
123/// override nor the native cache base (`HOME` or `LOCALAPPDATA`) is available.
124pub fn get_tldr_cache_dir(
125    environment: &BTreeMap<String, String>,
126    platform: HostPlatform,
127) -> Result<PathBuf, TldrCacheError> {
128    if let Some(path) = environment_value(environment, "MANT_TLDR_DIR") {
129        return Ok(PathBuf::from(path));
130    }
131    match platform {
132        HostPlatform::Linux => {
133            let home = home_dir(environment)?;
134            Ok(
135                environment_value(environment, "XDG_CACHE_HOME").map_or_else(
136                    || home.join(".cache").join("mant").join("tldr-pages"),
137                    |cache| PathBuf::from(cache).join("mant").join("tldr-pages"),
138                ),
139            )
140        }
141        HostPlatform::Macos => Ok(home_dir(environment)?
142            .join("Library")
143            .join("Caches")
144            .join("ManT")
145            .join("tldr-pages")),
146        HostPlatform::Windows => Ok(local_app_data(environment)?
147            .join("ManT")
148            .join("cache")
149            .join("tldr-pages")),
150    }
151}
152
153/// Return known installed-client cache roots in priority order.
154///
155/// # Errors
156///
157/// Returns [`TldrCacheError::MissingHomeDirectory`] when `HOME` is absent.
158pub fn get_system_tldr_cache_dirs(
159    environment: &BTreeMap<String, String>,
160    platform: HostPlatform,
161) -> Result<Vec<PathBuf>, TldrCacheError> {
162    if platform == HostPlatform::Windows {
163        let local = local_app_data(environment)?;
164        let roaming = environment_value(environment, "APPDATA").map(PathBuf::from);
165        let mut candidates = vec![
166            local.join("tldr"),
167            local.join("tlrc"),
168            local.join("tealdeer").join("tldr-pages"),
169        ];
170        if let Some(roaming) = roaming {
171            candidates.push(roaming.join("tldr"));
172            candidates.push(roaming.join("tlrc"));
173        }
174        if let Some(home) = optional_home_dir(environment) {
175            candidates.push(home.join(".tldrc").join("tldr"));
176            candidates.push(home.join(".tldr").join("cache"));
177            candidates.push(home.join(".tldr"));
178        }
179        return Ok(deduplicate_paths(candidates));
180    }
181
182    let home = home_dir(environment)?;
183    let portable_cache = environment_value(environment, "XDG_CACHE_HOME")
184        .map_or_else(|| home.join(".cache"), PathBuf::from);
185    let native_cache = match platform {
186        HostPlatform::Linux => portable_cache.clone(),
187        HostPlatform::Macos => home.join("Library").join("Caches"),
188        HostPlatform::Windows => unreachable!("Windows returned above"),
189    };
190    let mut candidates = vec![
191        portable_cache.join("tldr"),
192        native_cache.join("tlrc"),
193        portable_cache.join("tlrc"),
194        native_cache.join("tealdeer").join("tldr-pages"),
195        portable_cache.join("tealdeer").join("tldr-pages"),
196        // Homebrew's `tldr` formula installs tldr-c-client, which extracts
197        // the upstream repository below this root on every supported host.
198        home.join(".tldrc").join("tldr"),
199        // The official Node client adds one private `cache` layer beneath its
200        // configured root (which defaults to ~/.tldr).
201        home.join(".tldr").join("cache"),
202        home.join(".tldr"),
203    ];
204
205    if let Some(value) = environment_value(environment, "XDG_DATA_DIRS") {
206        candidates.extend(
207            env::split_paths(OsStr::new(value))
208                .filter(|path| !path.as_os_str().is_empty())
209                .map(|path| path.join("tldr")),
210        );
211    } else {
212        candidates.extend(
213            ["/usr/local/share", "/usr/share"]
214                .into_iter()
215                .map(|path| PathBuf::from(path).join("tldr")),
216        );
217    }
218    Ok(deduplicate_paths(candidates))
219}
220
221/// Select installed-client caches followed by `ManT`'s private fallback.
222///
223/// # Errors
224///
225/// Propagates cache path resolution failures.
226pub fn get_tldr_read_cache_dirs(
227    environment: &BTreeMap<String, String>,
228    platform: HostPlatform,
229    tldr_installed: bool,
230) -> Result<Vec<PathBuf>, TldrCacheError> {
231    if environment_value(environment, "MANT_TLDR_DIR").is_some() {
232        return get_tldr_cache_dir(environment, platform).map(|path| vec![path]);
233    }
234    let private_cache = get_tldr_cache_dir(environment, platform)?;
235    if !tldr_installed {
236        return Ok(vec![private_cache]);
237    }
238    let mut caches = get_system_tldr_cache_dirs(environment, platform)?;
239    caches.push(private_cache);
240    Ok(deduplicate_paths(caches))
241}
242
243/// Resolve locale candidates, retaining first occurrence priority.
244#[must_use]
245pub fn get_tldr_languages(environment: &BTreeMap<String, String>) -> Vec<String> {
246    let mut languages = Vec::new();
247    if environment
248        .get("LANG")
249        .is_some_and(|lang| !matches!(lang.as_str(), "C" | "POSIX"))
250    {
251        if let Some(language) = environment.get("LANGUAGE") {
252            for locale in language.split(':') {
253                languages.extend(normalize_locale(locale));
254            }
255        }
256        if let Some(locale) = environment.get("LANG") {
257            languages.extend(normalize_locale(locale));
258        }
259    }
260    languages.push("en".to_owned());
261    deduplicate_strings(languages)
262}
263
264/// Resolve host, common, then cross-platform fallback page directories.
265#[must_use]
266pub fn get_tldr_platforms(platform: HostPlatform) -> Vec<String> {
267    let mut platforms = match platform {
268        HostPlatform::Linux => vec!["linux".to_owned()],
269        HostPlatform::Macos => vec!["osx".to_owned(), "macos".to_owned()],
270        HostPlatform::Windows => vec!["windows".to_owned()],
271    };
272    platforms.extend(ALL_PLATFORMS.iter().map(ToString::to_string));
273    deduplicate_strings(platforms)
274}
275
276/// Convert a multi-word query to the tldr filename convention.
277#[must_use]
278pub fn normalize_tldr_topic(topic: &str) -> String {
279    topic
280        .trim()
281        .to_lowercase()
282        .split_whitespace()
283        .collect::<Vec<_>>()
284        .join("-")
285}
286
287/// Reject a normalized topic that would escape the platform page directory.
288///
289/// The topic becomes a single `<page>.md` filename joined onto a cache root,
290/// so it must be exactly one ordinary path component. Anything containing a
291/// path separator, a `.`/`..` segment, or an absolute or prefix component is
292/// refused before it reaches the filesystem, which prevents an untrusted topic
293/// (for example one supplied over MCP) from reading files outside the cache.
294fn is_safe_page_name(page_name: &str) -> bool {
295    let mut components = Path::new(page_name).components();
296    matches!(
297        (components.next(), components.next()),
298        (Some(std::path::Component::Normal(_)), None)
299    )
300}
301
302/// Read one cached tldr page using current host conventions; never updates it.
303///
304/// # Errors
305///
306/// Returns a cache path, I/O, or parser error. A missing page is `Ok(None)`.
307pub fn read_cached_tldr_page(topic: &str) -> Result<Option<TldrDocument>, TldrCacheError> {
308    let environment = env::vars().collect::<BTreeMap<_, _>>();
309    let platform = HostPlatform::current()?;
310    let cache_dirs = get_tldr_read_cache_dirs(
311        &environment,
312        platform,
313        find_executable("tldr", &environment).is_some(),
314    )?;
315    read_cached_tldr_page_with(
316        topic,
317        &cache_dirs,
318        &get_tldr_languages(&environment),
319        &get_tldr_platforms(platform),
320        &SystemFileReader,
321    )
322}
323
324trait TldrFileReader {
325    fn is_file(&self, path: &Path) -> bool;
326    fn read_to_string(&self, path: &Path) -> io::Result<String>;
327}
328
329struct SystemFileReader;
330
331impl TldrFileReader for SystemFileReader {
332    fn is_file(&self, path: &Path) -> bool {
333        path.is_file()
334    }
335
336    fn read_to_string(&self, path: &Path) -> io::Result<String> {
337        fs::read_to_string(path)
338    }
339}
340
341fn read_cached_tldr_page_with(
342    topic: &str,
343    cache_dirs: &[PathBuf],
344    languages: &[String],
345    platforms: &[String],
346    files: &dyn TldrFileReader,
347) -> Result<Option<TldrDocument>, TldrCacheError> {
348    let page_name = normalize_tldr_topic(topic);
349    if page_name.is_empty() || !is_safe_page_name(&page_name) {
350        return Ok(None);
351    }
352
353    // The client specification gives host platform precedence over language.
354    for platform in platforms {
355        for language in languages {
356            let page_directories = if language == "en" {
357                vec!["pages".to_owned(), "pages.en".to_owned()]
358            } else {
359                vec![format!("pages.{language}")]
360            };
361            for cache_dir in cache_dirs {
362                for pages in &page_directories {
363                    let source_path = cache_dir
364                        .join(pages)
365                        .join(platform)
366                        .join(format!("{page_name}.md"));
367                    if !files.is_file(&source_path) {
368                        continue;
369                    }
370                    let markdown = files.read_to_string(&source_path).map_err(|source| {
371                        TldrCacheError::Read {
372                            path: source_path.clone(),
373                            source,
374                        }
375                    })?;
376                    let page = parse_tldr_page(
377                        &markdown,
378                        TldrPageLocation {
379                            platform: platform.clone(),
380                            language: language.clone(),
381                            source_path: source_path.to_string_lossy().into_owned(),
382                        },
383                    )
384                    .map_err(|source| TldrCacheError::Parse {
385                        path: source_path,
386                        source,
387                    })?;
388                    return Ok(Some(page));
389                }
390            }
391        }
392    }
393    Ok(None)
394}
395
396fn home_dir(environment: &BTreeMap<String, String>) -> Result<PathBuf, TldrCacheError> {
397    optional_home_dir(environment).ok_or(TldrCacheError::MissingHomeDirectory)
398}
399
400fn optional_home_dir(environment: &BTreeMap<String, String>) -> Option<PathBuf> {
401    environment_value(environment, "HOME")
402        .or_else(|| environment_value(environment, "USERPROFILE"))
403        .filter(|home| !home.is_empty())
404        .map(PathBuf::from)
405}
406
407fn local_app_data(environment: &BTreeMap<String, String>) -> Result<PathBuf, TldrCacheError> {
408    environment_value(environment, "LOCALAPPDATA")
409        .filter(|path| !path.is_empty())
410        .map(PathBuf::from)
411        .ok_or(TldrCacheError::MissingLocalAppData)
412}
413
414fn normalize_locale(locale: &str) -> Vec<String> {
415    let normalized = locale
416        .split('.')
417        .next()
418        .unwrap_or_default()
419        .replace('-', "_");
420    if normalized.is_empty() || matches!(normalized.as_str(), "C" | "POSIX") {
421        return Vec::new();
422    }
423    let language = normalized.split('_').next().unwrap_or_default().to_owned();
424    if normalized == language {
425        vec![language]
426    } else {
427        vec![normalized, language]
428    }
429}
430
431fn deduplicate_paths(paths: Vec<PathBuf>) -> Vec<PathBuf> {
432    let mut seen = HashSet::new();
433    paths
434        .into_iter()
435        .filter(|path| seen.insert(path.clone()))
436        .collect()
437}
438
439fn deduplicate_strings(values: Vec<String>) -> Vec<String> {
440    let mut seen = HashSet::new();
441    values
442        .into_iter()
443        .filter(|value| seen.insert(value.clone()))
444        .collect()
445}
446
447#[cfg(test)]
448mod tests {
449    use std::{
450        collections::{BTreeMap, HashMap},
451        io,
452        path::{Path, PathBuf},
453    };
454
455    use super::{
456        HostPlatform, TldrFileReader, get_system_tldr_cache_dirs, get_tldr_cache_dir,
457        get_tldr_languages, get_tldr_platforms, get_tldr_read_cache_dirs, normalize_tldr_topic,
458        read_cached_tldr_page_with,
459    };
460
461    const PAGE: &str = "# tar\n\n> Archiving utility.\n\n- List: `tar --list`\n";
462
463    #[derive(Default)]
464    struct MemoryFiles {
465        files: HashMap<PathBuf, String>,
466    }
467
468    impl TldrFileReader for MemoryFiles {
469        fn is_file(&self, path: &Path) -> bool {
470            self.files.contains_key(path)
471        }
472
473        fn read_to_string(&self, path: &Path) -> io::Result<String> {
474            self.files
475                .get(path)
476                .cloned()
477                .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "memory fixture is missing"))
478        }
479    }
480
481    fn env(values: &[(&str, &str)]) -> BTreeMap<String, String> {
482        values
483            .iter()
484            .map(|(key, value)| ((*key).to_owned(), (*value).to_owned()))
485            .collect()
486    }
487
488    #[test]
489    fn resolves_mant_and_installed_client_cache_conventions() {
490        let environment = env(&[("HOME", "/home/test"), ("XDG_CACHE_HOME", "/cache")]);
491        assert_eq!(
492            get_tldr_cache_dir(&environment, HostPlatform::Linux).expect("cache dir"),
493            PathBuf::from("/cache/mant/tldr-pages")
494        );
495        assert_eq!(
496            get_tldr_cache_dir(&environment, HostPlatform::Macos).expect("cache dir"),
497            PathBuf::from("/home/test/Library/Caches/ManT/tldr-pages")
498        );
499        assert_eq!(
500            get_system_tldr_cache_dirs(&environment, HostPlatform::Linux).expect("system caches"),
501            [
502                "/cache/tldr",
503                "/cache/tlrc",
504                "/cache/tealdeer/tldr-pages",
505                "/home/test/.tldrc/tldr",
506                "/home/test/.tldr/cache",
507                "/home/test/.tldr",
508                "/usr/local/share/tldr",
509                "/usr/share/tldr",
510            ]
511            .map(PathBuf::from)
512        );
513        assert_eq!(
514            get_tldr_read_cache_dirs(&environment, HostPlatform::Linux, false)
515                .expect("fallback cache"),
516            [PathBuf::from("/cache/mant/tldr-pages")]
517        );
518        assert_eq!(
519            get_tldr_read_cache_dirs(&environment, HostPlatform::Linux, true)
520                .expect("client caches and fallback"),
521            [
522                "/cache/tldr",
523                "/cache/tlrc",
524                "/cache/tealdeer/tldr-pages",
525                "/home/test/.tldrc/tldr",
526                "/home/test/.tldr/cache",
527                "/home/test/.tldr",
528                "/usr/local/share/tldr",
529                "/usr/share/tldr",
530                "/cache/mant/tldr-pages",
531            ]
532            .map(PathBuf::from)
533        );
534    }
535
536    #[test]
537    fn windows_uses_local_application_data_for_private_and_client_caches() {
538        let environment = env(&[
539            ("LOCALAPPDATA", r"C:\Users\test\AppData\Local"),
540            ("APPDATA", r"C:\Users\test\AppData\Roaming"),
541            ("USERPROFILE", r"C:\Users\test"),
542        ]);
543        assert_eq!(
544            get_tldr_cache_dir(&environment, HostPlatform::Windows).expect("private cache"),
545            PathBuf::from(r"C:\Users\test\AppData\Local").join("ManT/cache/tldr-pages")
546        );
547        assert_eq!(
548            get_system_tldr_cache_dirs(&environment, HostPlatform::Windows).expect("client caches"),
549            [
550                PathBuf::from(r"C:\Users\test\AppData\Local").join("tldr"),
551                PathBuf::from(r"C:\Users\test\AppData\Local").join("tlrc"),
552                PathBuf::from(r"C:\Users\test\AppData\Local").join("tealdeer/tldr-pages"),
553                PathBuf::from(r"C:\Users\test\AppData\Roaming").join("tldr"),
554                PathBuf::from(r"C:\Users\test\AppData\Roaming").join("tlrc"),
555                PathBuf::from(r"C:\Users\test").join(".tldrc/tldr"),
556                PathBuf::from(r"C:\Users\test").join(".tldr/cache"),
557                PathBuf::from(r"C:\Users\test").join(".tldr"),
558            ]
559        );
560        assert_eq!(
561            &get_tldr_platforms(HostPlatform::Windows)[..2],
562            ["windows", "common"]
563        );
564    }
565
566    #[test]
567    fn reads_homebrew_c_client_and_node_client_cache_layouts_on_macos() {
568        let environment = env(&[("HOME", "/Users/test")]);
569        let cache_dirs = get_system_tldr_cache_dirs(&environment, HostPlatform::Macos)
570            .expect("macOS client caches");
571
572        for source in [
573            PathBuf::from("/Users/test/.tldrc/tldr/pages/common/tar.md"),
574            PathBuf::from("/Users/test/.tldr/cache/pages/common/tar.md"),
575        ] {
576            let files = MemoryFiles {
577                files: [(source.clone(), PAGE.to_owned())].into_iter().collect(),
578            };
579            let page = read_cached_tldr_page_with(
580                "tar",
581                &cache_dirs,
582                &["en".to_owned()],
583                &["osx".to_owned(), "common".to_owned()],
584                &files,
585            )
586            .expect("cache read")
587            .expect("page");
588
589            assert_eq!(Path::new(&page.source_path), source);
590        }
591    }
592
593    #[test]
594    fn installed_client_miss_falls_back_to_mant_private_cache() {
595        let environment = env(&[("HOME", "/home/test"), ("XDG_CACHE_HOME", "/cache")]);
596        let cache_dirs = get_tldr_read_cache_dirs(&environment, HostPlatform::Linux, true)
597            .expect("client and private caches");
598        let private_page = PathBuf::from("/cache/mant/tldr-pages/pages/common/tar.md");
599        let files = MemoryFiles {
600            files: [(private_page.clone(), PAGE.to_owned())]
601                .into_iter()
602                .collect(),
603        };
604
605        let page = read_cached_tldr_page_with(
606            "tar",
607            &cache_dirs,
608            &["en".to_owned()],
609            &["linux".to_owned(), "common".to_owned()],
610            &files,
611        )
612        .expect("cache read")
613        .expect("private fallback page");
614
615        assert_eq!(Path::new(&page.source_path), private_page);
616    }
617
618    #[test]
619    fn explicit_cache_is_independent_from_an_installed_client() {
620        let environment = env(&[("HOME", "/home/test"), ("MANT_TLDR_DIR", "/custom/tldr")]);
621        assert_eq!(
622            get_tldr_read_cache_dirs(&environment, HostPlatform::Linux, true)
623                .expect("explicit cache"),
624            [PathBuf::from("/custom/tldr")]
625        );
626    }
627
628    #[test]
629    fn normalizes_topic_locale_and_platform_priority() {
630        let environment = env(&[("LANG", "pt_BR.UTF-8"), ("LANGUAGE", "zh_TW:pt_BR")]);
631        assert_eq!(
632            get_tldr_languages(&environment),
633            ["zh_TW", "zh", "pt_BR", "pt", "en"]
634        );
635        assert_eq!(
636            &get_tldr_platforms(HostPlatform::Linux)[..3],
637            ["linux", "common", "osx"]
638        );
639        assert_eq!(normalize_tldr_topic(" Git Commit "), "git-commit");
640    }
641
642    #[test]
643    fn host_platform_precedes_a_translated_common_page() {
644        let root = PathBuf::from("/cache");
645        let english_linux = root.join("pages/linux/tar.md");
646        let translated_common = root.join("pages.zh/common/tar.md");
647        let files = MemoryFiles {
648            files: [
649                (english_linux.clone(), PAGE.to_owned()),
650                (translated_common, PAGE.to_owned()),
651            ]
652            .into_iter()
653            .collect(),
654        };
655        let page = read_cached_tldr_page_with(
656            "tar",
657            &[root],
658            &["zh".to_owned(), "en".to_owned()],
659            &["linux".to_owned(), "common".to_owned()],
660            &files,
661        )
662        .expect("cache read")
663        .expect("page");
664        assert_eq!(Path::new(&page.source_path), english_linux);
665        assert_eq!(page.language, "en");
666        assert_eq!(page.platform, "linux");
667    }
668
669    #[test]
670    fn reads_pages_dot_en_layout_after_repository_layout() {
671        let root = PathBuf::from("/cache/tlrc");
672        let source = root.join("pages.en/linux/tar.md");
673        let files = MemoryFiles {
674            files: [(source.clone(), PAGE.to_owned())].into_iter().collect(),
675        };
676        let page = read_cached_tldr_page_with(
677            "tar",
678            &[root],
679            &["en".to_owned()],
680            &["linux".to_owned()],
681            &files,
682        )
683        .expect("cache read")
684        .expect("page");
685        assert_eq!(Path::new(&page.source_path), source);
686    }
687
688    #[test]
689    fn refuses_topics_that_escape_the_platform_page_directory() {
690        let root = PathBuf::from("/cache");
691        // A page planted where a naive join of a traversal topic would land.
692        let escaped = PathBuf::from("/etc/hostname.md");
693        let files = MemoryFiles {
694            files: [(escaped, PAGE.to_owned())].into_iter().collect(),
695        };
696
697        for topic in ["../../../../etc/hostname", "/etc/hostname", "..", "a/b"] {
698            let result = read_cached_tldr_page_with(
699                topic,
700                std::slice::from_ref(&root),
701                &["en".to_owned()],
702                &["linux".to_owned()],
703                &files,
704            )
705            .expect("cache read must not error");
706            assert!(
707                result.is_none(),
708                "traversal topic {topic:?} must not resolve a page"
709            );
710        }
711    }
712
713    #[test]
714    fn only_single_ordinary_components_are_safe_page_names() {
715        assert!(super::is_safe_page_name("tar"));
716        assert!(super::is_safe_page_name("git-commit"));
717        assert!(!super::is_safe_page_name("../etc/passwd"));
718        assert!(!super::is_safe_page_name("/etc/passwd"));
719        assert!(!super::is_safe_page_name(".."));
720        assert!(!super::is_safe_page_name("a/b"));
721    }
722}