mise 2026.5.17

Dev tools, env vars, and tasks in one CLI
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
use crate::config::Settings;
use eyre::{Result, bail};
use std::fmt;

/// Represents a target platform for lockfile operations
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Platform {
    pub os: String,
    pub arch: String,
    pub qualifier: Option<String>,
}

impl Platform {
    /// Parse a platform string in the format "os-arch" or "os-arch-qualifier"
    /// Qualifier may contain hyphens (e.g., "musl-baseline")
    pub fn parse(platform_str: &str) -> Result<Self> {
        let parts: Vec<&str> = platform_str.split('-').collect();

        match parts.len() {
            0 | 1 => bail!(
                "Invalid platform format '{}'. Expected 'os-arch' or 'os-arch-qualifier'",
                platform_str
            ),
            2 => Ok(Platform {
                os: parts[0].to_string(),
                arch: parts[1].to_string(),
                qualifier: None,
            }),
            _ => {
                // Join remaining parts as qualifier (handles compound qualifiers like "musl-baseline")
                let qualifier = parts[2..].join("-");
                Ok(Platform {
                    os: parts[0].to_string(),
                    arch: parts[1].to_string(),
                    qualifier: Some(qualifier),
                })
            }
        }
    }

    /// Get the current platform from system information.
    /// On Linux, detects musl vs glibc at runtime and sets the qualifier accordingly.
    pub fn current() -> Self {
        let settings = Settings::get();
        let os = settings.os().to_string();
        let qualifier = if os == "linux" {
            match settings.libc() {
                Some("musl") => Some("musl".to_string()),
                Some("gnu") => None,
                _ if is_musl_system() => Some("musl".to_string()),
                _ => None,
            }
        } else {
            None
        };
        Platform {
            os,
            arch: settings.arch().to_string(),
            qualifier,
        }
    }

    pub fn libc(&self) -> Option<&str> {
        self.qualifier
            .as_deref()?
            .split('-')
            .find_map(|part| match part {
                "gnu" | "glibc" => Some("gnu"),
                "musl" => Some("musl"),
                _ => None,
            })
    }

    /// Validate that this platform is supported
    pub fn validate(&self) -> Result<()> {
        // Validate OS
        match self.os.as_str() {
            "linux" | "macos" | "windows" => {}
            _ => bail!(
                "Unsupported OS '{}'. Supported: linux, macos, windows",
                self.os
            ),
        }

        // Validate architecture
        match self.arch.as_str() {
            "x64" | "arm64" | "x86" | "loongarch64" | "riscv64" => {}
            _ => bail!(
                "Unsupported architecture '{}'. Supported: x64, arm64, x86, loongarch64, riscv64",
                self.arch
            ),
        }

        // Validate qualifier if present
        if let Some(qualifier) = &self.qualifier {
            match qualifier.as_str() {
                "gnu" | "glibc" | "musl" | "msvc" | "baseline" | "musl-baseline" => {}
                _ => bail!(
                    "Unsupported qualifier '{}'. Supported: gnu, glibc, musl, msvc, baseline, musl-baseline",
                    qualifier
                ),
            }
        }

        Ok(())
    }

    /// Check if this platform is compatible with the current system
    pub fn is_compatible_with_current(&self) -> bool {
        let current = Self::current();
        self.os == current.os && self.arch == current.arch
    }

    /// Convert to platform key format used in lockfiles
    pub fn to_key(&self) -> String {
        match &self.qualifier {
            Some(qualifier) => format!("{}-{}-{}", self.os, self.arch, qualifier),
            None => format!("{}-{}", self.os, self.arch),
        }
    }

    /// Parse multiple platform strings, validating each one
    pub fn parse_multiple(platform_strings: &[String]) -> Result<Vec<Self>> {
        let mut platforms = Vec::new();

        for platform_str in platform_strings {
            let platform = Self::parse(platform_str)?;
            platform.validate()?;
            platforms.push(platform);
        }

        // Remove duplicates and sort
        platforms.sort();
        platforms.dedup();

        Ok(platforms)
    }

    /// Get a list of commonly supported platforms
    pub fn common_platforms() -> Vec<Self> {
        vec![
            Platform::parse("linux-x64").unwrap(),
            Platform::parse("linux-x64-musl").unwrap(),
            Platform::parse("linux-arm64").unwrap(),
            Platform::parse("linux-arm64-musl").unwrap(),
            Platform::parse("macos-x64").unwrap(),
            Platform::parse("macos-arm64").unwrap(),
            Platform::parse("windows-x64").unwrap(),
        ]
    }

    /// Check if this is a Windows platform
    pub fn is_windows(&self) -> bool {
        self.os == "windows"
    }

    /// Check if this is a macOS platform
    pub fn is_macos(&self) -> bool {
        self.os == "macos"
    }

    /// Check if this is a Linux platform
    pub fn is_linux(&self) -> bool {
        self.os == "linux"
    }

    /// Check if this uses ARM64 architecture
    pub fn is_arm64(&self) -> bool {
        self.arch == "arm64"
    }

    /// Check if this uses x64 architecture
    pub fn is_x64(&self) -> bool {
        self.arch == "x64"
    }
}

impl fmt::Display for Platform {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_key())
    }
}

impl From<String> for Platform {
    fn from(s: String) -> Self {
        Self::parse(&s).unwrap_or_else(|_| {
            // Fallback to current platform if parsing fails
            Self::current()
        })
    }
}

impl From<&str> for Platform {
    fn from(s: &str) -> Self {
        Self::parse(s).unwrap_or_else(|_| {
            // Fallback to current platform if parsing fails
            Self::current()
        })
    }
}

/// Detect the current libc variant on Linux.
///
/// Returns `Some("gnu")` on glibc Linux, `Some("musl")` on musl Linux,
/// `None` on non-Linux or when the variant can't be determined (e.g. minimal
/// containers compiled against an unusual target_env).
///
/// Detection order on Linux:
///   1. `/etc/os-release` ID/ID_LIKE — strong signal for known musl distros.
///      Necessary because compat shims like `gcompat` on Alpine install
///      `/lib/ld-linux-*` alongside `/lib/ld-musl-*`, which would otherwise
///      cause the linker-based fallback to misclassify the system as glibc.
///   2. Linker file presence in `/lib` and `/lib64`.
///   3. Compile-time target (`target_env`) — for scratch/busybox containers
///      with no linker files.
#[cfg(target_os = "linux")]
pub fn detect_libc() -> Option<&'static str> {
    use std::sync::LazyLock;
    static DETECTED: LazyLock<Option<&'static str>> = LazyLock::new(|| {
        if let Some(true) = musl_from_os_release("/etc/os-release") {
            return Some("musl");
        }
        for dir in ["/lib", "/lib64"] {
            if has_file_prefix(dir, "ld-linux-") {
                return Some("gnu");
            }
        }
        for dir in ["/lib", "/lib64"] {
            if has_file_prefix(dir, "ld-musl-") {
                return Some("musl");
            }
        }
        if cfg!(target_env = "musl") {
            return Some("musl");
        }
        if cfg!(target_env = "gnu") {
            return Some("gnu");
        }
        None
    });
    *DETECTED
}

#[cfg(not(target_os = "linux"))]
pub fn detect_libc() -> Option<&'static str> {
    None
}

#[cfg(target_os = "linux")]
fn musl_from_os_release(path: &str) -> Option<bool> {
    let content = std::fs::read_to_string(path).ok()?;
    let mut ids: Vec<String> = Vec::new();
    for line in content.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let Some((key, value)) = line.split_once('=') else {
            continue;
        };
        let key = key.trim();
        if key == "ID" || key == "ID_LIKE" {
            let value = value.trim().trim_matches('"').trim_matches('\'');
            ids.extend(value.split_whitespace().map(str::to_string));
        }
    }
    // Known musl-libc distros. Compat shims (gcompat) don't change this — the
    // underlying libc is still musl.
    const MUSL_DISTROS: &[&str] = &["alpine", "postmarketos", "chimera"];
    if ids.iter().any(|id| MUSL_DISTROS.contains(&id.as_str())) {
        return Some(true);
    }
    None
}

#[cfg(target_os = "linux")]
fn has_file_prefix(dir: &str, prefix: &str) -> bool {
    std::fs::read_dir(dir)
        .map(|entries| {
            entries
                .flatten()
                .any(|e| e.file_name().to_string_lossy().starts_with(prefix))
        })
        .unwrap_or(false)
}

fn is_musl_system() -> bool {
    detect_libc() == Some("musl")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_platform_parse_basic() {
        let platform = Platform::parse("linux-x64").unwrap();
        assert_eq!(platform.os, "linux");
        assert_eq!(platform.arch, "x64");
        assert_eq!(platform.qualifier, None);
    }

    #[test]
    fn test_platform_parse_with_qualifier() {
        let platform = Platform::parse("linux-x64-gnu").unwrap();
        assert_eq!(platform.os, "linux");
        assert_eq!(platform.arch, "x64");
        assert_eq!(platform.qualifier, Some("gnu".to_string()));
    }

    #[test]
    fn test_platform_parse_with_compound_qualifier() {
        // Compound qualifiers like "musl-baseline" should parse correctly
        let platform = Platform::parse("linux-x64-musl-baseline").unwrap();
        assert_eq!(platform.os, "linux");
        assert_eq!(platform.arch, "x64");
        assert_eq!(platform.qualifier, Some("musl-baseline".to_string()));

        // Verify round-trip: parse -> to_key -> parse
        assert_eq!(platform.to_key(), "linux-x64-musl-baseline");
        let reparsed = Platform::parse(&platform.to_key()).unwrap();
        assert_eq!(reparsed.qualifier, Some("musl-baseline".to_string()));
    }

    #[test]
    fn test_platform_parse_invalid() {
        assert!(Platform::parse("linux").is_err());
        assert!(Platform::parse("").is_err());
    }

    #[test]
    fn test_platform_validation() {
        // Valid platforms
        assert!(Platform::parse("linux-x64").unwrap().validate().is_ok());
        assert!(Platform::parse("macos-arm64").unwrap().validate().is_ok());
        assert!(Platform::parse("windows-x64").unwrap().validate().is_ok());
        assert!(Platform::parse("linux-x64-gnu").unwrap().validate().is_ok());
        assert!(
            Platform::parse("linux-x64-glibc")
                .unwrap()
                .validate()
                .is_ok()
        );

        // Invalid OS
        assert!(Platform::parse("invalid-x64").unwrap().validate().is_err());

        // Invalid arch
        assert!(
            Platform::parse("linux-invalid")
                .unwrap()
                .validate()
                .is_err()
        );

        // Invalid qualifier
        assert!(
            Platform::parse("linux-x64-invalid")
                .unwrap()
                .validate()
                .is_err()
        );
    }

    #[test]
    fn test_platform_to_key() {
        let platform1 = Platform::parse("linux-x64").unwrap();
        assert_eq!(platform1.to_key(), "linux-x64");

        let platform2 = Platform::parse("linux-x64-gnu").unwrap();
        assert_eq!(platform2.to_key(), "linux-x64-gnu");
    }

    #[test]
    fn test_platform_multiple_parsing() {
        let platform_strings = vec![
            "linux-x64".to_string(),
            "macos-arm64".to_string(),
            "linux-x64".to_string(), // duplicate should be removed
        ];

        let platforms = Platform::parse_multiple(&platform_strings).unwrap();
        assert_eq!(platforms.len(), 2);
        assert_eq!(platforms[0].to_key(), "linux-x64");
        assert_eq!(platforms[1].to_key(), "macos-arm64");
    }

    #[test]
    fn test_platform_helpers() {
        let linux_platform = Platform::parse("linux-arm64").unwrap();
        assert!(linux_platform.is_linux());
        assert!(linux_platform.is_arm64());
        assert!(!linux_platform.is_windows());
        assert!(!linux_platform.is_x64());

        let windows_platform = Platform::parse("windows-x64").unwrap();
        assert!(windows_platform.is_windows());
        assert!(windows_platform.is_x64());
        assert!(!windows_platform.is_linux());
        assert!(!windows_platform.is_arm64());
    }

    #[test]
    fn test_common_platforms() {
        let platforms = Platform::common_platforms();
        assert_eq!(platforms.len(), 7);

        let keys: Vec<String> = platforms.iter().map(|p| p.to_key()).collect();
        assert!(keys.contains(&"linux-x64".to_string()));
        assert!(keys.contains(&"linux-x64-musl".to_string()));
        assert!(keys.contains(&"linux-arm64".to_string()));
        assert!(keys.contains(&"linux-arm64-musl".to_string()));
        assert!(keys.contains(&"macos-x64".to_string()));
        assert!(keys.contains(&"macos-arm64".to_string()));
        assert!(keys.contains(&"windows-x64".to_string()));
    }

    #[cfg(all(target_os = "linux", target_env = "musl"))]
    #[test]
    fn test_musl_binary_detects_musl() {
        // A musl-compiled binary should always detect musl, even in
        // minimal containers with no linker files (scratch, busybox).
        assert!(
            is_musl_system(),
            "musl-compiled binary should detect musl system"
        );
    }

    #[cfg(all(target_os = "linux", target_env = "musl"))]
    #[test]
    fn test_current_platform_has_musl_qualifier() {
        // A musl-compiled binary should always have the musl qualifier,
        // even in minimal containers with no linker files.
        let platform = Platform::current();
        assert_eq!(
            platform.qualifier.as_deref(),
            Some("musl"),
            "musl-compiled binary should have musl qualifier, got: {}",
            platform.to_key()
        );
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn test_os_release_alpine_id_is_musl() {
        let tmp = std::env::temp_dir().join("mise-libc-alpine");
        std::fs::write(
            &tmp,
            "NAME=\"Alpine Linux\"\nID=alpine\nVERSION_ID=3.22.4\n",
        )
        .unwrap();
        assert_eq!(musl_from_os_release(tmp.to_str().unwrap()), Some(true));
        let _ = std::fs::remove_file(&tmp);
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn test_os_release_id_like_alpine_is_musl() {
        let tmp = std::env::temp_dir().join("mise-libc-id-like");
        std::fs::write(&tmp, "ID=postmarketos\nID_LIKE=\"alpine\"\n").unwrap();
        assert_eq!(musl_from_os_release(tmp.to_str().unwrap()), Some(true));
        let _ = std::fs::remove_file(&tmp);
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn test_os_release_debian_returns_none() {
        let tmp = std::env::temp_dir().join("mise-libc-debian");
        std::fs::write(&tmp, "ID=debian\nID_LIKE=\"\"\n").unwrap();
        assert_eq!(musl_from_os_release(tmp.to_str().unwrap()), None);
        let _ = std::fs::remove_file(&tmp);
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn test_os_release_missing_returns_none() {
        assert_eq!(musl_from_os_release("/nonexistent/os-release"), None);
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn test_os_release_comments_and_blank_lines_do_not_short_circuit() {
        // Regression: previously `split_once('=')?` returned None on the first
        // comment or blank line, causing the function to ignore the `ID=` line
        // that came after and silently fall back to linker-based detection.
        let tmp = std::env::temp_dir().join("mise-libc-comments");
        std::fs::write(
            &tmp,
            "# this is a comment\n\nNAME=\"Alpine Linux\"\nID=alpine\n",
        )
        .unwrap();
        assert_eq!(musl_from_os_release(tmp.to_str().unwrap()), Some(true));
        let _ = std::fs::remove_file(&tmp);
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn test_os_release_whitespace_around_key_tolerated() {
        let tmp = std::env::temp_dir().join("mise-libc-whitespace");
        std::fs::write(&tmp, "  ID = alpine \n").unwrap();
        assert_eq!(musl_from_os_release(tmp.to_str().unwrap()), Some(true));
        let _ = std::fs::remove_file(&tmp);
    }
}