aboutsummaryrefslogtreecommitdiffhomepage
path: root/crates/mozart-core/src/vcs/driver/mod.rs
blob: cfaf11ed3edd792b1a43df273c43d2ff014fb726 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
pub mod bitbucket;
pub mod forgejo;
pub mod git;
pub mod github;
pub mod gitlab;
pub mod hg;
pub mod svn;

use std::collections::BTreeMap;
use std::path::PathBuf;

use anyhow::Result;
use serde::{Deserialize, Serialize};

/// Reference to a source distribution.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SourceReference {
    #[serde(rename = "type")]
    pub source_type: String,
    pub url: String,
    pub reference: String,
}

/// Reference to a dist (archive) distribution.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DistReference {
    #[serde(rename = "type")]
    pub dist_type: String,
    pub url: String,
    pub reference: String,
    pub shasum: Option<String>,
}

/// Configuration passed to VCS drivers.
#[derive(Debug, Clone)]
pub struct DriverConfig {
    /// Composer's `cache-vcs-dir`: root for VCS mirrors, one
    /// subdirectory per sanitized repository URL.
    pub cache_vcs_dir: PathBuf,
    /// GitHub OAuth token (from `GITHUB_TOKEN` or config).
    pub github_token: Option<String>,
    /// GitLab OAuth token.
    pub gitlab_token: Option<String>,
    /// Bitbucket OAuth consumer key/secret.
    pub bitbucket_oauth: Option<(String, String)>,
    /// Forgejo token.
    pub forgejo_token: Option<String>,
    /// Custom GitLab domains (for self-hosted).
    pub gitlab_domains: Vec<String>,
    /// Custom Forgejo domains (for self-hosted).
    pub forgejo_domains: Vec<String>,
}

impl Default for DriverConfig {
    fn default() -> Self {
        Self {
            cache_vcs_dir: default_cache_vcs_dir(),
            github_token: None,
            gitlab_token: None,
            bitbucket_oauth: None,
            forgejo_token: None,
            gitlab_domains: vec!["gitlab.com".to_string()],
            forgejo_domains: vec!["codeberg.org".to_string()],
        }
    }
}

/// Resolve the default `cache-vcs-dir`, honoring Composer's env vars.
///
/// Priority: `COMPOSER_CACHE_VCS_DIR` → `COMPOSER_CACHE_DIR/vcs` →
/// `XDG_CACHE_HOME/mozart/vcs` → `$HOME/.cache/mozart/vcs`.
fn default_cache_vcs_dir() -> PathBuf {
    if let Ok(p) = std::env::var("COMPOSER_CACHE_VCS_DIR") {
        return PathBuf::from(p);
    }
    let base = if let Ok(p) = std::env::var("COMPOSER_CACHE_DIR") {
        PathBuf::from(p)
    } else if let Ok(xdg) = std::env::var("XDG_CACHE_HOME") {
        PathBuf::from(xdg).join("mozart")
    } else if let Ok(home) = std::env::var("HOME") {
        PathBuf::from(home).join(".cache").join("mozart")
    } else {
        PathBuf::from("/tmp").join("mozart")
    };
    base.join("vcs")
}

/// Type of VCS driver.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DriverType {
    GitHub,
    GitLab,
    Bitbucket,
    Forgejo,
    Git,
    Svn,
    Hg,
}

/// The VCS driver interface.
///
/// Corresponds to Composer's `VcsDriverInterface`.
trait VcsDriver {
    /// Initialize the driver (e.g., clone mirror, fetch API metadata).
    async fn initialize(&mut self) -> Result<()>;

    /// The root identifier (default branch/trunk).
    fn root_identifier(&self) -> &str;

    /// All branches as `name -> commit_hash`.
    async fn branches(&mut self) -> Result<&BTreeMap<String, String>>;

    /// All tags as `name -> commit_hash`.
    async fn tags(&mut self) -> Result<&BTreeMap<String, String>>;

    /// Get composer.json content parsed as JSON for a given identifier.
    async fn composer_information(&mut self, identifier: &str)
    -> Result<Option<serde_json::Value>>;

    /// Get raw file content at a given path and identifier.
    async fn file_content(&self, file: &str, identifier: &str) -> Result<Option<String>>;

    /// Get the change date for a given identifier (ISO 8601).
    async fn change_date(&self, identifier: &str) -> Result<Option<String>>;

    /// Get the dist reference for a given identifier.
    async fn dist(&self, identifier: &str) -> Result<Option<DistReference>>;

    /// Get the source reference for a given identifier.
    fn source(&self, identifier: &str) -> SourceReference;

    /// The canonical URL of this repository.
    fn url(&self) -> &str;

    /// Clean up resources (temp dirs, etc.).
    async fn cleanup(&mut self) -> Result<()>;
}

/// Enum-dispatched VCS driver.
///
/// Wraps all concrete driver types to allow static dispatch with async trait methods.
pub enum AnyVcsDriver {
    GitHub(github::GitHubDriver),
    GitLab(gitlab::GitLabDriver),
    Bitbucket(bitbucket::BitbucketDriver),
    Forgejo(forgejo::ForgejoDriver),
    Git(git::GitDriver),
    Svn(svn::SvnDriver),
    Hg(hg::HgDriver),
}

macro_rules! dispatch {
    ($self:expr, $method:ident $(, $arg:expr)*) => {
        match $self {
            AnyVcsDriver::GitHub(d) => d.$method($($arg),*),
            AnyVcsDriver::GitLab(d) => d.$method($($arg),*),
            AnyVcsDriver::Bitbucket(d) => d.$method($($arg),*),
            AnyVcsDriver::Forgejo(d) => d.$method($($arg),*),
            AnyVcsDriver::Git(d) => d.$method($($arg),*),
            AnyVcsDriver::Svn(d) => d.$method($($arg),*),
            AnyVcsDriver::Hg(d) => d.$method($($arg),*),
        }
    };
}

macro_rules! dispatch_async {
    ($self:expr, $method:ident $(, $arg:expr)*) => {
        match $self {
            AnyVcsDriver::GitHub(d) => d.$method($($arg),*).await,
            AnyVcsDriver::GitLab(d) => d.$method($($arg),*).await,
            AnyVcsDriver::Bitbucket(d) => d.$method($($arg),*).await,
            AnyVcsDriver::Forgejo(d) => d.$method($($arg),*).await,
            AnyVcsDriver::Git(d) => d.$method($($arg),*).await,
            AnyVcsDriver::Svn(d) => d.$method($($arg),*).await,
            AnyVcsDriver::Hg(d) => d.$method($($arg),*).await,
        }
    };
}

impl AnyVcsDriver {
    pub async fn initialize(&mut self) -> Result<()> {
        dispatch_async!(self, initialize)
    }

    pub fn root_identifier(&self) -> &str {
        dispatch!(self, root_identifier)
    }

    pub async fn branches(&mut self) -> Result<&BTreeMap<String, String>> {
        dispatch_async!(self, branches)
    }

    pub async fn tags(&mut self) -> Result<&BTreeMap<String, String>> {
        dispatch_async!(self, tags)
    }

    pub async fn composer_information(
        &mut self,
        identifier: &str,
    ) -> Result<Option<serde_json::Value>> {
        dispatch_async!(self, composer_information, identifier)
    }

    pub async fn file_content(&self, file: &str, identifier: &str) -> Result<Option<String>> {
        dispatch_async!(self, file_content, file, identifier)
    }

    pub async fn change_date(&self, identifier: &str) -> Result<Option<String>> {
        dispatch_async!(self, change_date, identifier)
    }

    pub async fn dist(&self, identifier: &str) -> Result<Option<DistReference>> {
        dispatch_async!(self, dist, identifier)
    }

    pub fn source(&self, identifier: &str) -> SourceReference {
        dispatch!(self, source, identifier)
    }

    pub fn url(&self) -> &str {
        dispatch!(self, url)
    }

    pub async fn cleanup(&mut self) -> Result<()> {
        dispatch_async!(self, cleanup)
    }
}

/// Detect which driver type should handle a given URL.
///
/// Priority order matches Composer:
/// 1. GitHub → 2. GitLab → 3. Bitbucket → 4. Forgejo → 5. Git → 6. Hg → 7. SVN
pub fn detect_driver(
    url: &str,
    forced_type: Option<&str>,
    config: &DriverConfig,
) -> Option<DriverType> {
    if let Some(t) = forced_type {
        return match t {
            "github" => Some(DriverType::GitHub),
            "gitlab" => Some(DriverType::GitLab),
            "bitbucket" => Some(DriverType::Bitbucket),
            "forgejo" => Some(DriverType::Forgejo),
            "git" => Some(DriverType::Git),
            "svn" => Some(DriverType::Svn),
            "hg" | "mercurial" => Some(DriverType::Hg),
            _ => None,
        };
    }

    let url_lower = url.to_lowercase();

    // GitHub
    if github::GitHubDriver::supports(url) {
        return Some(DriverType::GitHub);
    }

    // GitLab
    if gitlab::GitLabDriver::supports(url, &config.gitlab_domains) {
        return Some(DriverType::GitLab);
    }

    // Bitbucket
    if bitbucket::BitbucketDriver::supports(url) {
        return Some(DriverType::Bitbucket);
    }

    // Forgejo
    if forgejo::ForgejoDriver::supports(url, &config.forgejo_domains) {
        return Some(DriverType::Forgejo);
    }

    // Git
    if git::GitDriver::supports(url) {
        return Some(DriverType::Git);
    }

    // Hg
    if hg::HgDriver::supports(url) {
        return Some(DriverType::Hg);
    }

    // SVN
    if url_lower.contains("svn") || svn::SvnDriver::supports(url) {
        return Some(DriverType::Svn);
    }

    // Default to git for generic URLs
    if url.starts_with("http://") || url.starts_with("https://") {
        return Some(DriverType::Git);
    }

    None
}

/// Create a driver instance for the given URL and type.
pub fn create_driver(url: &str, driver_type: DriverType, config: DriverConfig) -> AnyVcsDriver {
    match driver_type {
        DriverType::GitHub => AnyVcsDriver::GitHub(github::GitHubDriver::new(url, config)),
        DriverType::GitLab => AnyVcsDriver::GitLab(gitlab::GitLabDriver::new(url, config)),
        DriverType::Bitbucket => {
            AnyVcsDriver::Bitbucket(bitbucket::BitbucketDriver::new(url, config))
        }
        DriverType::Forgejo => AnyVcsDriver::Forgejo(forgejo::ForgejoDriver::new(url, config)),
        DriverType::Git => AnyVcsDriver::Git(git::GitDriver::new(url, config)),
        DriverType::Svn => AnyVcsDriver::Svn(svn::SvnDriver::new(url, config)),
        DriverType::Hg => AnyVcsDriver::Hg(hg::HgDriver::new(url, config)),
    }
}