Skip to main content

surjection_core/model/
project.rs

1//! Project manifests: `<P>/.surjection/project.toml` (shared) and
2//! `<P>/.surjection/project.local.toml` (private), mirrored in the store under
3//! `projects/<project-id>/` (SPEC 5.5).
4
5use std::collections::BTreeMap;
6
7use schemars::JsonSchema;
8use serde::{Deserialize, Serialize};
9
10use crate::error::ErrorCode;
11use crate::model::clients::ClientSelection;
12use crate::model::ids::IdKind;
13use crate::model::server::ServerBody;
14use crate::model::validate::{Diagnostics, at, join};
15use crate::model::{SCHEMA_VERSION, StoreModel};
16
17/// Both manifest files share this schema.
18#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
19#[schemars(
20    title = "Surjection project manifest (.surjection/project.toml, .surjection/project.local.toml)"
21)]
22pub struct ProjectManifest {
23    /// Schema version; always 1.
24    #[schemars(extend("const" = 1))]
25    pub schema: i64,
26    /// Project id. Required in `project.toml`, and in `project.local.toml`
27    /// when there is no shared file (a private project).
28    #[serde(default, skip_serializing_if = "Option::is_none")]
29    #[schemars(extend("pattern" = crate::model::ids::SLUG_PATTERN))]
30    pub id: Option<String>,
31    #[serde(default, skip_serializing_if = "Option::is_none")]
32    pub name: Option<String>,
33    #[serde(default, skip_serializing_if = "Option::is_none")]
34    pub defaults: Option<ProjectDefaults>,
35    /// Servers by name: overrides (`from`), suppressions (`enabled = false`)
36    /// or complete project-only definitions.
37    #[serde(default, skip_serializing_if = "Option::is_none")]
38    pub servers: Option<BTreeMap<String, ProjectServer>>,
39    #[serde(default, skip_serializing_if = "Option::is_none")]
40    pub skills: Option<ProjectSkills>,
41    #[serde(flatten)]
42    #[schemars(skip)]
43    pub extra: toml::Table,
44}
45
46impl StoreModel for ProjectManifest {
47    const SCHEMA_NAME: &'static str = "project";
48}
49
50#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
51pub struct ProjectDefaults {
52    /// Clients that receive project-scope files.
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    pub clients: Option<ClientSelection>,
55    #[serde(flatten)]
56    #[schemars(skip)]
57    pub extra: toml::Table,
58}
59
60#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
61pub struct ProjectServer {
62    /// Store server used as the base of this entry.
63    #[serde(default, skip_serializing_if = "Option::is_none")]
64    pub from: Option<String>,
65    /// `false` alone suppresses the same-named system server in this folder.
66    #[serde(default, skip_serializing_if = "Option::is_none")]
67    pub enabled: Option<bool>,
68    /// Clients that get this entry; defaults to `defaults.clients`.
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    pub clients: Option<ClientSelection>,
71    /// Inherited keys to remove, as dotted paths (`env.FOO`, `headers.X-Debug`).
72    #[serde(default, skip_serializing_if = "Option::is_none")]
73    pub unset: Option<Vec<String>>,
74    #[serde(flatten)]
75    pub body: ServerBody,
76    #[serde(flatten)]
77    #[schemars(skip)]
78    pub extra: toml::Table,
79}
80
81#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
82pub struct ProjectSkills {
83    /// Skill ids enabled in this project.
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    pub enable: Option<Vec<String>>,
86    /// `false`: link and hide via `.git/info/exclude`; `true`: copy files.
87    #[serde(default, skip_serializing_if = "Option::is_none")]
88    pub share: Option<bool>,
89    #[serde(flatten)]
90    #[schemars(skip)]
91    pub extra: toml::Table,
92}
93
94/// Which manifest file is being validated.
95#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96pub enum ManifestLayer<'a> {
97    /// `project.toml`.
98    Shared,
99    /// `project.local.toml`; `shared_id` is the id of the sibling
100    /// `project.toml`, `None` when the project is private-only.
101    Local { shared_id: Option<&'a str> },
102}
103
104impl ProjectManifest {
105    pub fn new(id: Option<String>) -> Self {
106        Self {
107            schema: SCHEMA_VERSION,
108            id,
109            name: None,
110            defaults: None,
111            servers: None,
112            skills: None,
113            extra: toml::Table::new(),
114        }
115    }
116
117    /// Validates per SPEC 5.5 and 6.2. `dir_id` is the store mirror
118    /// directory name (`projects/<dir_id>/`), when known.
119    pub fn validate(&self, layer: ManifestLayer<'_>, dir_id: Option<&str>) -> Diagnostics {
120        let mut d = Diagnostics::new();
121        match (layer, self.id.as_deref()) {
122            (ManifestLayer::Shared, None) => {
123                d.error(ErrorCode::MissingField, "id", "project.toml needs `id`");
124            }
125            (ManifestLayer::Local { shared_id: None }, None) => d.error(
126                ErrorCode::MissingField,
127                "id",
128                "project.local.toml without a project.toml is a private project and needs `id`",
129            ),
130            (ManifestLayer::Local { shared_id: Some(_) }, None) => {}
131            (ManifestLayer::Shared | ManifestLayer::Local { shared_id: None }, Some(id)) => {
132                d.check_named_id(IdKind::Project, id, "id", dir_id);
133            }
134            (
135                ManifestLayer::Local {
136                    shared_id: Some(shared),
137                },
138                Some(id),
139            ) => {
140                if d.check_id(IdKind::Project, id, "id") && id != shared {
141                    d.warning(
142                        ErrorCode::IdMismatch,
143                        "id",
144                        format!("id {id:?} differs from project.toml's {shared:?}, which wins"),
145                    );
146                }
147            }
148        }
149        if let Some(clients) = self.defaults.as_ref().and_then(|x| x.clients.as_ref()) {
150            d.check_client_selection(clients, "defaults.clients");
151        }
152        // A local file next to a shared one merges over it by server name
153        // (SPEC 6.2), so its tables may be partial.
154        let standalone = !matches!(layer, ManifestLayer::Local { shared_id: Some(_) });
155        for (name, server) in self.servers.iter().flatten() {
156            let path = join("servers", name);
157            d.check_id(IdKind::Server, name, &path);
158            server.validate_into(&path, standalone, &mut d);
159        }
160        if let Some(skills) = self
161            .skills
162            .as_ref()
163            .and_then(|skills| skills.enable.as_ref())
164        {
165            for (index, id) in skills.iter().enumerate() {
166                d.check_id(IdKind::Skill, id, &at("skills.enable", index));
167            }
168        }
169        d
170    }
171}
172
173impl ProjectServer {
174    /// `enabled = false` with no definition: hides a system server here.
175    pub fn is_suppression(&self) -> bool {
176        self.enabled == Some(false) && self.from.is_none() && self.body == ServerBody::default()
177    }
178
179    fn validate_into(&self, path: &str, standalone: bool, d: &mut Diagnostics) {
180        if let Some(from) = &self.from {
181            d.check_id(IdKind::Server, from, &join(path, "from"));
182        }
183        if let Some(clients) = &self.clients {
184            d.check_client_selection(clients, &join(path, "clients"));
185        }
186        for (index, entry) in self.unset.iter().flatten().enumerate() {
187            if entry.split('.').any(str::is_empty) {
188                d.error(
189                    ErrorCode::InvalidValue,
190                    at(&join(path, "unset"), index),
191                    format!("invalid unset path {entry:?}; expected a dotted key such as env.FOO"),
192                );
193            }
194        }
195        // Without `from` the table is a complete definition (SPEC 6.2),
196        // unless it may layer over a same-named shared entry.
197        let complete = standalone && self.from.is_none() && !self.is_suppression();
198        self.body.validate_into(path, complete, d);
199    }
200}