Skip to main content

lockdocs_core/upstream/
repository.rs

1//! Discover the source repository from installed package metadata.
2
3use crate::locate::Source;
4use crate::{Dep, Eco};
5use serde_json::Value;
6
7use super::Repo;
8
9/// Parse a GitHub URL or shorthand into owner/name.
10pub fn parse_github(url: &str) -> Option<(String, String)> {
11    let u = url.trim();
12    let rest = if let Some(r) = u.strip_prefix("github:") {
13        r
14    } else if let Some(i) = u.find("github.com") {
15        u[i + "github.com".len()..].trim_start_matches([':', '/'])
16    } else if !u.contains(':') && u.matches('/').count() == 1 && !u.starts_with('.') {
17        u // npm "owner/repo" shorthand
18    } else {
19        return None;
20    };
21    let mut it = rest.split(['/', '#', '?']).filter(|s| !s.is_empty());
22    let owner = it.next()?.to_string();
23    let name = it.next()?.trim_end_matches(".git").to_string();
24    let safe = |s: &str| !s.is_empty() && s != "." && s != ".." && s.bytes().all(|b| b.is_ascii_alphanumeric() || b"-_.".contains(&b));
25    if !safe(&owner) || !safe(&name) {
26        return None;
27    }
28    Some((owner, name))
29}
30
31type RepoParts = (Option<crate::private::Origin>, String, String);
32
33/// A repository URL on github.com, or (with `any_host`) on another git host.
34fn parse_repo(url: &str, any_host: bool) -> Option<RepoParts> {
35    if let Some((owner, name)) = parse_github(url) {
36        return Some((None, owner, name));
37    }
38    if !any_host {
39        return None;
40    }
41    let (origin, path) = crate::private::git::parse_repo_url(url)?;
42    let (owner, name) = path.rsplit_once('/')?;
43    Some((Some(origin), owner.to_string(), name.to_string()))
44}
45
46/// The package's source repository on github.com, from its own metadata.
47pub fn repo_of(dep: &Dep, src: &Source) -> Option<Repo> {
48    repo_of_with(dep, src, false)
49}
50
51/// Like `repo_of`; with `any_host` a repository on another git host qualifies too.
52pub fn repo_of_with(dep: &Dep, src: &Source, any_host: bool) -> Option<Repo> {
53    match dep.eco {
54        Eco::Npm => {
55            let v: Value = serde_json::from_str(&std::fs::read_to_string(src.dir.join("package.json")).ok()?).ok()?;
56            let r = v.get("repository")?;
57            let (url, dir) = match r {
58                Value::String(s) => (s.clone(), None),
59                _ => (
60                    r.get("url")?.as_str()?.to_string(),
61                    r.get("directory").and_then(|d| d.as_str()).map(String::from),
62                ),
63            };
64            let (host, owner, name) = parse_repo(&url, any_host)?;
65            Some(Repo {
66                owner,
67                name,
68                subdir: dir,
69                host,
70            })
71        }
72        Eco::PyPI => {
73            let meta = std::fs::read_to_string(src.metadata.as_ref()?).ok()?;
74            let mut best: Option<(u8, RepoParts)> = None;
75            for line in meta.lines().take_while(|l| !l.trim().is_empty()) {
76                let (key, val) = line.split_once(':')?;
77                let (rank, url) = match key.trim() {
78                    "Project-URL" => {
79                        let (label, url) = val.split_once(',')?;
80                        let l = label.trim().to_ascii_lowercase();
81                        let rank = if ["source", "repository", "source code", "code", "github"].contains(&l.as_str()) {
82                            3
83                        } else {
84                            1
85                        };
86                        (rank, url.trim().to_string())
87                    }
88                    "Home-page" => (2, val.trim().to_string()),
89                    _ => continue,
90                };
91                if let Some(gh) = parse_repo(&url, any_host) {
92                    if best.as_ref().is_none_or(|b| rank > b.0) {
93                        best = Some((rank, gh));
94                    }
95                }
96            }
97            let (_, (host, owner, name)) = best?;
98            Some(Repo {
99                owner,
100                name,
101                subdir: None,
102                host,
103            })
104        }
105        Eco::Cargo => {
106            let t: toml::Table = toml::from_str(&std::fs::read_to_string(src.dir.join("Cargo.toml")).ok()?).ok()?;
107            let url = t.get("package")?.get("repository")?.as_str()?;
108            let (host, owner, name) = parse_repo(url, any_host)?;
109            Some(Repo {
110                owner,
111                name,
112                subdir: None,
113                host,
114            })
115        }
116        Eco::Go if any_host && !dep.name.starts_with("github.com/") && crate::private::go::is_private_module(&dep.name) => {
117            let (path, sub) = crate::private::go::split_module(&dep.name)?;
118            let (owner, name) = path.rsplit_once('/')?;
119            let host = dep.name.split('/').next()?;
120            let origin = crate::private::Url::parse(&format!("https://{host}/"))?.origin();
121            Some(Repo {
122                owner: owner.into(),
123                name: name.into(),
124                subdir: sub,
125                host: Some(origin),
126            })
127        }
128        Eco::Go => {
129            let rest = dep.name.strip_prefix("github.com/")?;
130            let mut it = rest.split('/');
131            let owner = it.next()?.to_string();
132            let name = it.next()?.to_string();
133            let sub: Vec<&str> = it.filter(|s| !(s.starts_with('v') && s[1..].chars().all(|c| c.is_ascii_digit()))).collect();
134            Some(Repo {
135                owner,
136                name,
137                subdir: if sub.is_empty() { None } else { Some(sub.join("/")) },
138                host: None,
139            })
140        }
141    }
142}