Skip to main content

isothrum_runner/
name.rs

1//! A run's name: what the embedder calls the run (`app-web-portal`), else the run's name.
2//! It names the run's state folder and, through `${run.name}`, the Compose project and the
3//! networks, so it holds only what every engine accepts.
4
5use std::fmt;
6
7use serde::{Deserialize, Deserializer, Serialize, Serializer};
8
9use crate::Result;
10use crate::error::Error;
11
12/// The longest name: Docker's limit for a project name, minus room for a network suffix.
13const MAX_LEN: usize = 63;
14
15/// A run's name: 1 to 63 lowercase letters, digits, `-` or `_`, starting with a letter or digit
16/// (Compose's rule for a project name), and not a Windows device name (`con`, `nul`, `com1`…),
17/// which can't name a folder there.
18#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
19pub struct RunName(String);
20
21impl RunName {
22    /// The name, when it can name a run.
23    ///
24    /// # Errors
25    ///
26    /// Fails with `run_name` when `value` breaks that rule.
27    pub fn new(value: &str) -> Result<RunName> {
28        let mut chars = value.chars();
29        let first = chars.next().is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit());
30        let rest = chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '-' | '_'));
31        if first && rest && value.len() <= MAX_LEN && !is_windows_device(value) {
32            Ok(RunName(value.to_owned()))
33        } else {
34            Err(Error::RunName { value: value.to_owned() })
35        }
36    }
37
38    /// The name a project in folder `dir` runs as when none is given: the folder's name in
39    /// lower case, each character a run name can't hold as `-`, cut to the longest a name takes
40    /// (Compose names a project after its folder the same way).
41    ///
42    /// # Errors
43    ///
44    /// `run_name` when nothing of the folder's name is left that can name a run.
45    pub fn from_folder(dir: &std::path::Path) -> Result<RunName> {
46        let folder = dir.file_name().map(|n| n.to_string_lossy().to_lowercase()).unwrap_or_default();
47        let made: String = folder
48            .chars()
49            .map(|c| if c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' { c } else { '-' })
50            .collect();
51        let trimmed: String = made.trim_start_matches(['-', '_']).chars().take(MAX_LEN).collect();
52        RunName::new(&trimmed).map_err(|_| Error::RunName { value: folder })
53    }
54
55    /// The name.
56    #[must_use]
57    pub fn as_str(&self) -> &str {
58        &self.0
59    }
60}
61
62/// Whether `value` is one of the names Windows keeps for a device: a folder can't take it, on
63/// any drive, so a run named so couldn't keep its state there. A run name has no `.`, so the
64/// name alone is what counts.
65fn is_windows_device(value: &str) -> bool {
66    match value.as_bytes() {
67        b"con" | b"prn" | b"aux" | b"nul" => true,
68        [b'c', b'o', b'm', n] | [b'l', b'p', b't', n] => n.is_ascii_digit(),
69        _ => false,
70    }
71}
72
73impl fmt::Display for RunName {
74    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75        f.write_str(&self.0)
76    }
77}
78
79impl Serialize for RunName {
80    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
81        s.serialize_str(&self.0)
82    }
83}
84
85impl<'de> Deserialize<'de> for RunName {
86    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<RunName, D::Error> {
87        RunName::new(&String::deserialize(d)?).map_err(serde::de::Error::custom)
88    }
89}
90
91impl std::str::FromStr for RunName {
92    type Err = Error;
93
94    fn from_str(s: &str) -> Result<RunName> {
95        RunName::new(s)
96    }
97}
98
99impl TryFrom<&str> for RunName {
100    type Error = Error;
101
102    fn try_from(value: &str) -> Result<RunName> {
103        RunName::new(value)
104    }
105}
106
107impl TryFrom<String> for RunName {
108    type Error = Error;
109
110    fn try_from(value: String) -> Result<RunName> {
111        RunName::new(&value)
112    }
113}
114
115impl AsRef<str> for RunName {
116    fn as_ref(&self) -> &str {
117        &self.0
118    }
119}
120
121#[cfg(test)]
122mod tests {
123    use super::*;
124
125    #[test]
126    fn a_run_name_is_a_compose_project_name() {
127        for good in ["web-portal", "app-invoice-portal-api", "a", "stack_2", "9lives"] {
128            assert_eq!(RunName::new(good).unwrap().as_str(), good);
129        }
130        for bad in ["", "Web", "-x", "_x", "a b", "a/b", "..", "é", &"a".repeat(64)] {
131            assert_eq!(RunName::new(bad).unwrap_err().code(), crate::ErrorCode::RunName, "{bad}");
132        }
133    }
134
135    #[test]
136    fn a_windows_device_name_is_no_run_name() {
137        for device in ["con", "prn", "aux", "nul", "com0", "com1", "com9", "lpt1", "lpt9"] {
138            assert_eq!(RunName::new(device).unwrap_err().code(), crate::ErrorCode::RunName, "{device}");
139        }
140        for good in ["console", "con-1", "nul_stack", "com10", "lpt", "com", "auxiliary", "xcon"] {
141            assert_eq!(RunName::new(good).unwrap().as_str(), good);
142        }
143    }
144
145    #[test]
146    fn a_run_name_reads_back_checked() {
147        let name: RunName = serde_json::from_str("\"web-1\"").unwrap();
148        assert_eq!(serde_json::to_string(&name).unwrap(), "\"web-1\"");
149        let err = serde_json::from_str::<RunName>("\"../etc\"").unwrap_err().to_string();
150        assert!(err.contains("../etc"), "the refused name is said: {err}");
151    }
152}