mise 2026.4.11

The front-end to your dev env
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
use crate::backend::Backend;
use crate::backend::VersionInfo;
use crate::backend::backend_type::BackendType;
use crate::cli::args::BackendArg;
use crate::cmd::CmdLineRunner;
use crate::config::{Config, Settings};
use crate::git::{CloneOptions, Git};
use crate::install_context::InstallContext;
use crate::toolset::ToolVersion;
use crate::{dirs, file, github, gitlab};
use async_trait::async_trait;
use eyre::WrapErr;
use serde::Deserializer;
use serde::de::{MapAccess, Visitor};
use serde_derive::Deserialize;
use std::path::PathBuf;
use std::{
    fmt::{self, Debug},
    sync::Arc,
};
use strum::{AsRefStr, EnumString, VariantNames};
use url::Url;
use xx::regex;

/// SPM backend requires experimental mode to be enabled
pub const EXPERIMENTAL: bool = true;

#[derive(Debug)]
pub struct SPMBackend {
    ba: Arc<BackendArg>,
}

#[async_trait]
impl Backend for SPMBackend {
    fn get_type(&self) -> BackendType {
        BackendType::Spm
    }

    fn ba(&self) -> &Arc<BackendArg> {
        &self.ba
    }

    fn get_dependencies(&self) -> eyre::Result<Vec<&str>> {
        Ok(vec!["swift"])
    }

    async fn _list_remote_versions(&self, _config: &Arc<Config>) -> eyre::Result<Vec<VersionInfo>> {
        let provider = GitProvider::from_ba(&self.ba);
        let repo = SwiftPackageRepo::new(&self.tool_name(), &provider)?;
        let versions = match provider.kind {
            GitProviderKind::GitLab => {
                gitlab::list_releases_from_url(&provider.api_url, repo.shorthand.as_str())
                    .await?
                    .into_iter()
                    .map(|r| VersionInfo {
                        version: r.tag_name,
                        created_at: r.released_at,
                        ..Default::default()
                    })
                    .rev()
                    .collect()
            }
            _ => github::list_releases_from_url(&provider.api_url, repo.shorthand.as_str())
                .await?
                .into_iter()
                .map(|r| VersionInfo {
                    version: r.tag_name,
                    created_at: Some(r.created_at),
                    ..Default::default()
                })
                .rev()
                .collect(),
        };

        Ok(versions)
    }

    async fn install_version_(
        &self,
        ctx: &InstallContext,
        tv: ToolVersion,
    ) -> eyre::Result<ToolVersion> {
        let settings = Settings::get();
        settings.ensure_experimental("spm backend")?;

        // Check if swift is available
        self.warn_if_dependency_missing(
            &ctx.config,
            "swift",
            &["swift"],
            "To use Swift Package Manager (spm) tools with mise, you need to install Swift first:\n\
              mise use swift@latest\n\n\
            Or install Swift via https://swift.org/download/",
        )
        .await;
        let provider = GitProvider::from_ba(&self.ba);
        let repo = SwiftPackageRepo::new(&self.tool_name(), &provider)?;
        let revision = if tv.version == "latest" {
            self.latest_stable_version(&ctx.config)
                .await?
                .ok_or_else(|| eyre::eyre!("No stable versions found"))?
        } else {
            tv.version.clone()
        };
        let repo_dir = self.clone_package_repo(ctx, &tv, &repo, &revision)?;

        let executables = self.get_executable_names(ctx, &repo_dir, &tv).await?;
        if executables.is_empty() {
            return Err(eyre::eyre!("No executables found in the package"));
        }
        let bin_path = tv.install_path().join("bin");
        file::create_dir_all(&bin_path)?;
        for executable in executables {
            let exe_path = self
                .build_executable(&executable, &repo_dir, ctx, &tv)
                .await?;
            file::make_symlink(&exe_path, &bin_path.join(executable))?;
        }

        // delete (huge) intermediate artifacts
        file::remove_all(tv.install_path().join("repositories"))?;
        file::remove_all(tv.cache_path())?;

        Ok(tv)
    }
}

impl SPMBackend {
    pub fn from_arg(ba: BackendArg) -> Self {
        Self { ba: Arc::new(ba) }
    }

    fn clone_package_repo(
        &self,
        ctx: &InstallContext,
        tv: &ToolVersion,
        package_repo: &SwiftPackageRepo,
        revision: &str,
    ) -> Result<PathBuf, eyre::Error> {
        let repo = Git::new(tv.cache_path().join("repo"));
        if !repo.exists() {
            debug!(
                "Cloning swift package repo {} to {}",
                package_repo.url.as_str(),
                repo.dir.display(),
            );
            repo.clone(
                package_repo.url.as_str(),
                CloneOptions::default().pr(ctx.pr.as_ref()),
            )?;
        }
        debug!("Checking out revision: {revision}");
        repo.update_tag(revision.to_string())?;

        // Updates submodules ensuring they match the checked-out revision
        repo.update_submodules()?;

        Ok(repo.dir)
    }

    async fn get_executable_names(
        &self,
        ctx: &InstallContext,
        repo_dir: &PathBuf,
        tv: &ToolVersion,
    ) -> Result<Vec<String>, eyre::Error> {
        let package_json = cmd!(
            "swift",
            "package",
            "dump-package",
            "--package-path",
            &repo_dir,
            "--scratch-path",
            tv.install_path(),
            "--cache-path",
            dirs::CACHE.join("spm"),
        )
        .full_env(self.dependency_env(&ctx.config).await?)
        .read()?;
        let executables = serde_json::from_str::<PackageDescription>(&package_json)
            .wrap_err("Failed to parse package description")?
            .products
            .iter()
            .filter(|p| p.r#type.is_executable())
            .map(|p| p.name.clone())
            .collect::<Vec<String>>();
        debug!("Found executables: {:?}", executables);
        Ok(executables)
    }

    async fn build_executable(
        &self,
        executable: &str,
        repo_dir: &PathBuf,
        ctx: &InstallContext,
        tv: &ToolVersion,
    ) -> Result<PathBuf, eyre::Error> {
        debug!("Building swift package");
        CmdLineRunner::new("swift")
            .arg("build")
            .arg("--configuration")
            .arg("release")
            .arg("--product")
            .arg(executable)
            .arg("--scratch-path")
            .arg(tv.install_path())
            .arg("--package-path")
            .arg(repo_dir)
            .arg("--cache-path")
            .arg(dirs::CACHE.join("spm"))
            .with_pr(ctx.pr.as_ref())
            .prepend_path(
                self.dependency_toolset(&ctx.config)
                    .await?
                    .list_paths(&ctx.config)
                    .await,
            )?
            .execute()?;

        let bin_path = cmd!(
            "swift",
            "build",
            "--configuration",
            "release",
            "--product",
            &executable,
            "--package-path",
            &repo_dir,
            "--scratch-path",
            tv.install_path(),
            "--cache-path",
            dirs::CACHE.join("spm"),
            "--show-bin-path"
        )
        .full_env(self.dependency_env(&ctx.config).await?)
        .read()?;
        Ok(PathBuf::from(bin_path.trim().to_string()).join(executable))
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GitProvider {
    pub api_url: String,
    pub kind: GitProviderKind,
}

impl Default for GitProvider {
    fn default() -> Self {
        Self {
            api_url: github::API_URL.to_string(),
            kind: GitProviderKind::GitHub,
        }
    }
}

#[derive(AsRefStr, Clone, Debug, Eq, PartialEq, EnumString, VariantNames)]
pub enum GitProviderKind {
    #[strum(serialize = "github")]
    GitHub,
    #[strum(serialize = "gitlab")]
    GitLab,
}

impl GitProvider {
    fn from_ba(ba: &BackendArg) -> Self {
        let opts = ba.opts();

        let provider = opts
            .get("provider")
            .unwrap_or(GitProviderKind::GitHub.as_ref());
        let kind = if ba.tool_name.contains("gitlab.com") {
            GitProviderKind::GitLab
        } else {
            match provider.to_lowercase().as_str() {
                "gitlab" => GitProviderKind::GitLab,
                _ => GitProviderKind::GitHub,
            }
        };

        let api_url = match opts.get("api_url") {
            Some(api_url) => api_url.trim_end_matches('/').to_string(),
            None => {
                Self::derive_api_url_from_tool_name(&ba.tool_name, &kind).unwrap_or_else(|| {
                    match kind {
                        GitProviderKind::GitHub => github::API_URL.to_string(),
                        GitProviderKind::GitLab => gitlab::API_URL.to_string(),
                    }
                })
            }
        };

        Self { api_url, kind }
    }

    /// When the tool name is a full URL pointing to a self-hosted instance,
    /// derive the API URL from the host instead of falling back to the public API.
    fn derive_api_url_from_tool_name(tool_name: &str, kind: &GitProviderKind) -> Option<String> {
        let name = tool_name.strip_prefix("spm:").unwrap_or(tool_name);
        let url = Url::parse(name).ok()?;
        let host = url.host_str()?;
        match host {
            "github.com" | "gitlab.com" => None,
            _ => {
                let api_path = match kind {
                    GitProviderKind::GitHub => github::API_PATH,
                    GitProviderKind::GitLab => gitlab::API_PATH,
                };
                let mut api_url = url.clone();
                api_url.set_path(api_path);
                Some(api_url.as_str().trim_end_matches('/').to_string())
            }
        }
    }
}

#[derive(Debug)]
struct SwiftPackageRepo {
    /// https://github.com/owner/repo.git
    url: Url,
    /// owner/repo_name
    shorthand: String,
}

impl SwiftPackageRepo {
    /// Parse the slug or the full URL of a GitHub package repository.
    fn new(name: &str, provider: &GitProvider) -> Result<Self, eyre::Error> {
        let name = name.strip_prefix("spm:").unwrap_or(name);
        let shorthand_regex = regex!(r"^(?:[a-zA-Z0-9_-]+/)+[a-zA-Z0-9._-]+$");
        let shorthand_in_url_regex = regex!(
            r"^https://(?P<domain>[^/]+)/(?P<shorthand>(?:[a-zA-Z0-9_-]+/)+[a-zA-Z0-9._-]+)\.git"
        );

        let (shorthand, url) = if let Some(caps) = shorthand_in_url_regex.captures(name) {
            let shorthand = caps.name("shorthand").unwrap().as_str();
            let url = Url::parse(name)?;
            (shorthand, url)
        } else if shorthand_regex.is_match(name) {
            let host = match provider.kind {
                GitProviderKind::GitHub => "github.com",
                GitProviderKind::GitLab => "gitlab.com",
            };
            let url_str = format!("https://{}/{}.git", host, name);
            let url = Url::parse(&url_str)?;
            (name, url)
        } else {
            Err(eyre::eyre!(
                "Invalid Swift package repository: {}. The repository should either be a repository slug (owner/name), or the complete URL (e.g. https://github.com/owner/name.git).",
                name
            ))?
        };

        Ok(Self {
            url,
            shorthand: shorthand.to_string(),
        })
    }
}

#[cfg(test)]
mod tests {
    use crate::cli::args::BackendResolution;
    use crate::{config::Config, toolset::ToolVersionOptions};

    use super::*;
    use indexmap::indexmap;
    use pretty_assertions::assert_str_eq;

    #[tokio::test]
    async fn test_git_provider_from_ba() {
        // Example of defining a capture (closure) in Rust:
        let get_ba = |tool: String, opts: Option<ToolVersionOptions>| {
            BackendArg::new_raw(
                "spm".to_string(),
                Some(tool.clone()),
                tool,
                opts,
                BackendResolution::new(true),
            )
        };

        assert_eq!(
            GitProvider::from_ba(&get_ba("tool".to_string(), None)),
            GitProvider {
                api_url: github::API_URL.to_string(),
                kind: GitProviderKind::GitHub
            }
        );

        assert_eq!(
            GitProvider::from_ba(&get_ba(
                "tool".to_string(),
                Some(ToolVersionOptions {
                    opts: indexmap![
                        "provider".to_string() => toml::Value::String("gitlab".to_string())
                    ],
                    ..Default::default()
                })
            )),
            GitProvider {
                api_url: gitlab::API_URL.to_string(),
                kind: GitProviderKind::GitLab
            }
        );

        assert_eq!(
            GitProvider::from_ba(&get_ba(
                "tool".to_string(),
                Some(ToolVersionOptions {
                    opts: indexmap![
                        "api_url".to_string() => toml::Value::String("https://gitlab.acme.com/api/v4".to_string()),
                        "provider".to_string() => toml::Value::String("gitlab".to_string()),
                    ],
                    ..Default::default()
                })
            )),
            GitProvider {
                api_url: "https://gitlab.acme.com/api/v4".to_string(),
                kind: GitProviderKind::GitLab
            }
        );

        // Self-hosted GitHub Enterprise URL without api_url -> should derive from host
        assert_eq!(
            GitProvider::from_ba(&get_ba(
                "https://github.acme.com/org/Tool.git".to_string(),
                None
            )),
            GitProvider {
                api_url: "https://github.acme.com/api/v3".to_string(),
                kind: GitProviderKind::GitHub
            }
        );

        // Self-hosted GitLab URL without api_url -> should derive from host
        assert_eq!(
            GitProvider::from_ba(&get_ba(
                "https://gitlab.acme.com/org/Tool.git".to_string(),
                Some(ToolVersionOptions {
                    opts: indexmap![
                        "provider".to_string() => toml::Value::String("gitlab".to_string())
                    ],
                    ..Default::default()
                })
            )),
            GitProvider {
                api_url: "https://gitlab.acme.com/api/v4".to_string(),
                kind: GitProviderKind::GitLab
            }
        );

        // github.com URL without api_url -> should use default
        assert_eq!(
            GitProvider::from_ba(&get_ba("https://github.com/org/Tool.git".to_string(), None)),
            GitProvider {
                api_url: github::API_URL.to_string(),
                kind: GitProviderKind::GitHub
            }
        );

        // Explicit api_url should take precedence over derived URL
        assert_eq!(
            GitProvider::from_ba(&get_ba(
                "https://github.acme.com/org/Tool.git".to_string(),
                Some(ToolVersionOptions {
                    opts: indexmap![
                        "api_url".to_string() => toml::Value::String("https://custom-api.acme.com/v3".to_string())
                    ],
                    ..Default::default()
                })
            )),
            GitProvider {
                api_url: "https://custom-api.acme.com/v3".to_string(),
                kind: GitProviderKind::GitHub
            }
        );
    }

    #[tokio::test]
    async fn test_spm_repo_init_by_shorthand() {
        let _config = Config::get().await.unwrap();
        let package_repo =
            SwiftPackageRepo::new("nicklockwood/SwiftFormat", &GitProvider::default()).unwrap();
        assert_str_eq!(
            package_repo.url.as_str(),
            "https://github.com/nicklockwood/SwiftFormat.git"
        );
        assert_str_eq!(package_repo.shorthand, "nicklockwood/SwiftFormat");

        let package_repo = SwiftPackageRepo::new(
            "acme/nicklockwood/SwiftFormat",
            &GitProvider {
                api_url: gitlab::API_URL.to_string(),
                kind: GitProviderKind::GitLab,
            },
        )
        .unwrap();
        assert_str_eq!(
            package_repo.url.as_str(),
            "https://gitlab.com/acme/nicklockwood/SwiftFormat.git"
        );
        assert_str_eq!(package_repo.shorthand, "acme/nicklockwood/SwiftFormat");
    }

    #[tokio::test]
    async fn test_spm_repo_init_name() {
        let _config = Config::get().await.unwrap();
        assert!(
            SwiftPackageRepo::new("owner/name.swift", &GitProvider::default()).is_ok(),
            "name part can contain ."
        );
        assert!(
            SwiftPackageRepo::new("owner/name_swift", &GitProvider::default()).is_ok(),
            "name part can contain _"
        );
        assert!(
            SwiftPackageRepo::new("owner/name-swift", &GitProvider::default()).is_ok(),
            "name part can contain -"
        );
        assert!(
            SwiftPackageRepo::new("owner/name$swift", &GitProvider::default()).is_err(),
            "name part cannot contain characters other than a-zA-Z0-9._-"
        );
    }

    #[tokio::test]
    async fn test_spm_repo_init_by_url() {
        let package_repo = SwiftPackageRepo::new(
            "https://github.com/nicklockwood/SwiftFormat.git",
            &GitProvider::default(),
        )
        .unwrap();
        assert_str_eq!(
            package_repo.url.as_str(),
            "https://github.com/nicklockwood/SwiftFormat.git"
        );
        assert_str_eq!(package_repo.shorthand, "nicklockwood/SwiftFormat");

        let package_repo = SwiftPackageRepo::new(
            "https://gitlab.acme.com/acme/someuser/SwiftTool.git",
            &GitProvider {
                api_url: "https://api.gitlab.acme.com/api/v4".to_string(),
                kind: GitProviderKind::GitLab,
            },
        )
        .unwrap();
        assert_str_eq!(
            package_repo.url.as_str(),
            "https://gitlab.acme.com/acme/someuser/SwiftTool.git"
        );
        assert_str_eq!(package_repo.shorthand, "acme/someuser/SwiftTool");
    }
}

/// https://developer.apple.com/documentation/packagedescription
#[derive(Deserialize)]
struct PackageDescription {
    products: Vec<PackageDescriptionProduct>,
}

#[derive(Deserialize)]
struct PackageDescriptionProduct {
    name: String,
    #[serde(deserialize_with = "PackageDescriptionProductType::deserialize_product_type_field")]
    r#type: PackageDescriptionProductType,
}

#[derive(Deserialize)]
enum PackageDescriptionProductType {
    Executable,
    Other,
}

impl PackageDescriptionProductType {
    fn is_executable(&self) -> bool {
        matches!(self, Self::Executable)
    }

    /// Swift determines the toolchain to use with a given package using a comment in the Package.swift file at the top.
    /// For example:
    ///   // swift-tools-version: 6.0
    ///
    /// The version of the toolchain can be older than the Swift version used to build the package. This versioning gives
    /// Apple the flexibility to introduce and flag breaking changes in the toolchain.
    ///
    /// How to determine the product type is something that might change across different versions of Swift.
    ///
    /// ## Swift 5.x
    ///
    /// Product type is a key in the map with an undocumented value that we are not interested in and can be easily skipped.
    ///
    /// Example:
    /// ```json
    /// "type" : {
    ///     "executable" : null
    /// }
    /// ```
    /// or
    /// ```json
    /// "type" : {
    ///     "library" : [
    ///       "automatic"
    ///     ]
    /// }
    /// ```
    ///
    /// ## Swift 6.x
    ///
    /// The product type is directly the value under the key "type"
    ///
    /// Example:
    ///
    /// ```json
    /// "type": "executable"
    /// ```
    ///
    fn deserialize_product_type_field<'de, D>(
        deserializer: D,
    ) -> Result<PackageDescriptionProductType, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct TypeFieldVisitor;

        impl<'de> Visitor<'de> for TypeFieldVisitor {
            type Value = PackageDescriptionProductType;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("a map with a key 'executable' or other types")
            }

            fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error>
            where
                V: MapAccess<'de>,
            {
                if let Some(key) = map.next_key::<String>()? {
                    match key.as_str() {
                        "type" => {
                            let value: String = map.next_value()?;
                            if value == "executable" {
                                Ok(PackageDescriptionProductType::Executable)
                            } else {
                                Ok(PackageDescriptionProductType::Other)
                            }
                        }
                        "executable" => {
                            // Skip the value by reading it into a dummy serde_json::Value
                            let _value: serde_json::Value = map.next_value()?;
                            Ok(PackageDescriptionProductType::Executable)
                        }
                        _ => {
                            let _value: serde_json::Value = map.next_value()?;
                            Ok(PackageDescriptionProductType::Other)
                        }
                    }
                } else {
                    Err(serde::de::Error::custom("missing key"))
                }
            }
        }

        deserializer.deserialize_map(TypeFieldVisitor)
    }
}