Skip to main content

reflex/pulse/model/
xref.rs

1//! Link targets and their central resolution.
2//!
3//! Content links to a [`Target`]; only the [`Linker`] turns targets into URLs. Routes
4//! are base-less (`/internals/modules/src-pulse/`); the renderer prefixes the site's
5//! base path, so `--base-url /reflex/` needs no change here.
6
7use super::Site;
8use super::content::{Block, Inline};
9use super::ids::{AnchorId, PageId, SymbolId};
10use serde::{Deserialize, Serialize};
11use std::path::Path;
12
13#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
14#[serde(tag = "type", rename_all = "kebab-case")]
15pub enum Target {
16    Page { page: PageId },
17    Section { page: PageId, anchor: AnchorId },
18    Symbol { symbol: SymbolId },
19    Source { loc: SourceLoc },
20    External { url: String },
21}
22
23impl Target {
24    pub fn page(id: impl Into<PageId>) -> Self {
25        Target::Page { page: id.into() }
26    }
27}
28
29/// Lines of a file in the indexed tree. `start == 0` means the whole file.
30#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
31pub struct SourceLoc {
32    pub path: String,
33    #[serde(default, skip_serializing_if = "is_zero")]
34    pub start: u32,
35    #[serde(default, skip_serializing_if = "is_zero")]
36    pub end: u32,
37}
38
39fn is_zero(n: &u32) -> bool {
40    *n == 0
41}
42
43impl SourceLoc {
44    pub fn file(path: impl Into<String>) -> Self {
45        Self {
46            path: path.into(),
47            start: 0,
48            end: 0,
49        }
50    }
51
52    pub fn lines(path: impl Into<String>, start: u32, end: u32) -> Self {
53        Self {
54            path: path.into(),
55            start,
56            end: end.max(start),
57        }
58    }
59
60    /// `src/a.rs`, `src/a.rs:10` or `src/a.rs:10-20`.
61    pub fn label(&self) -> String {
62        match (self.start, self.end) {
63            (0, _) => self.path.clone(),
64            (s, e) if e > s => format!("{}:{s}-{e}", self.path),
65            (s, _) => format!("{}:{s}", self.path),
66        }
67    }
68}
69
70/// Where the source lives on the web, for permalinks.
71#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
72pub struct RepoInfo {
73    /// `https://github.com/owner/repo`
74    pub web_url: String,
75    pub host: RepoHost,
76    /// Full commit sha the site was built from.
77    pub commit: String,
78}
79
80#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
81#[serde(rename_all = "kebab-case")]
82pub enum RepoHost {
83    GitHub,
84    GitLab,
85    Other,
86}
87
88impl RepoInfo {
89    /// Detect from `git remote get-url origin` and `HEAD`. `None` outside git or with
90    /// a remote we cannot build web links for.
91    pub fn detect(workspace: &Path) -> Option<Self> {
92        let git = |args: &[&str]| -> Option<String> {
93            let out = std::process::Command::new("git")
94                .args(args)
95                .current_dir(workspace)
96                .output()
97                .ok()?;
98            out.status
99                .success()
100                .then(|| String::from_utf8_lossy(&out.stdout).trim().to_string())
101                .filter(|s| !s.is_empty())
102        };
103        let remote = git(&["remote", "get-url", "origin"])?;
104        let commit = git(&["rev-parse", "HEAD"])?;
105        Self::from_remote(&remote, commit)
106    }
107
108    /// Parse a git remote (https or scp-style ssh) into a web URL.
109    pub fn from_remote(remote: &str, commit: String) -> Option<Self> {
110        let remote = remote.trim();
111        let (host, path) = if let Some(rest) = remote.strip_prefix("git@") {
112            rest.split_once(':')?
113        } else {
114            let rest = remote
115                .strip_prefix("https://")
116                .or_else(|| remote.strip_prefix("http://"))
117                .or_else(|| remote.strip_prefix("ssh://git@"))?;
118            let rest = rest.rsplit_once('@').map(|(_, r)| r).unwrap_or(rest);
119            rest.split_once('/')?
120        };
121        let host = host.split(':').next()?; // drop an ssh port
122        let path = path.trim_end_matches('/').trim_end_matches(".git");
123        if path.is_empty() || host.is_empty() {
124            return None;
125        }
126        let kind = match host {
127            "github.com" => RepoHost::GitHub,
128            h if h == "gitlab.com" || h.starts_with("gitlab.") => RepoHost::GitLab,
129            _ => RepoHost::Other,
130        };
131        Some(Self {
132            web_url: format!("https://{host}/{path}"),
133            host: kind,
134            commit,
135        })
136    }
137
138    /// Permalink to lines of a file at the site's commit.
139    pub fn blob_url(&self, loc: &SourceLoc) -> Option<String> {
140        let blob = match self.host {
141            RepoHost::GitHub => "blob",
142            RepoHost::GitLab => "-/blob",
143            RepoHost::Other => return None,
144        };
145        let mut url = format!("{}/{blob}/{}/{}", self.web_url, self.commit, loc.path);
146        match (self.host, loc.start, loc.end) {
147            (_, 0, _) => {}
148            (RepoHost::GitHub, s, e) if e > s => url.push_str(&format!("#L{s}-L{e}")),
149            (RepoHost::GitLab, s, e) if e > s => url.push_str(&format!("#L{s}-{e}")),
150            (_, s, _) => url.push_str(&format!("#L{s}")),
151        }
152        Some(url)
153    }
154}
155
156/// A resolved link.
157#[derive(Debug, Clone, PartialEq, Eq)]
158pub struct Resolved {
159    /// Base-less route (`/docs/…/#anchor`) or an absolute external URL.
160    pub href: String,
161    pub external: bool,
162}
163
164/// Resolves [`Target`]s against one site.
165pub struct Linker<'a> {
166    site: &'a Site,
167}
168
169impl<'a> Linker<'a> {
170    pub fn new(site: &'a Site) -> Self {
171        Self { site }
172    }
173
174    pub fn resolve(&self, target: &Target) -> Option<Resolved> {
175        let internal = |href: String| Resolved {
176            href,
177            external: false,
178        };
179        match target {
180            Target::Page { page } => self.site.pages.get(page).map(|p| internal(p.route.clone())),
181            Target::Section { page, anchor } => self
182                .site
183                .pages
184                .get(page)
185                .map(|p| internal(format!("{}#{anchor}", p.route))),
186            Target::Symbol { symbol } => {
187                let entry = self.site.symbols.get(symbol)?;
188                let page = self.site.pages.get(&entry.page)?;
189                Some(internal(match &entry.anchor {
190                    Some(a) => format!("{}#{a}", page.route),
191                    None => page.route.clone(),
192                }))
193            }
194            Target::Source { loc } => self
195                .site
196                .meta
197                .repo
198                .as_ref()
199                .and_then(|r| r.blob_url(loc))
200                .map(|href| Resolved {
201                    href,
202                    external: true,
203                }),
204            Target::External { url } => Some(Resolved {
205                href: url.clone(),
206                external: true,
207            }),
208        }
209    }
210
211    /// Every internal link that does not resolve, as `(page, target)`. Source links
212    /// without a repo are not broken: they render as plain paths.
213    pub fn broken(&self) -> Vec<(PageId, Target)> {
214        let mut out = Vec::new();
215        for page in self.site.pages.values() {
216            let mut targets = Vec::new();
217            collect_block_targets(&page.blocks, &mut targets);
218            for t in targets {
219                let checkable = matches!(
220                    t,
221                    Target::Page { .. } | Target::Section { .. } | Target::Symbol { .. }
222                );
223                if checkable && self.resolve(&t).is_none() {
224                    out.push((page.id.clone(), t));
225                }
226            }
227        }
228        for tab in &self.site.tabs {
229            let mut ids = vec![tab.landing.clone()];
230            super::collect_nav_pages(&tab.nav, &mut ids);
231            for id in ids {
232                if !self.site.pages.contains_key(&id) {
233                    out.push((tab.landing.clone(), Target::Page { page: id }));
234                }
235            }
236        }
237        out.sort();
238        out.dedup();
239        out
240    }
241}
242
243fn collect_inline_targets(inlines: &[Inline], out: &mut Vec<Target>) {
244    for i in inlines {
245        match i {
246            Inline::Link { to, content } => {
247                out.push(to.clone());
248                collect_inline_targets(content, out);
249            }
250            Inline::Strong { content } | Inline::Emph { content } => {
251                collect_inline_targets(content, out)
252            }
253            Inline::Text { .. } | Inline::Code { .. } | Inline::Fact { .. } => {}
254        }
255    }
256}
257
258pub(super) fn collect_block_targets(blocks: &[Block], out: &mut Vec<Target>) {
259    for b in blocks {
260        match b {
261            Block::Paragraph { content } => collect_inline_targets(content, out),
262            Block::List { items, .. } => {
263                for item in items {
264                    collect_inline_targets(item, out);
265                }
266            }
267            Block::Table { rows, .. } => {
268                for cell in rows.iter().flatten() {
269                    collect_inline_targets(cell, out);
270                }
271            }
272            Block::Callout { body, .. } => collect_block_targets(body, out),
273            Block::Narrative { fallback, .. } => collect_block_targets(fallback, out),
274            Block::Diagram { links, .. } => out.extend(links.iter().map(|(_, t)| t.clone())),
275            Block::Cards { cards } => out.extend(cards.iter().map(|c| c.to.clone())),
276            Block::Heading { .. }
277            | Block::Symbol { .. }
278            | Block::Markdown { .. }
279            | Block::Code { .. }
280            | Block::Stats { .. } => {}
281        }
282    }
283}
284
285#[cfg(test)]
286mod tests {
287    use super::*;
288
289    #[test]
290    fn remotes_parse() {
291        let c = "abc123".to_string();
292        let r =
293            RepoInfo::from_remote("git@github.com:reflex-search/reflex.git", c.clone()).unwrap();
294        assert_eq!(r.web_url, "https://github.com/reflex-search/reflex");
295        assert_eq!(r.host, RepoHost::GitHub);
296        let r = RepoInfo::from_remote("https://github.com/o/r", c.clone()).unwrap();
297        assert_eq!(r.web_url, "https://github.com/o/r");
298        let r = RepoInfo::from_remote("https://token@gitlab.com/g/sub/r.git", c.clone()).unwrap();
299        assert_eq!(r.web_url, "https://gitlab.com/g/sub/r");
300        assert_eq!(r.host, RepoHost::GitLab);
301        let r =
302            RepoInfo::from_remote("ssh://git@gitlab.example.com:2222/g/r.git", c.clone()).unwrap();
303        assert_eq!(r.web_url, "https://gitlab.example.com/g/r");
304        assert!(RepoInfo::from_remote("/local/path", c).is_none());
305    }
306
307    #[test]
308    fn blob_urls() {
309        let gh = RepoInfo::from_remote("git@github.com:o/r.git", "sha".into()).unwrap();
310        assert_eq!(
311            gh.blob_url(&SourceLoc::lines("src/a.rs", 10, 20)).unwrap(),
312            "https://github.com/o/r/blob/sha/src/a.rs#L10-L20"
313        );
314        assert_eq!(
315            gh.blob_url(&SourceLoc::lines("src/a.rs", 7, 7)).unwrap(),
316            "https://github.com/o/r/blob/sha/src/a.rs#L7"
317        );
318        assert_eq!(
319            gh.blob_url(&SourceLoc::file("README.md")).unwrap(),
320            "https://github.com/o/r/blob/sha/README.md"
321        );
322        let gl = RepoInfo::from_remote("https://gitlab.com/o/r", "sha".into()).unwrap();
323        assert_eq!(
324            gl.blob_url(&SourceLoc::lines("a", 1, 3)).unwrap(),
325            "https://gitlab.com/o/r/-/blob/sha/a#L1-3"
326        );
327        let other = RepoInfo::from_remote("https://git.example.com/o/r", "sha".into()).unwrap();
328        assert!(other.blob_url(&SourceLoc::file("a")).is_none());
329    }
330
331    #[test]
332    fn source_loc_labels() {
333        assert_eq!(SourceLoc::file("a.rs").label(), "a.rs");
334        assert_eq!(SourceLoc::lines("a.rs", 4, 4).label(), "a.rs:4");
335        assert_eq!(SourceLoc::lines("a.rs", 4, 9).label(), "a.rs:4-9");
336    }
337}