Skip to main content

mortise_core/boundary/
rules.rs

1//! The boundary rules of an app, kept in `mortise.json` in the app folder so that a
2//! team shares them. The file also says whether `mortise check` fails CI, and may set
3//! the coverage limit and report of the app.
4//!
5//! It is the only file Mortise writes into an app without a command, and only when
6//! the interface asks after the user confirmed. No secret is ever written to it.
7
8use std::collections::BTreeMap;
9use std::io::Write;
10use std::path::{Path, PathBuf};
11
12use serde::{Deserialize, Serialize};
13
14/// The name of the rules file in the app folder.
15pub const RULES_FILE: &str = "mortise.json";
16
17/// The rules of this version, and whether a broken one fails CI.
18#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
19pub struct Rules {
20    /// No circular use: two modules must not use each other, directly or through others.
21    pub no_circular_use: bool,
22    /// Other modules use only a module's public surface.
23    pub public_surface_only: bool,
24    /// For a module without an accepted public surface, the folders that count as
25    /// public: a class in one of them may be used by other modules.
26    pub public_folders: Vec<String>,
27    /// Allowed use: the modules each module may use. `None` when the file has no
28    /// `allowed-use` key; the rule then checks nothing.
29    #[serde(default, skip_serializing_if = "Option::is_none")]
30    pub allowed_use: Option<AllowedUse>,
31    /// "Fail CI when a rule breaks": `mortise check` exits 1 when it finds a problem.
32    /// Off, it prints the same report and exits 0.
33    pub fail_ci: bool,
34}
35
36impl Default for Rules {
37    fn default() -> Self {
38        Self {
39            no_circular_use: true,
40            public_surface_only: true,
41            public_folders: vec!["Contracts".to_owned(), "Events".to_owned()],
42            allowed_use: None,
43            fail_ci: true,
44        }
45    }
46}
47
48/// The rule allowed use: the `allowed-use` object of `mortise.json`. nwidart/larch reads
49/// the same key.
50#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
51pub struct AllowedUse {
52    #[serde(default = "yes")]
53    pub enabled: bool,
54    /// For each module with a list, the modules it may use. An empty list means no
55    /// module. A module without a list is not checked. A save writes them by name.
56    #[serde(default)]
57    pub modules: BTreeMap<String, Vec<String>>,
58}
59
60impl AllowedUse {
61    /// True when `from` may use `to`: `from` has no list, or its list names `to`.
62    pub fn allows(&self, from: &str, to: &str) -> bool {
63        self.modules
64            .get(from)
65            .is_none_or(|list| list.iter().any(|name| name == to))
66    }
67}
68
69/// The coverage limit and report of an app: the `coverage` object of `mortise.json`,
70/// or the flags of `mortise check`. A value that is set wins over the settings of the
71/// window.
72#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
73pub struct CoverageSettings {
74    /// A module covered less than this many per cent is a warning. 0 to 100.
75    #[serde(default, skip_serializing_if = "Option::is_none")]
76    pub limit: Option<u8>,
77    /// The clover report, relative to the app folder or absolute.
78    #[serde(default, skip_serializing_if = "Option::is_none")]
79    pub report: Option<PathBuf>,
80}
81
82/// Where the rules of a snapshot came from.
83#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
84pub enum RulesSource {
85    /// The app has no `mortise.json`: the defaults apply.
86    Defaults,
87    /// Read from `mortise.json`.
88    File,
89    /// `mortise.json` could not be read as rules: the defaults apply. The message is the parser's.
90    Invalid(String),
91}
92
93#[derive(Debug, thiserror::Error)]
94pub enum RulesError {
95    #[error("cannot write {}: {source}", path.display())]
96    Io {
97        path: PathBuf,
98        source: std::io::Error,
99    },
100    /// The file holds something that is not a JSON object, which Mortise will not replace.
101    #[error("{} is not a JSON object: {message}", path.display())]
102    Invalid { path: PathBuf, message: String },
103}
104
105/// The shape of the file. Every key may be left out; a missing one takes its default.
106///
107/// ```json
108/// {
109///     "rules": {
110///         "no-circular-use": true,
111///         "public-surface-only": { "enabled": true, "folders": ["Contracts", "Events"] },
112///         "allowed-use": { "enabled": true, "modules": { "Audit": [], "History": ["Audit"] } }
113///     },
114///     "ci": { "fail": true },
115///     "coverage": { "limit": 70, "report": "build/coverage/clover.xml" }
116/// }
117/// ```
118#[derive(Serialize, Deserialize)]
119struct CiInFile {
120    #[serde(default = "yes")]
121    fail: bool,
122}
123
124impl Default for CiInFile {
125    fn default() -> Self {
126        Self { fail: true }
127    }
128}
129
130#[derive(Serialize, Deserialize)]
131struct RulesInFile {
132    #[serde(rename = "no-circular-use", default = "yes")]
133    no_circular_use: bool,
134    #[serde(rename = "public-surface-only", default, deserialize_with = "object")]
135    public_surface_only: PublicSurfaceInFile,
136    #[serde(
137        rename = "allowed-use",
138        default,
139        deserialize_with = "some_object",
140        skip_serializing_if = "Option::is_none"
141    )]
142    allowed_use: Option<AllowedUse>,
143}
144
145#[derive(Serialize, Deserialize)]
146struct PublicSurfaceInFile {
147    #[serde(default = "yes")]
148    enabled: bool,
149    #[serde(default = "default_folders")]
150    folders: Vec<String>,
151}
152
153impl Default for PublicSurfaceInFile {
154    fn default() -> Self {
155        Self {
156            enabled: true,
157            folders: default_folders(),
158        }
159    }
160}
161
162impl Default for RulesInFile {
163    fn default() -> Self {
164        Self {
165            no_circular_use: true,
166            public_surface_only: PublicSurfaceInFile::default(),
167            allowed_use: None,
168        }
169    }
170}
171
172/// A struct of the file from a JSON object only. serde also takes a list for the fields
173/// of a struct, so `[false]` would read as `{ "fail": false }`.
174fn object<'de, D, T>(deserializer: D) -> Result<T, D::Error>
175where
176    D: serde::Deserializer<'de>,
177    T: serde::de::DeserializeOwned,
178{
179    use serde::de::Error;
180    let value = serde_json::Value::deserialize(deserializer)?;
181    if !value.is_object() {
182        return Err(D::Error::custom("expected a JSON object"));
183    }
184    serde_json::from_value(value).map_err(D::Error::custom)
185}
186
187/// A key of the file that may be absent, from a JSON object only.
188fn some_object<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
189where
190    D: serde::Deserializer<'de>,
191    T: serde::de::DeserializeOwned,
192{
193    object(deserializer).map(Some)
194}
195
196/// One key of the file at the top: its default when it is absent.
197fn section<T: serde::de::DeserializeOwned + Default>(
198    file: &serde_json::Map<String, serde_json::Value>,
199    key: &str,
200) -> Result<T, String> {
201    match file.get(key) {
202        None => Ok(T::default()),
203        Some(value) if value.is_object() => {
204            serde_json::from_value(value.clone()).map_err(|error| format!("{key}: {error}"))
205        }
206        Some(_) => Err(format!("{key} is not a JSON object")),
207    }
208}
209
210fn yes() -> bool {
211    true
212}
213
214fn default_folders() -> Vec<String> {
215    Rules::default().public_folders
216}
217
218impl Rules {
219    /// Reads the rules of the app in `root`.
220    pub fn load(root: &Path) -> (Self, RulesSource) {
221        let file = load_file(root);
222        (file.rules, file.source)
223    }
224
225    /// Writes the rules to `mortise.json` in `root`. Other keys of the file are kept.
226    pub fn save(&self, root: &Path) -> Result<(), RulesError> {
227        let path = root.join(RULES_FILE);
228        let mut file = match std::fs::read(&path) {
229            Ok(json) => serde_json::from_slice::<serde_json::Map<String, serde_json::Value>>(&json)
230                .map_err(|error| RulesError::Invalid {
231                    path: path.clone(),
232                    message: error.to_string(),
233                })?,
234            Err(error) if error.kind() == std::io::ErrorKind::NotFound => serde_json::Map::new(),
235            Err(source) => return Err(RulesError::Io { path, source }),
236        };
237        let rules = RulesInFile {
238            no_circular_use: self.no_circular_use,
239            public_surface_only: PublicSurfaceInFile {
240                enabled: self.public_surface_only,
241                folders: self.public_folders.clone(),
242            },
243            allowed_use: self.allowed_use.clone(),
244        };
245        file.insert(
246            "rules".to_owned(),
247            serde_json::to_value(rules).expect("rules are plain data"),
248        );
249        // Other keys of `ci` are kept too.
250        let fail = serde_json::Value::Bool(self.fail_ci);
251        match file.get_mut("ci") {
252            Some(serde_json::Value::Object(ci)) => {
253                ci.insert("fail".to_owned(), fail);
254            }
255            _ => {
256                let ci = serde_json::to_value(CiInFile { fail: self.fail_ci })
257                    .expect("ci is plain data");
258                file.insert("ci".to_owned(), ci);
259            }
260        }
261
262        // Four spaces and a line end, like the other JSON files of a Laravel app.
263        let mut json = Vec::new();
264        let formatter = serde_json::ser::PrettyFormatter::with_indent(b"    ");
265        let mut serializer = serde_json::Serializer::with_formatter(&mut json, formatter);
266        file.serialize(&mut serializer)
267            .expect("a map of JSON values can be written");
268        json.push(b'\n');
269
270        let io = |source| RulesError::Io {
271            path: path.clone(),
272            source,
273        };
274        // A temporary file beside it, then put in its place in one step, so that the
275        // file is never half written. Its name is unique, so no file of the user is
276        // touched.
277        let mut builder = tempfile::Builder::new();
278        builder.prefix(".mortise.json.").suffix(".tmp");
279        // A temporary file is for its owner only. Ask for what `std::fs::write` gives.
280        #[cfg(unix)]
281        {
282            use std::os::unix::fs::PermissionsExt;
283            builder.permissions(std::fs::Permissions::from_mode(0o666));
284        }
285        let mut temporary = builder.tempfile_in(root).map_err(io)?;
286        temporary.write_all(&json).map_err(io)?;
287        // This replaces the file on Windows too.
288        temporary.persist(&path).map_err(|error| io(error.error))?;
289        Ok(())
290    }
291
292    /// True when a class is part of the public surface of its module by the folder
293    /// list. `inside` is the class name after the module's namespace:
294    /// `Contracts\PaymentGateway`.
295    pub fn is_public(&self, inside: &str) -> bool {
296        let Some((folder, _)) = inside.split_once('\\') else {
297            // A class directly in the module's namespace is in no folder.
298            return false;
299        };
300        self.public_folders
301            .iter()
302            .any(|public| public.eq_ignore_ascii_case(folder))
303    }
304}
305
306/// What `mortise.json` holds, as a read takes it.
307pub(crate) struct RulesFile {
308    pub(crate) rules: Rules,
309    pub(crate) source: RulesSource,
310    pub(crate) coverage: CoverageSettings,
311    /// Why the `coverage` object is ignored, when it cannot be read. The rules and `ci`
312    /// stay as read: a broken `coverage` does not throw them away.
313    pub(crate) coverage_ignored: Option<String>,
314}
315
316/// Reads `mortise.json` in `root`. A file whose `rules` or `ci` cannot be read gives the
317/// defaults for everything. A `coverage` that cannot be read is ignored on its own.
318pub(crate) fn load_file(root: &Path) -> RulesFile {
319    let defaults = |source| RulesFile {
320        rules: Rules::default(),
321        source,
322        coverage: CoverageSettings::default(),
323        coverage_ignored: None,
324    };
325    let Ok(json) = std::fs::read(root.join(RULES_FILE)) else {
326        return defaults(RulesSource::Defaults);
327    };
328    let file = match serde_json::from_slice::<serde_json::Map<String, serde_json::Value>>(&json) {
329        Ok(file) => file,
330        Err(error) => return defaults(RulesSource::Invalid(error.to_string())),
331    };
332    let (rules, ci) = match section::<RulesInFile>(&file, "rules")
333        .and_then(|rules| Ok((rules, section::<CiInFile>(&file, "ci")?)))
334    {
335        Ok(read) => read,
336        Err(message) => return defaults(RulesSource::Invalid(message)),
337    };
338    let coverage =
339        section::<CoverageSettings>(&file, "coverage").and_then(|coverage| match coverage.limit {
340            Some(limit) if limit > 100 => Err(format!("coverage limit {limit} is over 100")),
341            _ => Ok(coverage),
342        });
343    let (coverage, coverage_ignored) = match coverage {
344        Ok(coverage) => (coverage, None),
345        Err(message) => (CoverageSettings::default(), Some(message)),
346    };
347    RulesFile {
348        rules: Rules {
349            no_circular_use: rules.no_circular_use,
350            public_surface_only: rules.public_surface_only.enabled,
351            public_folders: rules.public_surface_only.folders,
352            allowed_use: rules.allowed_use,
353            fail_ci: ci.fail,
354        },
355        source: RulesSource::File,
356        coverage,
357        coverage_ignored,
358    }
359}
360
361#[cfg(test)]
362mod tests {
363    use super::*;
364
365    #[test]
366    fn no_file_means_the_defaults() {
367        let app = tempfile::tempdir().unwrap();
368        let (rules, source) = Rules::load(app.path());
369        assert_eq!(source, RulesSource::Defaults);
370        assert!(rules.no_circular_use && rules.public_surface_only);
371        assert_eq!(rules.public_folders, ["Contracts", "Events"]);
372        assert_eq!(rules.allowed_use, None);
373    }
374
375    #[test]
376    fn what_is_saved_is_loaded_again_and_other_keys_are_kept() {
377        let app = tempfile::tempdir().unwrap();
378        let path = app.path().join(RULES_FILE);
379        std::fs::write(
380            &path,
381            r#"{"team": "shop", "rules": {"no-circular-use": true}, "ci": {"runner": "linux"}, "coverage": {"limit": 70}}"#,
382        )
383        .unwrap();
384        // A file of the user with a name close to the temporary one.
385        let partial = app.path().join("mortise.json.partial");
386        std::fs::write(&partial, "mine").unwrap();
387
388        let rules = Rules {
389            no_circular_use: false,
390            public_surface_only: true,
391            public_folders: vec!["Contracts".into(), "Api".into()],
392            allowed_use: Some(AllowedUse {
393                enabled: false,
394                modules: BTreeMap::from([
395                    ("History".into(), vec!["Billing".into(), "Audit".into()]),
396                    ("Audit".into(), vec![]),
397                ]),
398            }),
399            fail_ci: false,
400        };
401        rules.save(app.path()).unwrap();
402        assert_eq!(Rules::load(app.path()), (rules, RulesSource::File));
403        assert_eq!(load_file(app.path()).coverage.limit, Some(70));
404
405        let text = std::fs::read_to_string(&path).unwrap();
406        assert_eq!(
407            text,
408            r#"{
409    "team": "shop",
410    "rules": {
411        "no-circular-use": false,
412        "public-surface-only": {
413            "enabled": true,
414            "folders": [
415                "Contracts",
416                "Api"
417            ]
418        },
419        "allowed-use": {
420            "enabled": false,
421            "modules": {
422                "Audit": [],
423                "History": [
424                    "Billing",
425                    "Audit"
426                ]
427            }
428        }
429    },
430    "ci": {
431        "runner": "linux",
432        "fail": false
433    },
434    "coverage": {
435        "limit": 70
436    }
437}
438"#
439        );
440        assert_eq!(std::fs::read_to_string(&partial).unwrap(), "mine");
441        assert_eq!(
442            std::fs::read_dir(app.path()).unwrap().count(),
443            2,
444            "nothing is left beside it"
445        );
446        // Readable as a file that `std::fs::write` makes.
447        #[cfg(unix)]
448        {
449            use std::os::unix::fs::PermissionsExt;
450            let mode = |path: &Path| std::fs::metadata(path).unwrap().permissions().mode();
451            assert_eq!(mode(&path), mode(&partial));
452        }
453    }
454
455    #[test]
456    fn missing_keys_take_their_default() {
457        let app = tempfile::tempdir().unwrap();
458        let path = app.path().join(RULES_FILE);
459        std::fs::write(
460            &path,
461            r#"{"rules": {"public-surface-only": {"folders": ["Api"]}}}"#,
462        )
463        .unwrap();
464        let (rules, source) = Rules::load(app.path());
465        assert_eq!(source, RulesSource::File);
466        assert!(rules.no_circular_use && rules.public_surface_only);
467        assert_eq!(rules.public_folders, ["Api"]);
468        assert!(rules.fail_ci, "CI fails when the file does not say");
469        assert_eq!(rules.allowed_use, None, "no key, no rule");
470
471        std::fs::write(&path, r#"{"rules": {"allowed-use": {}}}"#).unwrap();
472        let (rules, _) = Rules::load(app.path());
473        assert_eq!(
474            rules.allowed_use,
475            Some(AllowedUse {
476                enabled: true,
477                modules: BTreeMap::new(),
478            })
479        );
480
481        std::fs::write(&path, r#"{"coverage": {"report": "build/clover.xml"}}"#).unwrap();
482        let file = load_file(app.path());
483        assert_eq!(
484            (file.rules, file.source),
485            (Rules::default(), RulesSource::File)
486        );
487        assert_eq!(
488            file.coverage,
489            CoverageSettings {
490                limit: None,
491                report: Some("build/clover.xml".into()),
492            }
493        );
494    }
495
496    #[test]
497    fn a_file_that_cannot_be_read_as_rules_gives_the_defaults_and_is_not_replaced() {
498        let app = tempfile::tempdir().unwrap();
499        let path = app.path().join(RULES_FILE);
500        for content in [
501            "{ not json",
502            "[1, 2]",
503            r#"{"rules": {"no-circular-use": "yes"}}"#,
504            r#"{"ci": {"fail": "no"}}"#,
505            // A list is not taken for the fields of an object.
506            r#"{"ci": [false]}"#,
507            r#"{"rules": [false]}"#,
508            r#"{"rules": {"public-surface-only": [false]}}"#,
509            r#"{"rules": {"allowed-use": [true]}}"#,
510            r#"{"rules": {"allowed-use": {"modules": ["Audit"]}}}"#,
511            r#"{"rules": {"allowed-use": {"modules": {"Audit": "Billing"}}}}"#,
512        ] {
513            std::fs::write(&path, content).unwrap();
514            let (rules, source) = Rules::load(app.path());
515            assert_eq!(rules, Rules::default(), "{content}");
516            assert!(matches!(source, RulesSource::Invalid(_)), "{content}");
517        }
518        std::fs::write(&path, "[1, 2]").unwrap();
519        assert!(matches!(
520            Rules::default().save(app.path()),
521            Err(RulesError::Invalid { .. })
522        ));
523        assert_eq!(std::fs::read_to_string(&path).unwrap(), "[1, 2]");
524    }
525
526    #[test]
527    fn a_coverage_that_cannot_be_read_is_ignored_and_keeps_the_rules() {
528        let app = tempfile::tempdir().unwrap();
529        let path = app.path().join(RULES_FILE);
530        for (coverage, why) in [
531            (r#"{"limit": 101}"#, "coverage limit 101 is over 100"),
532            ("[70]", "coverage is not a JSON object"),
533        ] {
534            std::fs::write(
535                &path,
536                format!(r#"{{"rules": {{"no-circular-use": false}}, "ci": {{"fail": false}}, "coverage": {coverage}}}"#),
537            )
538            .unwrap();
539            let file = load_file(app.path());
540            assert_eq!(file.source, RulesSource::File);
541            assert!(!file.rules.no_circular_use && !file.rules.fail_ci);
542            assert_eq!(file.coverage, CoverageSettings::default());
543            assert_eq!(file.coverage_ignored.as_deref(), Some(why));
544        }
545    }
546
547    #[test]
548    fn a_class_is_public_by_its_first_folder() {
549        let rules = Rules::default();
550        assert!(rules.is_public(r"Contracts\PaymentGateway"));
551        assert!(rules.is_public(r"Events\Billing\InvoicePaid"));
552        assert!(rules.is_public(r"contracts\PaymentGateway"));
553        assert!(!rules.is_public(r"Models\Invoice"));
554        assert!(!rules.is_public("Invoice"));
555        assert!(!rules.is_public(r"ContractsExtra\Thing"));
556    }
557}