Skip to main content

oxi/storage/packages/
source.rs

1//! Source-spec parsing for the package system.
2//!
3//! Every package source string flows through `ParsedSource::parse`,
4//! which recognises npm specs, GitHub shorthand, raw git URLs, archive
5//! URLs, and local paths. Helpers (`parse_npm_spec`,
6//! `split_git_path_ref`, `parse_git_source`) are pure functions so they
7
8use serde::{Deserialize, Serialize};
9use std::sync::LazyLock;
10
11/// Parsed package source
12#[derive(Debug, Clone, Serialize, Deserialize)]
13#[serde(tag = "type", rename_all = "snake_case")]
14pub enum ParsedSource {
15    /// Variant.
16    Npm {
17        /// Full spec (e.g. "express@4.18.0")
18        spec: String,
19        /// Package name without version
20        name: String,
21        /// Whether a version was pinned
22        pinned: bool,
23    },
24    /// Variant.
25    Git {
26        /// Full repository URL
27        repo: String,
28        /// Host (e.g. "github.com")
29        host: String,
30        /// Path on host (e.g. "org/repo")
31        path: String,
32        /// Optional ref (branch / tag / commit)
33        ref_: Option<String>,
34    },
35    /// Variant.
36    Local {
37        /// Local path
38        path: String,
39    },
40    /// Variant.
41    Url {
42        /// URL to archive
43        url: String,
44    },
45}
46
47impl ParsedSource {
48    /// Parse a source string into a ParsedSource
49    pub fn parse(source: &str) -> Self {
50        if let Some(rest) = source.strip_prefix("npm:") {
51            let spec = rest.trim();
52            let (name, pinned) = parse_npm_spec(spec);
53            return ParsedSource::Npm {
54                spec: spec.to_string(),
55                name,
56                pinned,
57            };
58        }
59
60        if let Some(rest) = source.strip_prefix("github:") {
61            let parts: Vec<&str> = rest.splitn(2, '/').collect();
62            if parts.len() == 2 {
63                let (path, ref_) = split_git_path_ref(rest);
64                return ParsedSource::Git {
65                    repo: format!("https://github.com/{}.git", path),
66                    host: "github.com".to_string(),
67                    path,
68                    ref_,
69                };
70            }
71        }
72
73        if source.starts_with("git+") || source.starts_with("git://") || source.starts_with("git@")
74        {
75            return parse_git_source(source);
76        }
77
78        if source.starts_with("https://") || source.starts_with("http://") {
79            // Distinguish git URLs from plain archive URLs
80            if source.ends_with(".git")
81                || source.contains("github.com")
82                || source.contains("gitlab.com")
83            {
84                return parse_git_source(source);
85            }
86            // Archive URL (.tar.gz, .zip, .tgz)
87            if source.ends_with(".tar.gz")
88                || source.ends_with(".tgz")
89                || source.ends_with(".zip")
90                || source.ends_with(".tar.bz2")
91            {
92                return ParsedSource::Url {
93                    url: source.to_string(),
94                };
95            }
96            // Default to git for http(s) URLs that look like repos
97            return parse_git_source(source);
98        }
99
100        // Local path
101        ParsedSource::Local {
102            path: source.to_string(),
103        }
104    }
105
106    /// Get a unique identity key for this source (ignoring version/ref)
107    pub fn identity(&self) -> String {
108        match self {
109            ParsedSource::Npm { name, .. } => format!("npm:{}", name),
110            ParsedSource::Git { host, path, .. } => format!("git:{}/{}", host, path),
111            ParsedSource::Local { path } => format!("local:{}", path),
112            ParsedSource::Url { url } => format!("url:{}", url),
113        }
114    }
115
116    /// Get a display-friendly name
117    pub fn display_name(&self) -> String {
118        match self {
119            ParsedSource::Npm { name, .. } => name.clone(),
120            ParsedSource::Git { host, path, .. } => format!("{}/{}", host, path),
121            ParsedSource::Local { path } => path.clone(),
122            ParsedSource::Url { url } => url.clone(),
123        }
124    }
125}
126
127/// Cached regex for parsing npm package specs
128pub(super) static NPM_SPEC_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
129    regex::Regex::new(r"^(@?[^@]+(?:/[^@]+)?)(?:@(.+))?$").expect("valid static regex")
130});
131
132/// Parse an npm spec into (name, pinned)
133pub(super) fn parse_npm_spec(spec: &str) -> (String, bool) {
134    // Handle scoped packages like @scope/name@version
135    if let Some(caps) = NPM_SPEC_RE.captures(spec) {
136        let name = caps.get(1).map(|m| m.as_str()).unwrap_or(spec);
137        let has_version = caps.get(2).is_some();
138        return (name.to_string(), has_version);
139    }
140    (spec.to_string(), false)
141}
142
143/// Split a git path like "org/repo@ref" into ("org/repo", Some("ref"))
144pub(super) fn split_git_path_ref(input: &str) -> (String, Option<String>) {
145    if let Some(at_pos) = input.rfind('@') {
146        // Make sure it's not part of an email (don't split if there's no / before @)
147        if input[..at_pos].contains('/') {
148            return (
149                input[..at_pos].to_string(),
150                Some(input[at_pos + 1..].to_string()),
151            );
152        }
153    }
154    (input.to_string(), None)
155}
156
157/// Parse a git source string
158pub(super) fn parse_git_source(source: &str) -> ParsedSource {
159    // Handle git@host:path format (SSH)
160    if let Some(rest) = source.strip_prefix("git@") {
161        let colon_pos = rest.find(':').unwrap_or(rest.len());
162        let host = &rest[..colon_pos];
163        let path_part = rest.get(colon_pos + 1..).unwrap_or("");
164        let (path, ref_) = if let Some(hash_pos) = path_part.rfind('#') {
165            (
166                path_part[..hash_pos].to_string(),
167                Some(path_part[hash_pos + 1..].to_string()),
168            )
169        } else {
170            split_git_path_ref(path_part)
171        };
172        let repo = format!("git@{}:{}", host, path_part);
173        let host = host.to_string();
174        return ParsedSource::Git {
175            repo,
176            host,
177            path: path.trim_end_matches(".git").to_string(),
178            ref_,
179        };
180    }
181
182    // Handle git+ssh://, git+https://, git:// prefixes
183    let url_str = source
184        .strip_prefix("git+")
185        .unwrap_or(source)
186        .strip_prefix("git://")
187        .map(|s| format!("https://{}", s))
188        .unwrap_or_else(|| source.strip_prefix("git+").unwrap_or(source).to_string());
189
190    // Parse URL to extract host and path
191    let url = match url::Url::parse(&url_str) {
192        Ok(u) => u,
193        Err(_) => {
194            return ParsedSource::Local {
195                path: source.to_string(),
196            };
197        }
198    };
199
200    let host = url.host_str().unwrap_or("unknown").to_string();
201    let full_path = url.path().trim_start_matches('/').to_string();
202
203    // Check for #ref fragment
204    let fragment = url.fragment().map(|f| f.to_string());
205
206    let (path, ref_) = if let Some(frag) = fragment {
207        (full_path.trim_end_matches(".git").to_string(), Some(frag))
208    } else {
209        let (p, r) = split_git_path_ref(&full_path);
210        (p.trim_end_matches(".git").to_string(), r)
211    };
212
213    let repo = url_str.clone();
214
215    ParsedSource::Git {
216        repo,
217        host,
218        path,
219        ref_,
220    }
221}