Skip to main content

mortise_core/run/
detect.rs

1//! Herd, Sail and Docker, found from the folder of an app. Reads files only.
2//!
3//! Nothing here starts a program. A file that is missing or not valid means "not found".
4
5use std::fs;
6use std::path::{Path, PathBuf};
7
8/// The compose files that Docker Compose reads, in its own order.
9const COMPOSE_FILES: [&str; 4] = [
10    "compose.yaml",
11    "compose.yml",
12    "docker-compose.yaml",
13    "docker-compose.yml",
14];
15
16/// A runner that the folder of an app points to.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum Detected {
19    /// The folder is a Herd site, parked or linked.
20    Herd,
21    /// The folder holds `vendor/bin/sail` and a compose file. Never on Windows.
22    Sail,
23    /// The folder holds a compose file and Sail is not found. The service is always `app`.
24    Docker,
25}
26
27/// What the folder points to, the best first. Reads files only.
28///
29/// `herd_config` is the valet folder of Herd, as [`herd_config_dir`] gives it.
30pub fn detect(root: &Path, herd_config: Option<&Path>) -> Vec<Detected> {
31    let mut found = Vec::new();
32    if herd_config.is_some_and(|valet| is_herd_site(root, valet)) {
33        found.push(Detected::Herd);
34    }
35    let compose = COMPOSE_FILES.iter().any(|name| root.join(name).is_file());
36    // Sail is a bash script. On Windows it runs in WSL only, so Mortise does not offer it.
37    let sail = !cfg!(windows) && compose && root.join("vendor/bin/sail").is_file();
38    if sail {
39        found.push(Detected::Sail);
40    } else if compose {
41        found.push(Detected::Docker);
42    }
43    found
44}
45
46/// The valet folder of Herd on this platform. `None` on Linux.
47///
48/// These folders are assumed from the documentation of Herd and Valet.
49/// They were not checked on a machine with Herd.
50pub fn herd_config_dir() -> Option<PathBuf> {
51    let home = directories::BaseDirs::new()?.home_dir().to_path_buf();
52    if cfg!(target_os = "macos") {
53        Some(home.join("Library/Application Support/Herd/config/valet"))
54    } else if cfg!(windows) {
55        Some(home.join(r".config\herd\config\valet"))
56    } else {
57        None
58    }
59}
60
61/// Whether `root` is parked (its parent is in `paths` of `config.json`) or linked
62/// (an entry in `Sites/` points to it). Both sides are compared after `canonicalize`.
63fn is_herd_site(root: &Path, valet: &Path) -> bool {
64    let Ok(root) = fs::canonicalize(root) else {
65        return false;
66    };
67    parked(&root, valet) || linked(&root, valet)
68}
69
70fn parked(root: &Path, valet: &Path) -> bool {
71    let Some(parent) = root.parent() else {
72        return false;
73    };
74    let Ok(text) = fs::read_to_string(valet.join("config.json")) else {
75        return false;
76    };
77    let Ok(config) = serde_json::from_str::<serde_json::Value>(&text) else {
78        return false;
79    };
80    let Some(paths) = config.get("paths").and_then(|paths| paths.as_array()) else {
81        return false;
82    };
83    paths
84        .iter()
85        .filter_map(|path| path.as_str())
86        .filter_map(|path| fs::canonicalize(path).ok())
87        .any(|path| path == parent)
88}
89
90/// `canonicalize` follows the link, so a link of any kind (a junction on Windows too) is compared
91/// by its target.
92fn linked(root: &Path, valet: &Path) -> bool {
93    let Ok(entries) = fs::read_dir(valet.join("Sites")) else {
94        return false;
95    };
96    entries
97        .flatten()
98        .filter_map(|entry| fs::canonicalize(entry.path()).ok())
99        .any(|target| target == root)
100}
101
102#[cfg(test)]
103mod tests {
104    use super::*;
105
106    fn touch(path: &Path) {
107        fs::create_dir_all(path.parent().unwrap()).unwrap();
108        fs::write(path, "").unwrap();
109    }
110
111    /// A folder `parked/shop` and an empty valet folder.
112    fn herd() -> (tempfile::TempDir, PathBuf, PathBuf) {
113        let temp = tempfile::tempdir().unwrap();
114        let root = temp.path().join("parked/shop");
115        fs::create_dir_all(&root).unwrap();
116        let valet = temp.path().join("valet");
117        fs::create_dir_all(&valet).unwrap();
118        (temp, root, valet)
119    }
120
121    /// Parks the folder `parked` in the valet folder.
122    fn park(temp: &tempfile::TempDir, valet: &Path) {
123        let config = serde_json::json!({ "paths": [temp.path().join("parked")] });
124        fs::write(valet.join("config.json"), config.to_string()).unwrap();
125    }
126
127    #[test]
128    fn a_folder_in_a_parked_path_is_herd() {
129        let (temp, root, valet) = herd();
130        park(&temp, &valet);
131        assert_eq!(detect(&root, Some(&valet)), [Detected::Herd]);
132        assert_eq!(detect(&root, None), []);
133    }
134
135    #[cfg(unix)]
136    #[test]
137    fn a_folder_linked_from_sites_is_herd() {
138        let (temp, _, valet) = herd();
139        let root = temp.path().join("elsewhere/shop");
140        fs::create_dir_all(&root).unwrap();
141        fs::create_dir_all(valet.join("Sites")).unwrap();
142        std::os::unix::fs::symlink(&root, valet.join("Sites/shop")).unwrap();
143        assert_eq!(detect(&root, Some(&valet)), [Detected::Herd]);
144    }
145
146    #[test]
147    fn a_broken_config_is_not_herd() {
148        let (_temp, root, valet) = herd();
149        fs::write(valet.join("config.json"), "{ \"paths\": [").unwrap();
150        assert_eq!(detect(&root, Some(&valet)), []);
151    }
152
153    #[test]
154    fn sail_needs_a_compose_file_and_not_windows() {
155        let temp = tempfile::tempdir().unwrap();
156        touch(&temp.path().join("vendor/bin/sail"));
157        assert_eq!(detect(temp.path(), None), []);
158        touch(&temp.path().join("compose.yaml"));
159        let sail = if cfg!(windows) {
160            Detected::Docker
161        } else {
162            Detected::Sail
163        };
164        assert_eq!(detect(temp.path(), None), [sail]);
165    }
166
167    #[test]
168    fn each_compose_file_is_docker() {
169        for name in COMPOSE_FILES {
170            let temp = tempfile::tempdir().unwrap();
171            touch(&temp.path().join(name));
172            assert_eq!(detect(temp.path(), None), [Detected::Docker], "{name}");
173        }
174    }
175
176    #[test]
177    fn herd_comes_before_sail() {
178        let (temp, root, valet) = herd();
179        park(&temp, &valet);
180        touch(&root.join("vendor/bin/sail"));
181        touch(&root.join("docker-compose.yml"));
182        let sail = if cfg!(windows) {
183            Detected::Docker
184        } else {
185            Detected::Sail
186        };
187        assert_eq!(detect(&root, Some(&valet)), [Detected::Herd, sail]);
188    }
189
190    #[test]
191    fn an_empty_folder_finds_nothing() {
192        let temp = tempfile::tempdir().unwrap();
193        assert_eq!(detect(temp.path(), Some(&temp.path().join("valet"))), []);
194    }
195}