Skip to main content

litz_project/
lib.rs

1//! One portable Litz project.
2//!
3//! A project is the circuit, the source files that belong to it, and the few
4//! settings a runner needs. It is a single JSON document with a format tag and
5//! a version, so it can be written by one frontend, read by another, and kept
6//! in version control without a database.
7//!
8//! The circuit itself stays `diagram.json`-shaped: this crate does not invent
9//! a second schematic format. What it adds is the parts a project needs around
10//! it — files, file groups for multi-board canvases, and options — plus the
11//! validation that keeps a hand-edited file from walking out of its own
12//! directory.
13//!
14//! ```
15//! use litz_project::Project;
16//!
17//! let mut project = Project::new("blink");
18//! project.add_file("main.c", "int main(void) { return 0; }");
19//! let text = project.to_json().unwrap();
20//! let reopened = Project::from_json(&text).unwrap();
21//! assert_eq!(reopened.name, "blink");
22//! assert_eq!(reopened.files[0].name, "main.c");
23//! ```
24
25#![forbid(unsafe_code)]
26
27use litz_diagram::Circuit;
28use serde::{Deserialize, Serialize};
29use std::collections::{BTreeMap, BTreeSet};
30use std::path::Path;
31
32/// The tag every project file carries.
33pub const FORMAT: &str = "litz-project";
34/// The format revision this crate writes. Older files load unchanged.
35pub const VERSION: u32 = 1;
36
37fn empty_circuit() -> Circuit {
38    Circuit {
39        version: 1,
40        author: None,
41        editor: None,
42        parts: Vec::new(),
43        connections: Vec::new(),
44        extra: BTreeMap::new(),
45    }
46}
47
48fn format_tag() -> String {
49    FORMAT.to_string()
50}
51
52fn format_version() -> u32 {
53    VERSION
54}
55
56/// One source file in the project.
57#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
58pub struct SourceFile {
59    pub name: String,
60    #[serde(default)]
61    pub content: String,
62    /// Which board's file group this file belongs to, for a multi-board
63    /// project. `None` is the project's own group.
64    #[serde(default, skip_serializing_if = "Option::is_none")]
65    pub group: Option<String>,
66}
67
68impl SourceFile {
69    pub fn new(name: impl Into<String>, content: impl Into<String>) -> Self {
70        Self {
71            name: name.into(),
72            content: content.into(),
73            group: None,
74        }
75    }
76
77    pub fn in_group(self, group: impl Into<String>) -> Self {
78        Self {
79            group: Some(group.into()),
80            ..self
81        }
82    }
83}
84
85/// Runner settings stored with the project.
86#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
87pub struct Options {
88    /// `micropython`, `firmware`, or a board-specific runtime name.
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub runtime: Option<String>,
91    /// The image the project boots, relative to the project file.
92    #[serde(default, skip_serializing_if = "Option::is_none")]
93    pub firmware: Option<String>,
94    /// Treat warnings as failures, matching `litz --strict`.
95    #[serde(default)]
96    pub strict: bool,
97}
98
99/// A complete project.
100#[derive(Debug, Clone, Serialize, Deserialize)]
101pub struct Project {
102    #[serde(default = "format_tag")]
103    pub format: String,
104    #[serde(default = "format_version")]
105    pub version: u32,
106    #[serde(default)]
107    pub name: String,
108    #[serde(default = "empty_circuit")]
109    pub circuit: Circuit,
110    #[serde(default)]
111    pub files: Vec<SourceFile>,
112    #[serde(default)]
113    pub options: Options,
114    /// Unknown keys survive a save, as in the circuit format.
115    #[serde(flatten)]
116    pub extra: BTreeMap<String, serde_json::Value>,
117}
118
119/// Why a project file was refused.
120#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
121pub enum ProjectError {
122    #[error("not a Litz project (format {0:?})")]
123    WrongFormat(String),
124    #[error("project version {0} is newer than this build understands ({VERSION})")]
125    NewerVersion(u32),
126    #[error("file name {0:?} is empty")]
127    EmptyFileName(String),
128    #[error("file name {0:?} must be a plain name, not a path")]
129    UnsafeFileName(String),
130    #[error("file name {0:?} is used twice")]
131    DuplicateFileName(String),
132    #[error("{0}")]
133    Io(String),
134    #[error("{0}")]
135    Json(String),
136}
137
138impl Project {
139    /// A new, empty project.
140    pub fn new(name: impl Into<String>) -> Self {
141        Self {
142            format: FORMAT.to_string(),
143            version: VERSION,
144            name: name.into(),
145            circuit: empty_circuit(),
146            files: Vec::new(),
147            options: Options::default(),
148            extra: BTreeMap::new(),
149        }
150    }
151
152    /// Add or replace a file in the project's own group.
153    pub fn add_file(
154        &mut self,
155        name: impl Into<String>,
156        content: impl Into<String>,
157    ) -> &mut SourceFile {
158        let file = SourceFile::new(name, content);
159        self.files.retain(|f| f.name != file.name);
160        self.files.push(file);
161        self.files.last_mut().expect("just pushed")
162    }
163
164    pub fn file(&self, name: &str) -> Option<&SourceFile> {
165        self.files.iter().find(|f| f.name == name)
166    }
167
168    /// Files belonging to one board's group.
169    pub fn group(&self, group: Option<&str>) -> impl Iterator<Item = &SourceFile> {
170        self.files
171            .iter()
172            .filter(move |f| f.group.as_deref() == group)
173    }
174
175    /// Structural checks a hand-edited file can fail.
176    pub fn validate(&self) -> Result<(), ProjectError> {
177        if self.format != FORMAT {
178            return Err(ProjectError::WrongFormat(self.format.clone()));
179        }
180        if self.version > VERSION {
181            return Err(ProjectError::NewerVersion(self.version));
182        }
183        let mut seen = BTreeSet::new();
184        for file in &self.files {
185            if file.name.trim().is_empty() {
186                return Err(ProjectError::EmptyFileName(file.name.clone()));
187            }
188            let safe = Path::new(&file.name)
189                .components()
190                .all(|c| matches!(c, std::path::Component::Normal(_)));
191            if !safe || file.name.contains('/') || file.name.contains('\\') {
192                return Err(ProjectError::UnsafeFileName(file.name.clone()));
193            }
194            if !seen.insert(file.name.clone()) {
195                return Err(ProjectError::DuplicateFileName(file.name.clone()));
196            }
197        }
198        Ok(())
199    }
200
201    pub fn to_json(&self) -> Result<String, ProjectError> {
202        serde_json::to_string_pretty(self).map_err(|e| ProjectError::Json(e.to_string()))
203    }
204
205    pub fn from_json(text: &str) -> Result<Self, ProjectError> {
206        let project: Self =
207            serde_json::from_str(text).map_err(|e| ProjectError::Json(e.to_string()))?;
208        project.validate()?;
209        Ok(project)
210    }
211
212    pub fn save(&self, path: &Path) -> Result<(), ProjectError> {
213        self.validate()?;
214        let text = self.to_json()?;
215        std::fs::write(path, text).map_err(|e| ProjectError::Io(format!("{}: {e}", path.display())))
216    }
217
218    pub fn load(path: &Path) -> Result<Self, ProjectError> {
219        let text = std::fs::read_to_string(path)
220            .map_err(|e| ProjectError::Io(format!("{}: {e}", path.display())))?;
221        Self::from_json(&text)
222    }
223}
224
225#[cfg(test)]
226mod tests {
227    use super::*;
228    use litz_diagram::PartInstance;
229
230    #[test]
231    fn a_project_round_trips_with_its_files_and_circuit() {
232        let mut project = Project::new("blink");
233        project
234            .circuit
235            .parts
236            .push(PartInstance::new("led1", "litz-led"));
237        project.add_file("main.c", "int main(void) { return 0; }");
238        project.options.runtime = Some("firmware".into());
239        let text = project.to_json().unwrap();
240        let again = Project::from_json(&text).unwrap();
241        assert_eq!(again.name, "blink");
242        assert_eq!(again.files.len(), 1);
243        assert_eq!(again.circuit.parts.len(), 1);
244        assert_eq!(again.options.runtime.as_deref(), Some("firmware"));
245        assert_eq!(again.format, FORMAT);
246    }
247
248    #[test]
249    fn unknown_keys_survive_a_save() {
250        let text = r#"{"format":"litz-project","version":1,"name":"x","thumbnail":"a.png"}"#;
251        let project = Project::from_json(text).unwrap();
252        let written = project.to_json().unwrap();
253        assert!(written.contains("thumbnail"));
254    }
255
256    #[test]
257    fn a_path_in_a_file_name_is_refused() {
258        let mut project = Project::new("x");
259        project.add_file("../outside.c", "");
260        assert!(matches!(
261            project.validate(),
262            Err(ProjectError::UnsafeFileName(_))
263        ));
264    }
265
266    #[test]
267    fn two_files_cannot_share_a_name() {
268        let mut project = Project::new("x");
269        project.files.push(SourceFile::new("main.c", "a"));
270        project.files.push(SourceFile::new("main.c", "b"));
271        assert!(matches!(
272            project.validate(),
273            Err(ProjectError::DuplicateFileName(_))
274        ));
275    }
276
277    #[test]
278    fn a_foreign_document_is_refused() {
279        let text = r#"{"format":"other","version":1}"#;
280        assert!(matches!(
281            Project::from_json(text),
282            Err(ProjectError::WrongFormat(_))
283        ));
284    }
285
286    #[test]
287    fn a_newer_version_is_refused_rather_than_guessed() {
288        let text = format!(r#"{{"format":"litz-project","version":{}}}"#, VERSION + 1);
289        assert!(matches!(
290            Project::from_json(&text),
291            Err(ProjectError::NewerVersion(_))
292        ));
293    }
294
295    #[test]
296    fn file_groups_are_separate() {
297        let mut project = Project::new("multi");
298        project
299            .files
300            .push(SourceFile::new("a.c", "").in_group("left"));
301        project
302            .files
303            .push(SourceFile::new("b.c", "").in_group("right"));
304        assert_eq!(project.group(Some("left")).count(), 1);
305        assert_eq!(project.group(None).count(), 0);
306    }
307}