isothrum_runner/
project.rs1pub(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#[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 Compose,
30 Vagrant,
32 Terraform,
34}
35
36const COMPOSE_FILES: [&str; 4] = ["compose.yaml", "compose.yml", "docker-compose.yaml", "docker-compose.yml"];
38
39const VAGRANTFILE: &str = "Vagrantfile";
41
42const TERRAFORM_LOCK: &str = ".terraform.lock.hcl";
44
45impl Format {
46 pub const ALL: [Format; 3] = [Format::Compose, Format::Vagrant, Format::Terraform];
48
49 #[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 #[must_use]
61 pub fn named(name: &str) -> Option<Format> {
62 Format::ALL.into_iter().find(|f| f.as_str() == name)
63 }
64
65 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 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
122fn 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
147fn 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#[derive(Debug, Clone, PartialEq, Eq)]
156#[non_exhaustive]
157pub struct Project {
158 pub dir: PathBuf,
160 pub format: Format,
162 pub files: Vec<PathBuf>,
164}
165
166impl Project {
167 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 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
218struct 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;