1use std::borrow::Cow;
2use std::path::{Component, Path, PathBuf};
3
4use crate::migrate::migrate_dir;
5use crate::paths::{home_dir, option_root};
6
7#[derive(Debug, Clone, PartialEq, Eq, Hash)]
16pub struct App {
17 id: Cow<'static, str>,
18 mark: Cow<'static, str>,
19 display_name: Cow<'static, str>,
20 dir_name: Cow<'static, str>,
22 legacy_home_parts: &'static [&'static str],
26}
27
28impl App {
29 pub const OPSH: Self = Self {
30 id: Cow::Borrowed("opsh"),
31 mark: Cow::Borrowed("❯"),
32 display_name: Cow::Borrowed("opsh"),
33 dir_name: Cow::Borrowed("opsh"),
34 legacy_home_parts: &[],
35 };
36
37 pub const TERMINAL: Self = Self {
38 id: Cow::Borrowed("terminal"),
39 mark: Cow::Borrowed("◇"),
40 display_name: Cow::Borrowed("optionTerm"),
41 dir_name: Cow::Borrowed("terminal"),
42 legacy_home_parts: &[],
43 };
44
45 pub const MUSIC: Self = Self {
46 id: Cow::Borrowed("music"),
47 mark: Cow::Borrowed("♪"),
48 display_name: Cow::Borrowed("optionMusic"),
49 dir_name: Cow::Borrowed("music"),
50 legacy_home_parts: &["option", "music"],
51 };
52
53 pub const FILES: Self = Self {
54 id: Cow::Borrowed("files"),
55 mark: Cow::Borrowed("◆"),
56 display_name: Cow::Borrowed("optionFiles"),
57 dir_name: Cow::Borrowed("files"),
58 legacy_home_parts: &[],
59 };
60
61 pub const OS: Self = Self {
62 id: Cow::Borrowed("os"),
63 mark: Cow::Borrowed("◇"),
64 display_name: Cow::Borrowed("optionOS"),
65 dir_name: Cow::Borrowed("os"),
66 legacy_home_parts: &[".optionos"],
67 };
68
69 pub const DE: Self = Self {
70 id: Cow::Borrowed("de"),
71 mark: Cow::Borrowed("◇"),
72 display_name: Cow::Borrowed("optionDE"),
73 dir_name: Cow::Borrowed("de"),
74 legacy_home_parts: &[".optionde"],
75 };
76
77 pub const CAL: Self = Self {
78 id: Cow::Borrowed("cal"),
79 mark: Cow::Borrowed("◷"),
80 display_name: Cow::Borrowed("optionCalendar"),
81 dir_name: Cow::Borrowed("cal"),
82 legacy_home_parts: &[],
83 };
84
85 pub const SEARCH: Self = Self {
86 id: Cow::Borrowed("search"),
87 mark: Cow::Borrowed("⌕"),
88 display_name: Cow::Borrowed("optionSearch"),
89 dir_name: Cow::Borrowed("search"),
90 legacy_home_parts: &[],
91 };
92
93 pub const ALL: &'static [Self] = &[
95 Self::OPSH,
96 Self::TERMINAL,
97 Self::MUSIC,
98 Self::FILES,
99 Self::OS,
100 Self::DE,
101 Self::CAL,
102 Self::SEARCH,
103 ];
104
105 pub fn new(
110 id: impl Into<Cow<'static, str>>,
111 mark: impl Into<Cow<'static, str>>,
112 display_name: impl Into<Cow<'static, str>>,
113 ) -> Self {
114 let id = id.into();
115 let dir_name = id.clone();
116 Self {
117 id,
118 mark: mark.into(),
119 display_name: display_name.into(),
120 dir_name,
121 legacy_home_parts: &[],
122 }
123 }
124
125 pub fn known(id: &str) -> Option<Self> {
128 if id == "needle" {
129 return Some(Self::SEARCH);
130 }
131 Self::ALL.iter().find(|app| app.id() == id).cloned()
132 }
133
134 pub fn id(&self) -> &str {
135 &self.id
136 }
137
138 pub fn mark(&self) -> &str {
139 &self.mark
140 }
141
142 pub fn display_name(&self) -> &str {
143 &self.display_name
144 }
145
146 pub fn bundle_id(&self) -> String {
148 format!("io.option.{}", self.id)
149 }
150
151 pub fn dir(&self) -> PathBuf {
153 option_root().join(self.dir_name.as_ref() as &str)
154 }
155
156 pub fn config_toml(&self) -> PathBuf {
158 self.dir().join("config.toml")
159 }
160
161 pub fn cache_dir(&self) -> PathBuf {
163 self.dir().join("cache")
164 }
165
166 pub fn keys_toml(&self) -> PathBuf {
168 self.try_path("keys.toml").expect("static name")
169 }
170
171 pub fn session_toml(&self) -> PathBuf {
173 self.try_path("session.toml").expect("static name")
174 }
175
176 pub fn path(&self, relative: impl AsRef<Path>) -> PathBuf {
182 self.dir().join(relative)
183 }
184
185 pub fn try_path(&self, relative: impl AsRef<Path>) -> std::io::Result<PathBuf> {
191 let rel = relative.as_ref();
192 if rel.is_absolute() {
193 return Err(std::io::Error::new(
194 std::io::ErrorKind::InvalidInput,
195 "absolute path not allowed",
196 ));
197 }
198 if rel.components().any(|c| matches!(c, Component::ParentDir)) {
199 return Err(std::io::Error::new(
200 std::io::ErrorKind::InvalidInput,
201 "parent-dir component not allowed",
202 ));
203 }
204 Ok(self.dir().join(rel))
205 }
206
207 pub fn ensure(&self) -> std::io::Result<PathBuf> {
211 let dir = self.dir();
212 self.migrate_legacy()?;
213 std::fs::create_dir_all(&dir)?;
214 Ok(dir)
215 }
216
217 pub fn ensure_cache(&self) -> std::io::Result<PathBuf> {
221 self.ensure()?;
222 let cache = self.cache_dir();
223 std::fs::create_dir_all(&cache)?;
224 Ok(cache)
225 }
226
227 pub fn migrate_legacy(&self) -> std::io::Result<bool> {
229 if self.legacy_home_parts.is_empty() {
230 return Ok(false);
231 }
232 let home = home_dir();
233 let legacy = self
234 .legacy_home_parts
235 .iter()
236 .fold(home, |acc, part| acc.join(part));
237 migrate_dir(&legacy, &self.dir())
238 }
239}
240
241#[cfg(test)]
242mod tests {
243 use super::*;
244
245 #[test]
246 fn known_lookup() {
247 assert_eq!(App::known("opsh"), Some(App::OPSH));
248 assert_eq!(App::known("search"), Some(App::SEARCH));
249 assert_eq!(App::known("needle"), Some(App::SEARCH));
250 assert_eq!(App::known("nope"), None);
251 }
252
253 #[test]
254 fn bundle_ids() {
255 assert_eq!(App::MUSIC.bundle_id(), "io.option.music");
256 assert_eq!(App::TERMINAL.bundle_id(), "io.option.terminal");
257 assert_eq!(App::OPSH.mark(), "❯");
258 assert_eq!(App::MUSIC.mark(), "♪");
259 assert_eq!(App::MUSIC.display_name(), "optionMusic");
260 assert_eq!(App::SEARCH.bundle_id(), "io.option.search");
261 assert_eq!(App::SEARCH.mark(), "⌕");
262 assert_eq!(App::SEARCH.display_name(), "optionSearch");
263 }
264
265 #[test]
266 fn custom_app() {
267 let app = App::new("labs", "◇", "Option Labs");
268 assert_eq!(app.id(), "labs");
269 assert!(app.dir().ends_with(Path::new(".option").join("labs")));
270 }
271
272 #[test]
273 fn dynamic_app_id() {
274 let _guard = crate::test_env::lock();
275 let root = tempfile::tempdir().unwrap();
276 unsafe {
278 std::env::set_var("OPTION_HOME", root.path());
279 }
280 let id = String::from("dyn-") + "x";
281 let app = App::new(id, String::from("◇"), String::from("Dyn X"));
282 assert_eq!(app.id(), "dyn-x");
283 assert!(app.dir().ends_with("dyn-x"));
284 assert_eq!(app.dir(), root.path().join("dyn-x"));
285 unsafe {
286 std::env::remove_var("OPTION_HOME");
287 }
288 }
289
290 #[test]
291 fn try_path_ok() {
292 let _guard = crate::test_env::lock();
293 let root = tempfile::tempdir().unwrap();
294 unsafe {
296 std::env::set_var("OPTION_HOME", root.path());
297 }
298 let dir = App::FILES.dir();
299 assert_eq!(
300 App::FILES.try_path("keys.toml").unwrap(),
301 dir.join("keys.toml")
302 );
303 assert_eq!(App::FILES.try_path("a/b").unwrap(), dir.join("a/b"));
304 assert_eq!(App::FILES.try_path("").unwrap(), dir.join(""));
305 unsafe {
306 std::env::remove_var("OPTION_HOME");
307 }
308 }
309
310 #[test]
311 fn try_path_rejects() {
312 let _guard = crate::test_env::lock();
313 let root = tempfile::tempdir().unwrap();
314 unsafe {
316 std::env::set_var("OPTION_HOME", root.path());
317 }
318 assert!(App::FILES.try_path("/abs").is_err());
319 assert!(App::FILES.try_path("../x").is_err());
320 assert!(App::FILES.try_path("a/../../x").is_err());
321 unsafe {
322 std::env::remove_var("OPTION_HOME");
323 }
324 }
325
326 #[test]
327 fn music_legacy_path_segments() {
328 let _guard = crate::test_env::lock();
329 let home = tempfile::tempdir().unwrap();
330 let root = tempfile::tempdir().unwrap();
331 let legacy = home.path().join("option").join("music");
332 std::fs::create_dir_all(&legacy).unwrap();
333 std::fs::write(legacy.join("keep.txt"), b"ok").unwrap();
334 unsafe {
336 std::env::set_var("HOME", home.path());
337 std::env::set_var("OPTION_HOME", root.path());
338 }
339 assert!(App::MUSIC.migrate_legacy().unwrap());
340 assert_eq!(
341 std::fs::read_to_string(root.path().join("music").join("keep.txt")).unwrap(),
342 "ok"
343 );
344 assert!(!legacy.exists());
345 unsafe {
346 std::env::remove_var("OPTION_HOME");
347 std::env::remove_var("HOME");
348 }
349 }
350
351 #[test]
352 fn well_known_paths() {
353 assert_eq!(
354 App::TERMINAL
355 .keys_toml()
356 .file_name()
357 .and_then(|s| s.to_str()),
358 Some("keys.toml")
359 );
360 assert_eq!(
361 App::TERMINAL
362 .session_toml()
363 .file_name()
364 .and_then(|s| s.to_str()),
365 Some("session.toml")
366 );
367 assert_eq!(
368 App::MUSIC.cache_dir().file_name().and_then(|s| s.to_str()),
369 Some("cache")
370 );
371 }
372
373 #[test]
374 fn ensure_cache_creates_tree() {
375 let _guard = crate::test_env::lock();
376 let root = tempfile::tempdir().unwrap();
377 unsafe {
379 std::env::set_var("OPTION_HOME", root.path());
380 }
381 let cache = App::FILES.ensure_cache().unwrap();
382 assert!(cache.is_dir());
383 assert_eq!(cache, root.path().join("files").join("cache"));
384 unsafe {
385 std::env::remove_var("OPTION_HOME");
386 }
387 }
388}