Skip to main content

isothrum_runner/
project.rs

1//! A project: the folder a run starts from, in one of the formats Isothrum drives. The format is
2//! recognised from the folder's own files ([`Format::detect`]), never from a file another tool
3//! writes for the runner: any Compose project, Vagrantfile or Terraform module runs, whoever
4//! wrote it.
5//!
6//! - [`Format`]: which tool runs the folder, and the files that say so.
7//! - [`Project`]: the folder, its format and those files, plus the digest that tells an update
8//!   the files changed.
9//! - [`platform`]: the host and hypervisor words the drivers and the embedder share.
10//! - [`inputs`]: the values a run is given, written the way each tool reads them.
11
12pub(crate) mod inputs;
13pub(crate) mod platform;
14pub(crate) mod variables;
15
16use std::path::{Path, PathBuf};
17
18use serde::{Deserialize, Serialize};
19
20use crate::Result;
21use crate::error::Error;
22
23/// The format of a project, which is the tool that runs it.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, schemars::JsonSchema)]
25#[serde(rename_all = "lowercase")]
26#[non_exhaustive]
27pub enum Format {
28    /// A Compose project (`docker compose`): a `compose.yaml` or one of the names Compose reads.
29    Compose,
30    /// A Vagrant project (`vagrant`): a `Vagrantfile`.
31    Vagrant,
32    /// A Terraform root module (`terraform`): one or more `*.tf` or `*.tf.json` files.
33    Terraform,
34}
35
36/// The file names Compose reads in a folder by default, in its own order of precedence.
37const COMPOSE_FILES: [&str; 4] = ["compose.yaml", "compose.yml", "docker-compose.yaml", "docker-compose.yml"];
38
39/// The file Vagrant reads in a folder.
40const VAGRANTFILE: &str = "Vagrantfile";
41
42/// The files of a Terraform root module that pin its providers, part of what it runs.
43const TERRAFORM_LOCK: &str = ".terraform.lock.hcl";
44
45impl Format {
46    /// Every format, in the order a folder is tried.
47    pub const ALL: [Format; 3] = [Format::Compose, Format::Vagrant, Format::Terraform];
48
49    /// The format as written on the command line and in events (`compose`).
50    #[must_use]
51    pub const fn as_str(self) -> &'static str {
52        match self {
53            Format::Compose => "compose",
54            Format::Vagrant => "vagrant",
55            Format::Terraform => "terraform",
56        }
57    }
58
59    /// The format named `name` ([`Format::as_str`]), if any.
60    #[must_use]
61    pub fn named(name: &str) -> Option<Format> {
62        Format::ALL.into_iter().find(|f| f.as_str() == name)
63    }
64
65    /// The files of `dir` that make it a project of this format, sorted; none when it isn't one.
66    /// Compose: the first default file Compose itself would read (one only, as Compose takes).
67    /// Vagrant: the `Vagrantfile`. Terraform: every `*.tf` and `*.tf.json` file, and the provider
68    /// lock when there is one.
69    ///
70    /// # Errors
71    ///
72    /// `io` when `dir` can't be listed.
73    pub fn files_in(self, dir: &Path) -> Result<Vec<PathBuf>> {
74        let found = match self {
75            Format::Compose => COMPOSE_FILES.iter().map(|n| dir.join(n)).find(|p| p.is_file()).into_iter().collect(),
76            Format::Vagrant => Some(dir.join(VAGRANTFILE)).filter(|p| p.is_file()).into_iter().collect(),
77            Format::Terraform => terraform_files(dir)?,
78        };
79        Ok(found)
80    }
81
82    /// The format of `dir`: the one whose files it holds ([`Format::files_in`]).
83    ///
84    /// # Errors
85    ///
86    /// `project_invalid` when `dir` holds no format's files, or the files of several (a folder
87    /// with both a Compose file and a Vagrantfile: the caller names the one to run); `io` when
88    /// `dir` can't be listed.
89    pub fn detect(dir: &Path) -> Result<Format> {
90        let mut found = Vec::new();
91        for format in Format::ALL {
92            if !format.files_in(dir)?.is_empty() {
93                found.push(format);
94            }
95        }
96        match found.as_slice() {
97            [one] => Ok(*one),
98            [] => Err(Error::Project {
99                dir: dir.to_path_buf(),
100                reason: format!(
101                    "it holds no Compose file ({}), Vagrantfile or Terraform module (*.tf)",
102                    COMPOSE_FILES.join(", ")
103                ),
104            }),
105            many => Err(Error::Project {
106                dir: dir.to_path_buf(),
107                reason: format!(
108                    "it holds the files of several formats ({}): name the one to run",
109                    many.iter().map(|f| f.as_str()).collect::<Vec<_>>().join(", ")
110                ),
111            }),
112        }
113    }
114}
115
116impl std::fmt::Display for Format {
117    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
118        f.write_str(self.as_str())
119    }
120}
121
122/// Every Terraform file at the top of `dir` (a root module's own; its sub-modules are what it
123/// calls), sorted, with the provider lock.
124fn terraform_files(dir: &Path) -> Result<Vec<PathBuf>> {
125    let entries = match std::fs::read_dir(dir) {
126        Ok(entries) => entries,
127        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
128        Err(e) => return Err(Error::io(dir, "list")(e)),
129    };
130    let mut found = Vec::new();
131    for entry in entries {
132        let path = entry.map_err(Error::io(dir, "list"))?.path();
133        if is_terraform_file(&path) && path.is_file() {
134            found.push(path);
135        }
136    }
137    if !found.is_empty() {
138        let lock = dir.join(TERRAFORM_LOCK);
139        if lock.is_file() {
140            found.push(lock);
141        }
142    }
143    found.sort();
144    Ok(found)
145}
146
147/// Whether `path` names a Terraform file: `*.tf` or `*.tf.json`, in lower case as Terraform reads
148/// them.
149fn is_terraform_file(path: &Path) -> bool {
150    let tf = |p: &Path| p.extension().is_some_and(|e| e == "tf");
151    tf(path) || (path.extension().is_some_and(|e| e == "json") && tf(&path.with_extension("")))
152}
153
154/// A project to run: its folder, its format and the files that make it one.
155#[derive(Debug, Clone, PartialEq, Eq)]
156#[non_exhaustive]
157pub struct Project {
158    /// The folder, absolute: where the tool runs.
159    pub dir: PathBuf,
160    /// Its format.
161    pub format: Format,
162    /// The files that make it a project of that format ([`Format::files_in`]), absolute.
163    pub files: Vec<PathBuf>,
164}
165
166impl Project {
167    /// The project in `dir`, of format `format` when given, else the one detected
168    /// ([`Format::detect`]).
169    ///
170    /// # Errors
171    ///
172    /// `project_invalid` when `dir` isn't a folder, when `format` is given and `dir` holds none
173    /// of its files, or as [`Format::detect`] refuses; `io` when `dir` can't be read.
174    pub fn open(dir: &Path, format: Option<Format>) -> Result<Project> {
175        let dir = std::path::absolute(dir).map_err(Error::io(dir, "read"))?;
176        if !dir.is_dir() {
177            return Err(Error::Project {
178                dir,
179                reason: "it isn't a folder".to_owned(),
180            });
181        }
182        let format = match format {
183            Some(f) => f,
184            None => Format::detect(&dir)?,
185        };
186        let files = format.files_in(&dir)?;
187        if files.is_empty() {
188            return Err(Error::Project {
189                dir,
190                reason: format!("it holds no {format} project"),
191            });
192        }
193        Ok(Project { dir, format, files })
194    }
195
196    /// What the project's files hold, as a short digest: it changes when one of them changes, is
197    /// added or goes (an update reads it to know the project changed). What those files only
198    /// point at (a build context, a provisioner's script, a sub-module) isn't read: the tool reads
199    /// it again at every operation anyway. Not a security check.
200    ///
201    /// # Errors
202    ///
203    /// `io` when one of the files can't be read.
204    pub fn digest(&self) -> Result<String> {
205        let mut hash = Fnv64::new();
206        hash.write(self.format.as_str().as_bytes());
207        for file in &self.files {
208            let name = file.strip_prefix(&self.dir).unwrap_or(file);
209            hash.write(&[0]);
210            hash.write(name.to_string_lossy().as_bytes());
211            hash.write(&[0]);
212            hash.write(&std::fs::read(file).map_err(Error::io(file, "read"))?);
213        }
214        Ok(format!("fnv64:{:016x}", hash.0))
215    }
216}
217
218/// FNV-1a over 64 bits: enough to tell that files changed, and nothing more.
219struct Fnv64(u64);
220
221impl Fnv64 {
222    fn new() -> Fnv64 {
223        Fnv64(0xcbf2_9ce4_8422_2325)
224    }
225
226    fn write(&mut self, bytes: &[u8]) {
227        for b in bytes {
228            self.0 = (self.0 ^ u64::from(*b)).wrapping_mul(0x0000_0100_0000_01b3);
229        }
230    }
231}
232
233#[cfg(test)]
234mod tests;