mdbook_linkcheck/
links.rs

1use codespan::{FileId, Files, Span};
2use linkcheck::Link;
3use pulldown_cmark::{BrokenLink, CowStr};
4use std::{cell::RefCell, fmt::Debug};
5
6/// Search every file in the [`Files`] and collate all the links that are
7/// found.
8pub fn extract<I>(
9    target_files: I,
10    files: &Files<String>,
11) -> (Vec<Link>, Vec<IncompleteLink>)
12where
13    I: IntoIterator<Item = FileId>,
14{
15    let mut links = Vec::new();
16    let broken_links = RefCell::new(Vec::new());
17
18    for file_id in target_files {
19        let src = files.source(file_id);
20        log::debug!("Scanning {}", files.name(file_id).to_string_lossy());
21
22        links.extend(scan_links(file_id, &*src, &mut |broken_link| {
23            let BrokenLink {
24                reference, span, ..
25            } = broken_link;
26            log::debug!(
27                "Found a (possibly) broken link to [{}] at {:?}",
28                reference,
29                span
30            );
31
32            broken_links.borrow_mut().push(IncompleteLink {
33                reference: broken_link.reference.to_string(),
34                span: Span::new(span.start as u32, span.end as u32),
35                file: file_id,
36            });
37            None
38        }));
39    }
40
41    (links, broken_links.into_inner())
42}
43
44fn scan_links<'a, F>(
45    file_id: FileId,
46    src: &'a str,
47    cb: &'a mut F,
48) -> impl Iterator<Item = Link> + 'a
49where
50    F: FnMut(BrokenLink<'_>) -> Option<(CowStr<'a>, CowStr<'a>)> + 'a,
51{
52    linkcheck::scanners::markdown_with_broken_link_callback(src, Some(cb))
53        .map(move |(link, span)| Link::new(link, span, file_id))
54}
55
56/// A potential link that has a broken reference (e.g `[foo]` when there is no
57/// `[foo]: ...` entry at the bottom).
58#[derive(Debug, Clone, PartialEq)]
59pub struct IncompleteLink {
60    /// The reference name (e.g. the `foo` in `[foo]`).
61    pub reference: String,
62    /// Which file was the incomplete link found in?
63    pub file: FileId,
64    /// Where this incomplete link occurred in the source text.
65    pub span: Span,
66}