Skip to main content

compmd_pack/
place.rs

1//! A file's place (spec §6.4): a release and the file's path in it, `@kit/mermaid@1.2.0/dist/mermaid.js`.
2
3use std::fmt;
4use std::str::FromStr;
5
6use serde::{Deserialize, Serialize};
7
8use crate::file_path::FilePath;
9use crate::invalid::Invalid;
10use crate::release::ReleaseId;
11
12/// A file of a pack, by its place. In JSON it is `{"pack": …, "version": …, "path": …}`.
13#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
14pub struct Place {
15    /// The release.
16    #[serde(flatten)]
17    pub release: ReleaseId,
18    /// The file's path in it.
19    pub path: FilePath,
20}
21
22impl Place {
23    /// The file `path` of `release`.
24    #[must_use]
25    pub const fn new(release: ReleaseId, path: FilePath) -> Self {
26        Self { release, path }
27    }
28
29    /// The place `parts` name: `@scope`, `name@version`, then the file's path, as a URL's path after `packs/` writes
30    /// it. None when they don't name one.
31    #[must_use]
32    pub fn from_parts(parts: &[&str]) -> Option<Self> {
33        let [scope, named, path @ ..] = parts else {
34            return None;
35        };
36        Some(Self {
37            release: format!("{scope}/{named}").parse().ok()?,
38            path: FilePath::new(path.join("/")).ok()?,
39        })
40    }
41
42    /// The file `relative` names, seen from this one, in the same release; `None` when it leaves the pack.
43    #[must_use]
44    pub fn join(&self, relative: &str) -> Option<Self> {
45        Some(Self {
46            release: self.release.clone(),
47            path: self.path.join(relative)?,
48        })
49    }
50}
51
52/// `@kit/mermaid@1.2.0/dist/mermaid.js`, as diagnostics name a document of a pack (spec §10.4).
53impl fmt::Display for Place {
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        write!(f, "{}/{}", self.release, self.path)
56    }
57}
58
59impl FromStr for Place {
60    type Err = Invalid;
61
62    fn from_str(text: &str) -> Result<Self, Self::Err> {
63        let parts: Vec<&str> = text.split('/').collect();
64        Self::from_parts(&parts).ok_or_else(|| Invalid::Path(text.to_owned()))
65    }
66}
67
68#[cfg(test)]
69mod tests {
70    use super::*;
71
72    fn place(text: &str) -> Place {
73        text.parse().expect(text)
74    }
75
76    #[test]
77    fn a_place_is_a_release_and_a_path() {
78        let module = place("@kit/mermaid@1.2.0/dist/mermaid.js");
79        assert_eq!(module.release.to_string(), "@kit/mermaid@1.2.0");
80        assert_eq!(module.path.as_str(), "dist/mermaid.js");
81        assert_eq!(module.to_string(), "@kit/mermaid@1.2.0/dist/mermaid.js");
82        assert_eq!(
83            Place::new(module.release.clone(), module.path.clone()),
84            module
85        );
86        assert_eq!(
87            Place::from_parts(&["@kit", "mermaid@1.2.0", "dist", "mermaid.js"]),
88            Some(module)
89        );
90    }
91
92    #[test]
93    fn a_place_is_flat_in_json() {
94        let module = place("@kit/mermaid@1.2.0/dist/mermaid.js");
95        let json = serde_json::json!({"pack": "@kit/mermaid", "version": "1.2.0", "path": "dist/mermaid.js"});
96        assert_eq!(serde_json::to_value(&module).expect("JSON"), json);
97        assert_eq!(
98            serde_json::from_value::<Place>(json).expect("a place"),
99            module
100        );
101    }
102
103    #[test]
104    fn what_names_no_place_is_refused() {
105        for text in [
106            "@kit/mermaid@1.2.0",
107            "@kit/mermaid@1.2.0/",
108            "@kit/mermaid/a.js",
109            "kit/mermaid@1.2.0/a.js",
110            "@kit/mermaid@1.2.0/../a.js",
111            "@kit",
112        ] {
113            assert_eq!(
114                text.parse::<Place>(),
115                Err(Invalid::Path(text.to_owned())),
116                "{text}"
117            );
118        }
119        assert_eq!(Place::from_parts(&[]), None);
120    }
121
122    #[test]
123    fn a_relative_file_stays_in_its_release() {
124        let kit = place("@acme/kit@1.4.2/kit.comp.md");
125        assert_eq!(
126            kit.join("./parts/chip.comp.md"),
127            Some(place("@acme/kit@1.4.2/parts/chip.comp.md"))
128        );
129        assert_eq!(kit.join("../x.comp.md"), None);
130    }
131}