Skip to main content

mortise_core/
settings.rs

1//! Mortise's own settings: the apps it knows, kept in one JSON file on this computer.
2//!
3//! No secret is ever written here, and nothing here is written into an app folder.
4
5use std::collections::{BTreeMap, BTreeSet};
6use std::path::{Path, PathBuf};
7
8use serde::{Deserialize, Serialize};
9
10use crate::app::AppSnapshot;
11use crate::editor::Editor;
12use crate::findings::DEFAULT_COVERAGE_LIMIT;
13use crate::modules::code::propose_monogram;
14use crate::run::PhpSettings;
15use crate::runtime::environment::Environment;
16
17/// An app Mortise knows.
18#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
19pub struct AppEntry {
20    /// The app folder. Absolute.
21    pub root: PathBuf,
22    /// The name shown for the app. The name of its folder until the user changes it.
23    pub name: String,
24    /// The two letters on the app's tile.
25    pub monogram: String,
26    /// The code of each module, by module name. A code is kept once given.
27    #[serde(default)]
28    pub codes: BTreeMap<String, String>,
29    /// The order of the module index: problems first, or by name.
30    #[serde(default)]
31    pub problems_first: bool,
32    /// A module covered less than this many per cent is a warning.
33    #[serde(default = "default_coverage_limit")]
34    pub coverage_limit: u8,
35    /// The clover report, relative to the app folder or absolute. `None` lets Mortise
36    /// look in `phpunit.xml` and the usual places.
37    #[serde(default)]
38    pub coverage_report: Option<String>,
39    /// The running copies of the app that Mortise can ask for their runtime status.
40    #[serde(default)]
41    pub environments: Vec<Environment>,
42    /// The name of the environment the runtime box shows.
43    #[serde(default)]
44    pub environment: Option<String>,
45    /// How PHP runs for the app.
46    #[serde(default)]
47    pub php: PhpSettings,
48}
49
50impl AppEntry {
51    /// The name every screen shows for the app: the name set in Settings, else the
52    /// name read from the app, which is the name of its folder.
53    pub fn display_name(&self) -> &str {
54        if self.name.trim().is_empty() {
55            self.root
56                .file_name()
57                .and_then(|folder| folder.to_str())
58                .unwrap_or(&self.name)
59        } else {
60            &self.name
61        }
62    }
63
64    /// The environment the runtime box shows: the chosen one, else the first.
65    pub fn chosen_environment(&self) -> Option<&Environment> {
66        self.environments
67            .iter()
68            .find(|environment| Some(&environment.name) == self.environment.as_ref())
69            .or(self.environments.first())
70    }
71}
72
73fn default_coverage_limit() -> u8 {
74    DEFAULT_COVERAGE_LIMIT
75}
76
77/// The theme of the interface.
78#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
79#[serde(rename_all = "kebab-case")]
80pub enum ThemeChoice {
81    /// Follows the operating system and changes with it.
82    #[default]
83    System,
84    Light,
85    Dark,
86}
87
88/// Whether things move.
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
90#[serde(rename_all = "kebab-case")]
91pub enum Motion {
92    /// Follows the reduced motion setting of the operating system.
93    #[default]
94    System,
95    Reduced,
96    Full,
97}
98
99/// How high the rows of the module index are.
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
101#[serde(rename_all = "kebab-case")]
102pub enum IndexRows {
103    /// Two lines up to 20 modules, one line above.
104    #[default]
105    Automatic,
106    TwoLines,
107    OneLine,
108}
109
110/// What applies to Mortise as a whole, not to one app.
111#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
112#[serde(default)]
113pub struct General {
114    pub theme: ThemeChoice,
115    /// 100, 110, 125 or 150: every size in the interface scales with it.
116    pub text_size: u16,
117    pub motion: Motion,
118    pub index_rows: IndexRows,
119    pub editor: Editor,
120    /// The command for [`Editor::Custom`], with `{file}` and `{line}`.
121    pub editor_command: String,
122    /// On Linux: the window controls sit on the left.
123    pub window_controls_left: bool,
124    /// The platform's own title bar, with Mortise's bar under it.
125    pub system_title_bar: bool,
126    /// The width of the module index in a window that has room for it: 220 to 320.
127    pub index_width: u16,
128}
129
130impl Default for General {
131    fn default() -> Self {
132        Self {
133            theme: ThemeChoice::System,
134            text_size: 100,
135            motion: Motion::System,
136            index_rows: IndexRows::Automatic,
137            editor: Editor::VsCode,
138            editor_command: String::new(),
139            window_controls_left: false,
140            system_title_bar: false,
141            index_width: 264,
142        }
143    }
144}
145
146impl General {
147    /// The command that opens a file, with `{file}` and `{line}` where they go.
148    pub fn editor_command(&self) -> &str {
149        self.editor.command().unwrap_or(&self.editor_command)
150    }
151}
152
153/// Everything Mortise keeps between runs.
154#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
155pub struct Settings {
156    /// The apps, in the order of the rail.
157    #[serde(default)]
158    pub apps: Vec<AppEntry>,
159    /// The app that was open last, as an index into `apps`.
160    #[serde(default)]
161    pub current: Option<usize>,
162    #[serde(default)]
163    pub general: General,
164}
165
166#[derive(Debug, thiserror::Error)]
167pub enum SettingsError {
168    #[error("cannot read or write {}: {source}", path.display())]
169    Io {
170        path: PathBuf,
171        source: std::io::Error,
172    },
173    #[error("{} is not valid: {message}", path.display())]
174    Invalid { path: PathBuf, message: String },
175}
176
177impl Settings {
178    /// Where the settings file is: `settings.json` in the config folder of the
179    /// platform, or in the folder named by `MORTISE_CONFIG_DIR`.
180    pub fn default_path() -> Option<PathBuf> {
181        let dir = match std::env::var_os("MORTISE_CONFIG_DIR") {
182            Some(dir) if !dir.is_empty() => PathBuf::from(dir),
183            _ => directories::ProjectDirs::from("", "", "Mortise")?
184                .config_dir()
185                .to_owned(),
186        };
187        Some(dir.join("settings.json"))
188    }
189
190    /// Loads the settings. A file that does not exist yet gives empty settings.
191    pub fn load(path: &Path) -> Result<Self, SettingsError> {
192        let json = match std::fs::read(path) {
193            Ok(json) => json,
194            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
195                return Ok(Self::default());
196            }
197            Err(source) => {
198                return Err(SettingsError::Io {
199                    path: path.to_owned(),
200                    source,
201                });
202            }
203        };
204        let mut settings: Self =
205            serde_json::from_slice(&json).map_err(|error| SettingsError::Invalid {
206                path: path.to_owned(),
207                message: error.to_string(),
208            })?;
209        if settings
210            .current
211            .is_some_and(|current| current >= settings.apps.len())
212        {
213            settings.current = None;
214        }
215        Ok(settings)
216    }
217
218    /// Saves the settings. The file is written beside its place and then moved over
219    /// it, so a crash cannot leave half a file.
220    pub fn save(&self, path: &Path) -> Result<(), SettingsError> {
221        let io = |source| SettingsError::Io {
222            path: path.to_owned(),
223            source,
224        };
225        if let Some(dir) = path.parent() {
226            std::fs::create_dir_all(dir).map_err(io)?;
227        }
228        let json = serde_json::to_vec_pretty(self).expect("settings are plain data");
229        let partial = path.with_extension("json.partial");
230        std::fs::write(&partial, json).map_err(io)?;
231        std::fs::rename(&partial, path).map_err(io)
232    }
233
234    /// The place of the app in `root` among the apps, if Mortise knows it.
235    pub fn position(&self, root: &Path) -> Option<usize> {
236        let wanted = same_folder(root);
237        self.apps
238            .iter()
239            .position(|app| same_folder(&app.root) == wanted)
240    }
241
242    /// Adds an app after the others and returns its place. The monogram differs
243    /// from those of the other apps.
244    pub fn add(&mut self, app: &AppSnapshot) -> usize {
245        let taken: BTreeSet<String> = self.apps.iter().map(|app| app.monogram.clone()).collect();
246        self.apps.push(AppEntry {
247            root: app.root.clone(),
248            name: app.name.clone(),
249            monogram: propose_monogram(&app.name, &taken),
250            codes: app.codes(),
251            problems_first: false,
252            coverage_limit: DEFAULT_COVERAGE_LIMIT,
253            coverage_report: None,
254            environments: Vec::new(),
255            environment: None,
256            php: PhpSettings::default(),
257        });
258        self.apps.len() - 1
259    }
260
261    /// Forgets an app. Its folder and files stay as they are.
262    pub fn remove(&mut self, index: usize) -> AppEntry {
263        let entry = self.apps.remove(index);
264        self.current = match self.current {
265            Some(current) if current == index => None,
266            Some(current) if current > index => Some(current - 1),
267            other => other,
268        };
269        entry
270    }
271}
272
273/// A folder in a form that is equal for two ways of writing the same folder.
274fn same_folder(path: &Path) -> PathBuf {
275    std::fs::canonicalize(path)
276        .or_else(|_| std::path::absolute(path))
277        .unwrap_or_else(|_| path.to_owned())
278}
279
280#[cfg(test)]
281mod tests {
282    use super::*;
283
284    fn entry(name: &str, monogram: &str) -> AppEntry {
285        AppEntry {
286            root: PathBuf::from("/code").join(name),
287            name: name.into(),
288            monogram: monogram.into(),
289            codes: BTreeMap::from([("Checkout".to_owned(), "CHK".to_owned())]),
290            problems_first: false,
291            coverage_limit: 50,
292            coverage_report: None,
293            environments: Vec::new(),
294            environment: None,
295            php: PhpSettings::default(),
296        }
297    }
298
299    #[test]
300    fn the_display_name_is_the_settings_name_else_the_folder() {
301        let mut app = entry("shop-api", "SA");
302        app.name = "Shop".into();
303        assert_eq!(app.display_name(), "Shop");
304        app.name = "  ".into();
305        assert_eq!(app.display_name(), "shop-api");
306    }
307
308    #[test]
309    fn a_missing_file_is_empty_settings() {
310        let dir = tempfile::tempdir().unwrap();
311        assert_eq!(
312            Settings::load(&dir.path().join("settings.json")).unwrap(),
313            Settings::default()
314        );
315    }
316
317    #[test]
318    fn what_is_saved_is_loaded_again() {
319        let dir = tempfile::tempdir().unwrap();
320        // The folder does not exist yet.
321        let path = dir.path().join("mortise").join("settings.json");
322        let settings = Settings {
323            apps: vec![
324                entry("shop-api", "SA"),
325                AppEntry {
326                    php: PhpSettings {
327                        runner: Some(crate::RunnerKind::Docker {
328                            service: "app".into(),
329                        }),
330                        working_folder: Some("api".into()),
331                        time_limit_minutes: 25,
332                    },
333                    ..entry("crm", "CR")
334                },
335            ],
336            current: Some(1),
337            general: General {
338                text_size: 125,
339                theme: ThemeChoice::Dark,
340                ..General::default()
341            },
342        };
343        settings.save(&path).unwrap();
344        assert_eq!(Settings::load(&path).unwrap(), settings);
345        // Nothing is left beside the file.
346        assert_eq!(
347            std::fs::read_dir(path.parent().unwrap()).unwrap().count(),
348            1
349        );
350    }
351
352    #[test]
353    fn an_environment_is_saved_without_a_secret() {
354        use crate::runtime::environment::Credentials;
355        let dir = tempfile::tempdir().unwrap();
356        let path = dir.path().join("settings.json");
357        let staging = Environment {
358            name: "staging".into(),
359            base_url: "https://staging.shop-api.example".into(),
360            path: "actuator".into(),
361            credentials: Credentials::Basic {
362                user: "mortise".into(),
363            },
364        };
365        let settings = Settings {
366            apps: vec![AppEntry {
367                environments: vec![staging.clone()],
368                environment: Some("staging".into()),
369                ..entry("shop-api", "SA")
370            }],
371            ..Settings::default()
372        };
373        settings.save(&path).unwrap();
374        let loaded = Settings::load(&path).unwrap();
375        assert_eq!(loaded.apps[0].chosen_environment(), Some(&staging));
376        // The file holds the kind and the user name, and no field for a secret.
377        let json: serde_json::Value =
378            serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
379        assert_eq!(
380            json["apps"][0]["environments"][0]["credentials"],
381            serde_json::json!({"kind": "basic", "user": "mortise"})
382        );
383    }
384
385    #[test]
386    fn a_broken_file_is_an_error_and_is_not_touched() {
387        let dir = tempfile::tempdir().unwrap();
388        let path = dir.path().join("settings.json");
389        std::fs::write(&path, "{ not json").unwrap();
390        assert!(matches!(
391            Settings::load(&path),
392            Err(SettingsError::Invalid { .. })
393        ));
394        assert_eq!(std::fs::read_to_string(&path).unwrap(), "{ not json");
395    }
396
397    #[test]
398    fn a_current_app_that_is_gone_is_dropped() {
399        let dir = tempfile::tempdir().unwrap();
400        let path = dir.path().join("settings.json");
401        std::fs::write(
402            &path,
403            r#"{"apps": [{"root": "/code/a", "name": "a", "monogram": "AA"}], "current": 3}"#,
404        )
405        .unwrap();
406        let settings = Settings::load(&path).unwrap();
407        assert_eq!(settings.current, None);
408        // A file from before the PHP settings loads with their defaults.
409        assert_eq!(settings.apps[0].php, PhpSettings::default());
410    }
411
412    #[test]
413    fn removing_an_app_keeps_the_current_one() {
414        let mut settings = Settings {
415            apps: vec![entry("a", "AA"), entry("b", "BB"), entry("c", "CC")],
416            current: Some(2),
417            general: General::default(),
418        };
419        assert_eq!(settings.remove(0).name, "a");
420        assert_eq!(settings.current, Some(1));
421        assert_eq!(settings.remove(1).name, "c");
422        assert_eq!(settings.current, None);
423    }
424
425    #[test]
426    fn the_same_folder_written_two_ways_is_one_app() {
427        let dir = tempfile::tempdir().unwrap();
428        let root = dir.path().join("shop-api");
429        std::fs::create_dir(&root).unwrap();
430        let settings = Settings {
431            apps: vec![AppEntry {
432                root: root.clone(),
433                ..entry("shop-api", "SA")
434            }],
435            current: None,
436            general: General::default(),
437        };
438        assert_eq!(settings.position(&root), Some(0));
439        assert_eq!(
440            settings.position(&root.join("..").join("shop-api")),
441            Some(0)
442        );
443        assert_eq!(settings.position(&dir.path().join("other")), None);
444    }
445}