Skip to main content

isoloom_spec/
error.rs

1//! Why a spec, a file beside it or a value in it isn't one Isoloom reads: one enum for the
2//! crate. Every message says where (the folder, the file, the field, the value) and why, in
3//! words a user acts on without reading Isoloom's code. A spec that reads but is wrong is
4//! [`Error::Invalid`], holding its [`Problem`]s, one per field.
5
6use std::fmt;
7use std::path::PathBuf;
8
9use crate::model::Target;
10use crate::profile::ProfileProblem;
11use crate::syntax::Problem;
12
13/// Why a spec, a file beside it or a value in it isn't one Isoloom reads.
14#[derive(Debug, thiserror::Error)]
15#[non_exhaustive]
16pub enum Error {
17    /// The folder has no spec file.
18    #[error("no isoloom.yml in {}", .0.display())]
19    NotFound(PathBuf),
20    /// Both `isoloom.yml` and `isoloom.yaml` exist: which one is meant is ambiguous.
21    #[error("both isoloom.yml and isoloom.yaml exist in {}; keep one", .0.display())]
22    Ambiguous(PathBuf),
23    /// A file exists but couldn't be read.
24    #[error("can't read {}: {source}", path.display())]
25    Read {
26        /// The file.
27        path: PathBuf,
28        /// The system's reason.
29        #[source]
30        source: std::io::Error,
31    },
32    /// Not YAML: the spec's text before its overrides, or a profile's spec it merges. The
33    /// message carries the line and column.
34    #[error("{0}")]
35    Yaml(#[from] serde_yaml_ng::Error),
36    /// The spec's problems: every one found, coded and placed, in file order.
37    #[error("{}", Rendered { file, problems })]
38    Invalid {
39        /// The spec file the problems are placed in (`isoloom.yml`).
40        file: String,
41        /// The problems.
42        problems: Vec<Problem>,
43    },
44    /// A `-s` that isn't `key=value`.
45    #[error("`-s {set}`: expected key=value, like -s machines.web.vm.os=ubuntu@24.04")]
46    SetShape {
47        /// The `-s` as given.
48        set: String,
49    },
50    /// A `-s` whose key isn't a dotted path.
51    #[error("`-s {set}`: the key is a dotted path, like cloud.aws.region")]
52    SetKey {
53        /// The `-s` as given.
54        set: String,
55    },
56    /// A name that breaks its rule.
57    #[error("`{value}` isn't a valid {what}: {rule}")]
58    Name {
59        /// What it names (`port name`).
60        what: &'static str,
61        /// The value written.
62        value: String,
63        /// The rule, as an author fixes the value.
64        rule: &'static str,
65    },
66    /// An OS no family names.
67    #[error("unknown OS `{text}`; write `<family>@<version>` with one of: {known}")]
68    UnknownOs {
69        /// What the spec wrote.
70        text: String,
71        /// The families and their versions.
72        known: String,
73    },
74    /// A known OS family without that version.
75    #[error("{family} has no version `{version}`; use one of: {known} (`{family}` alone is {family}@{default})")]
76    UnknownOsVersion {
77        /// The family.
78        family: &'static str,
79        /// The version the spec wrote.
80        version: String,
81        /// The family's versions.
82        known: String,
83        /// The family's default version.
84        default: &'static str,
85    },
86    /// A `{{ path }}` placeholder whose path the grammar doesn't have.
87    #[error("`{{{{ {path} }}}}` isn't a placeholder Isoloom knows: {why}")]
88    Placeholder {
89        /// The path as written, trimmed.
90        path: String,
91        /// What the paths there are.
92        why: &'static str,
93    },
94    /// A `{{` without its `}}`.
95    #[error("a `{{{{` without its `}}}}`")]
96    Unclosed,
97    /// A placeholder the place it is written in can't name (a run-time value in a file).
98    #[error("`{{{{ {reference} }}}}`: {why}")]
99    NotHere {
100        /// What it names.
101        reference: crate::syntax::placeholder::Reference,
102        /// Why the place can't name it.
103        why: &'static str,
104    },
105    /// A file mode that isn't octal digits up to `0777`.
106    #[error("`{0}` isn't a file mode: octal digits up to 0777, like \"0444\"")]
107    Mode(String),
108    /// A machine with both a catalogue `service` and a custom `app`.
109    #[error("`service` and `app` are both given: a machine is a catalogue service or a custom app")]
110    ServiceAndApp,
111    /// A machine's `with` without a `service`.
112    #[error("`with` sets a catalogue service's settings: it goes with `service`")]
113    WithWithoutService,
114    /// An app's `config` without an `appliance`.
115    #[error("`config` is an appliance's: it goes with `appliance`")]
116    ConfigWithoutAppliance,
117    /// An appliance built from a Dockerfile.
118    #[error("an appliance comes from its `image` (or `firmware`), not a `build`")]
119    ApplianceBuild,
120    /// `firmware` without `appliance: cisco-dynamips`.
121    #[error("`firmware` is `cisco-dynamips`'s: it goes with `appliance: cisco-dynamips`")]
122    FirmwareWithoutDynamips,
123    /// An app with no recipe at all.
124    #[error("an app needs a recipe: `image`, `build`, `steps` or `appliance`")]
125    NoRecipe,
126    /// `cisco-dynamips` with an `image`.
127    #[error("`cisco-dynamips` boots its `firmware`; Isoloom builds its image, so no `image`")]
128    DynamipsImage,
129    /// `cisco-dynamips` without its `firmware`.
130    #[error("`cisco-dynamips` needs the `firmware` it boots (the IOS `.bin`)")]
131    DynamipsFirmware,
132    /// Another appliance with a `firmware`.
133    #[error("`firmware` is `cisco-dynamips`'s; this appliance runs its `image`")]
134    ApplianceFirmware,
135    /// An appliance without its `image`.
136    #[error("an appliance runs its `image` (`vrnetlab/cisco_iol:<version>`)")]
137    ApplianceImage,
138    /// A healthcheck with both a `test` and an `http` page.
139    #[error("`test` and `http` are both given: a healthcheck is a `test` or an `http` page")]
140    TestAndHttp,
141    /// A healthcheck that tries nothing.
142    #[error("a healthcheck says what to try: `{{ test: <command> }}` or `{{ http: {{ port, path }} }}`")]
143    NoHealthProbe,
144    /// A file with no source.
145    #[error("a file needs one of `source`, `content`, `input` and `secret`")]
146    NoFileSource,
147    /// A file with several sources.
148    #[error("`{}` are {} given: keep one source", .0.join("` and `"), if .0.len() == 2 { "both" } else { "all" })]
149    FileSources(Vec<&'static str>),
150    /// An environment value written as a reference to neither one input nor one secret.
151    #[error("write one of `{{ input: NAME }}`")]
152    EnvReference,
153    /// A GPU count that is neither a whole number nor `all`.
154    #[error("`gpus.count`: a whole number or `all`, not {0}")]
155    GpuCount(String),
156    /// `gpus` as a word other than `all`.
157    #[error("`gpus`: a number, `all` or a mapping, not `{0}`")]
158    GpusWord(String),
159    /// A device written with more than three parts.
160    #[error("`{0}`: a device is `host[:guest[:permissions]]`")]
161    Device(String),
162    /// A layer of the defaults (the user's or the project's file, `--images`) that isn't YAML.
163    #[error("{}: {source}", path.display())]
164    Layer {
165        /// The file.
166        path: PathBuf,
167        /// What the YAML reader reported.
168        #[source]
169        source: serde_yaml_ng::Error,
170    },
171    /// The defaults, merged, hold a key or a value they don't have.
172    #[error("defaults ({sources}): {source}")]
173    Defaults {
174        /// The layers merged, as `isoloom defaults` names them.
175        sources: String,
176        /// What the typed read reported.
177        #[source]
178        source: serde_yaml_ng::Error,
179    },
180    /// An image table that isn't one (`--images`, the defaults' `images:`).
181    #[error("{0}")]
182    Images(#[source] serde_yaml_ng::Error),
183    /// A profile's name that isn't kebab-case.
184    #[error("profile `{0}`: a profile name is kebab-case (lowercase letters, digits, dashes)")]
185    ProfileName(String),
186    /// No profile by that name.
187    #[error("no profile `{name}` ({})", Known { folder, known })]
188    NoProfile {
189        /// The name asked for.
190        name: String,
191        /// The project's profiles folder.
192        folder: PathBuf,
193        /// The profiles it has, by name.
194        known: Vec<String>,
195    },
196    /// Both `profiles/<name>.yml` and `.yaml` exist.
197    #[error("both {}/{name}.yml and {}/{name}.yaml exist; keep one", crate::profile::DIR, crate::profile::DIR)]
198    TwoProfiles {
199        /// The profile's name.
200        name: String,
201    },
202    /// A profile's file that isn't YAML, or holds a field a profile doesn't have.
203    #[error("profile `{name}` ({}): {source}", path.display())]
204    ProfileYaml {
205        /// The profile's name.
206        name: String,
207        /// Its file.
208        path: PathBuf,
209        /// What the YAML reader reported.
210        #[source]
211        source: serde_yaml_ng::Error,
212    },
213    /// A profile's `spec` or `defaults` that isn't a mapping.
214    #[error("profile `{name}` ({}): `{key}` is a mapping", path.display())]
215    ProfileMapping {
216        /// The profile's name.
217        name: String,
218        /// Its file.
219        path: PathBuf,
220        /// The field.
221        key: &'static str,
222    },
223    /// A profile's input that isn't one value.
224    #[error("profile `{name}` ({}): input `{input}` takes a single value (text, a number or a boolean)", path.display())]
225    ProfileInput {
226        /// The profile's name.
227        name: String,
228        /// Its file.
229        path: PathBuf,
230        /// The input.
231        input: String,
232    },
233    /// The profile names what the spec doesn't have: one line per problem.
234    #[error("{}", Lines(problems))]
235    ProfileMismatch {
236        /// The problems, one per field.
237        problems: Vec<ProfileProblem>,
238    },
239    /// Another target than the one the profile runs on.
240    #[error("profile `{profile}` runs on `{}`, not `{asked}`: drop the target or choose another profile", target.id())]
241    ProfileTarget {
242        /// The profile's name.
243        profile: String,
244        /// The target it runs on.
245        target: Target,
246        /// The target asked for.
247        asked: String,
248    },
249    /// An instance number outside 1 to [`crate::instance::MAX`].
250    #[error("an instance number is 1 to {}", crate::instance::MAX)]
251    InstanceNumber(u8),
252    /// An environment's name too long once it carries its instance.
253    #[error("`{0}` is too long for an instance name (at most 55 characters with the suffix)")]
254    InstanceName(String),
255    /// Text that isn't an IPv4 block.
256    #[error("`{0}` isn't an IPv4 block: write the network's own address, `/` and the prefix length (`10.20.0.0/24`)")]
257    Cidr(String),
258    /// Text that isn't an IPv6 /64 block.
259    #[error("`{0}` isn't an IPv6 block: write a unique local or global network address and `/64` (`fd00:20::/64`)")]
260    Cidr6(String),
261    /// A published port too high to shift for the instance.
262    #[error("machines.{machine}.ports: published port {port} leaves no room for instance {instance} (ports shift by 100 per instance)")]
263    InstancePort {
264        /// The machine.
265        machine: String,
266        /// The published port.
267        port: u16,
268        /// The instance.
269        instance: u8,
270    },
271    /// An IPv6 block too high to shift for the instance.
272    #[error("networks.{network}.ipv6.cidr: {cidr} leaves no room for instance {instance}")]
273    InstanceIpv6 {
274        /// The network.
275        network: String,
276        /// Its IPv6 block.
277        cidr: String,
278        /// The instance.
279        instance: u8,
280    },
281}
282
283/// What a function of this crate returns.
284pub type Result<T, E = Error> = std::result::Result<T, E>;
285
286/// Problems as an author reads them, one after the other.
287struct Rendered<'a> {
288    file: &'a str,
289    problems: &'a [Problem],
290}
291
292impl fmt::Display for Rendered<'_> {
293    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
294        for (i, p) in self.problems.iter().enumerate() {
295            if i > 0 {
296                f.write_str("\n")?;
297            }
298            f.write_str(&p.render(self.file))?;
299        }
300        Ok(())
301    }
302}
303
304/// Items one per line.
305struct Lines<'a, T>(&'a [T]);
306
307impl<T: fmt::Display> fmt::Display for Lines<'_, T> {
308    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
309        for (i, item) in self.0.iter().enumerate() {
310            if i > 0 {
311                f.write_str("\n")?;
312            }
313            write!(f, "{item}")?;
314        }
315        Ok(())
316    }
317}
318
319/// The profiles a project has, or the folder that has none.
320struct Known<'a> {
321    folder: &'a PathBuf,
322    known: &'a [String],
323}
324
325impl fmt::Display for Known<'_> {
326    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
327        if self.known.is_empty() {
328            write!(f, "no profiles in {}", self.folder.display())
329        } else {
330            write!(f, "profiles here: {}", self.known.join(", "))
331        }
332    }
333}
334
335#[cfg(test)]
336mod tests {
337    use super::*;
338    use crate::syntax::{Code, FieldPath};
339
340    #[test]
341    fn a_specs_problems_read_one_after_the_other() {
342        let problems = vec![
343            Problem::new(Code::MissingField, FieldPath::new("version"), "a spec says its format's version"),
344            Problem::new(Code::UnknownField, FieldPath::new("nme"), "`nme` isn't a field here"),
345        ];
346        let invalid = Error::Invalid {
347            file: "isoloom.yaml".into(),
348            problems,
349        };
350        assert_eq!(
351            invalid.to_string(),
352            "error[missing-field] version\n  a spec says its format's version\nerror[unknown-field] nme\n  `nme` isn't a field here"
353        );
354    }
355
356    #[test]
357    fn a_missing_profile_lists_the_profiles_there_are() {
358        let missing = |known: &[&str]| Error::NoProfile {
359            name: "c".into(),
360            folder: PathBuf::from("/lab/profiles"),
361            known: known.iter().map(|k| (*k).to_owned()).collect(),
362        };
363        assert_eq!(missing(&[]).to_string(), "no profile `c` (no profiles in /lab/profiles)");
364        assert_eq!(missing(&["a", "b"]).to_string(), "no profile `c` (profiles here: a, b)");
365    }
366
367    #[test]
368    fn a_profiles_problems_read_one_per_line() {
369        let problems = vec![
370            ProfileProblem::Input {
371                profile: "p".into(),
372                input: "A".into(),
373            },
374            ProfileProblem::Input {
375                profile: "p".into(),
376                input: "B".into(),
377            },
378        ];
379        assert_eq!(
380            Error::ProfileMismatch { problems }.to_string(),
381            "profile `p`: input `A` isn't one of the spec's `inputs`\nprofile `p`: input `B` isn't one of the spec's `inputs`"
382        );
383    }
384
385    #[test]
386    fn several_sources_of_one_file_are_named_together() {
387        assert_eq!(
388            Error::FileSources(vec!["source", "input"]).to_string(),
389            "`source` and `input` are both given: keep one source"
390        );
391        assert_eq!(
392            Error::FileSources(vec!["source", "content", "input"]).to_string(),
393            "`source` and `content` and `input` are all given: keep one source"
394        );
395    }
396}