Skip to main content

lisette_stdlib/
target.rs

1use std::env::consts;
2use std::fmt;
3
4#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
5pub struct Target {
6    pub goos: &'static str,
7    pub goarch: &'static str,
8}
9
10/// The targets with stdlib typedefs, mirroring the `justfile`'s `_supported-targets`.
11pub const SUPPORTED_TARGETS: &[Target] = &[
12    Target::new("linux", "amd64"),
13    Target::new("linux", "arm64"),
14    Target::new("darwin", "amd64"),
15    Target::new("darwin", "arm64"),
16    Target::new("windows", "amd64"),
17    Target::new("windows", "arm64"),
18];
19
20impl Target {
21    pub const fn new(goos: &'static str, goarch: &'static str) -> Self {
22        Self { goos, goarch }
23    }
24
25    pub fn parse(text: &str) -> Option<Self> {
26        let (goos, goarch) = text.split_once('/')?;
27        SUPPORTED_TARGETS
28            .iter()
29            .copied()
30            .find(|target| target.goos == goos && target.goarch == goarch)
31    }
32
33    pub fn cache_segment(self) -> String {
34        format!("{}_{}", self.goos, self.goarch)
35    }
36
37    pub fn is_host(self) -> bool {
38        self == Self::host()
39    }
40
41    pub fn host() -> Self {
42        let goos = match consts::OS {
43            "macos" => "darwin",
44            other => other,
45        };
46        let goarch = match consts::ARCH {
47            "x86_64" => "amd64",
48            "aarch64" => "arm64",
49            "x86" => "386",
50            other => other,
51        };
52        Self { goos, goarch }
53    }
54}
55
56impl Default for Target {
57    fn default() -> Self {
58        Self::host()
59    }
60}
61
62impl fmt::Display for Target {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        write!(f, "{}/{}", self.goos, self.goarch)
65    }
66}
67
68/// Format a `(goos, goarch)` slice as a comma-separated `goos/goarch` list,
69/// for "Available on: ..." diagnostics.
70pub fn format_targets(targets: &[(&str, &str)]) -> String {
71    targets
72        .iter()
73        .map(|(goos, goarch)| format!("{}/{}", goos, goarch))
74        .collect::<Vec<_>>()
75        .join(", ")
76}
77
78#[cfg(test)]
79mod tests {
80    use super::*;
81    use crate::get_go_stdlib_typedef;
82
83    #[test]
84    fn every_supported_target_has_an_overlay() {
85        for target in SUPPORTED_TARGETS {
86            assert!(
87                get_go_stdlib_typedef("os", *target).is_some(),
88                "`{target}` has no typedef overlay"
89            );
90        }
91    }
92
93    #[test]
94    fn parse_accepts_only_supported_targets() {
95        assert_eq!(Target::parse("linux/amd64"), Some(SUPPORTED_TARGETS[0]));
96        assert_eq!(Target::parse("freebsd/amd64"), None);
97        assert_eq!(Target::parse("linux"), None);
98        assert_eq!(Target::parse("linux/amd64/extra"), None);
99        assert_eq!(Target::parse(""), None);
100    }
101}