1#![forbid(unsafe_code)]
26
27use litz_diagram::Circuit;
28use serde::{Deserialize, Serialize};
29use std::collections::{BTreeMap, BTreeSet};
30use std::path::Path;
31
32pub const FORMAT: &str = "litz-project";
34pub 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
58pub struct SourceFile {
59 pub name: String,
60 #[serde(default)]
61 pub content: String,
62 #[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#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
87pub struct Options {
88 #[serde(default, skip_serializing_if = "Option::is_none")]
90 pub runtime: Option<String>,
91 #[serde(default, skip_serializing_if = "Option::is_none")]
93 pub firmware: Option<String>,
94 #[serde(default)]
96 pub strict: bool,
97}
98
99#[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 #[serde(flatten)]
116 pub extra: BTreeMap<String, serde_json::Value>,
117}
118
119#[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 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 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 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 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}