ferrocad_core 0.1.4

FerroCAD core: quantities, properties, documents, recompute DAG
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
//! Document format selection and the read/write dispatch.
//!
//! FerroCAD keeps **two explicit serializers** and never sniffs a file's content
//! to choose between them:
//!
//! | Suffix | [`DocumentFormat`] | Backend |
//! | --- | --- | --- |
//! | `.ferrocad` (any case) | [`DocumentFormat::Native`] | [`native`] — JSON envelope |
//! | `.fe2o3` / `.fe203` (any case) | [`DocumentFormat::Native`] | [`native`] — accepted aliases |
//! | `.FCStd` (any case) | [`DocumentFormat::Fcstd`] | [`fcstd_write`] / [`fcstd`] — ZIP + `Document.xml` |
//!
//! A path with no suffix, or with any other suffix, is an error naming both valid
//! suffixes: there is no silent default.
//!
//! The suffix and the bytes always agree: a `.FCStd` write is a real ZIP archive
//! ([`fcstd_write::write_fcstd`]) and a `.ferrocad` write is the native JSON
//! envelope ([`native::write`]). Neither backend is tried as a fallback for a
//! write.
//!
//! # Reading an `.FCStd` path
//!
//! [`read`] with [`DocumentFormat::Fcstd`] checks the first four bytes. A ZIP
//! local-file header goes to [`fcstd::read_fcstd`]; anything else is accepted
//! only when it carries the native envelope marker (`"format": "ferrocad"`)
//! and is otherwise reported as "not a ZIP archive", never as a JSON parse
//! error. The native fallback exists only for files written before the switch
//! (FerroCAD used to emit JSON under an `.FCStd` name); it is read-only.
//!
//! `.ferrocad` never falls back to the FCStd reader, and an unknown suffix is
//! never guessed.

use std::fmt;
use std::io;

use serde_json::Value;

use super::fcstd::{self, FcstdError};
use super::fcstd_write::{self, FcstdWriteError};
use super::native::{self, NATIVE_FORMAT};
use super::SavedDocument;

/// The serializers a document path can select.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DocumentFormat {
    /// FerroCAD's own JSON format (`.ferrocad`).
    Native,
    /// Upstream FreeCAD's ZIP container (`.FCStd`).
    Fcstd,
}

impl DocumentFormat {
    /// Select the format from `path`'s suffix, case-insensitively.
    ///
    /// A missing or unrecognised suffix is [`FormatError::UnknownExtension`];
    /// nothing is defaulted.
    pub fn from_path(path: &str) -> Result<Self, FormatError> {
        let suffix = std::path::Path::new(path)
            .extension()
            .and_then(|s| s.to_str());
        match suffix {
            Some(s) if s.eq_ignore_ascii_case("ferrocad") => Ok(DocumentFormat::Native),
            // The iron-oxide spelling is the alternative the owner considered; both
            // are the same native serializer. `.ferrocad` stays canonical.
            Some(s) if s.eq_ignore_ascii_case("fe2o3") || s.eq_ignore_ascii_case("fe203") => {
                Ok(DocumentFormat::Native)
            }
            Some(s) if s.eq_ignore_ascii_case("fcstd") => Ok(DocumentFormat::Fcstd),
            _ => Err(FormatError::UnknownExtension {
                path: path.to_owned(),
            }),
        }
    }

    /// The canonical suffix, without the dot.
    pub fn extension(self) -> &'static str {
        match self {
            DocumentFormat::Native => "ferrocad",
            DocumentFormat::Fcstd => "FCStd",
        }
    }
}

impl fmt::Display for DocumentFormat {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.extension())
    }
}

/// Read `path` with the serializer its suffix selects.
///
/// The returned format is the one that was used, so a caller can record it and
/// reuse it on a later save.
pub fn read(path: &str) -> Result<(SavedDocument, DocumentFormat), FormatError> {
    let format = DocumentFormat::from_path(path)?;
    let saved = match format {
        DocumentFormat::Native => native::read(path)?,
        DocumentFormat::Fcstd => read_fcstd_backend(path)?,
    };
    Ok((saved, format))
}

/// Write `doc` to `path` with the serializer `format` selects.
///
/// The `.FCStd` arm builds a real ZIP archive through
/// [`fcstd_write::write_fcstd`]; a property whose type the writer cannot
/// represent is an error naming the object and property rather than a silently
/// lossy save. Use [`write_with_report`] to learn what was skipped (currently
/// only an object's `python_state`).
pub fn write(
    doc: &SavedDocument,
    path: &str,
    format: DocumentFormat,
) -> Result<(), FormatError> {
    write_with_report(doc, path, format).map(|_| ())
}

/// Like [`write`], but returns what the chosen backend could not represent.
///
/// The native serializer is lossless, so its report is always empty.
pub fn write_with_report(
    doc: &SavedDocument,
    path: &str,
    format: DocumentFormat,
) -> Result<fcstd_write::WriteReport, FormatError> {
    match format {
        DocumentFormat::Native => native::write(doc, path).map(|()| Default::default()),
        DocumentFormat::Fcstd => {
            fcstd_write::write_fcstd_with_report(doc, path).map_err(|e| FormatError::FcstdWrite {
                path: path.to_owned(),
                source: e,
            })
        }
    }
}

/// The `.FCStd` read arm: ZIP first, then the marker-gated native fallback.
fn read_fcstd_backend(path: &str) -> Result<SavedDocument, FormatError> {
    let data = std::fs::read(path).map_err(|e| FormatError::io(path, e))?;
    if data.starts_with(b"PK\x03\x04") {
        return fcstd::read_fcstd(path).map_err(|e| FormatError::Fcstd {
            path: path.to_owned(),
            source: e,
        });
    }
    // Transitional, read-only: FerroCAD used to write native JSON under an
    // `.FCStd` name. Accept it only when the envelope carries the marker, so a
    // truncated or renamed ZIP is reported below instead of as a JSON error.
    let probe: Value = serde_json::from_slice(&data)
        .map_err(|_| FormatError::NeitherZipNorNative { path: path.to_owned() })?;
    if probe.get("format").and_then(Value::as_str) != Some(NATIVE_FORMAT) {
        return Err(FormatError::NeitherZipNorNative {
            path: path.to_owned(),
        });
    }
    native::decode(path, &data)
}

/// Errors from format selection, encoding, and both read/write backends.
#[derive(Debug)]
pub enum FormatError {
    /// The path has no suffix, or a suffix neither serializer recognises.
    UnknownExtension { path: String },
    /// A native envelope names a format other than `ferrocad`.
    NotNative { path: String, format: String },
    /// A native envelope was written by a newer FerroCAD.
    NewerVersion { path: String, version: u32 },
    /// An `.FCStd` path holds neither a ZIP archive nor a native envelope.
    NeitherZipNorNative { path: String },
    /// The file could not be read or written.
    Io { path: String, source: io::Error },
    /// Native JSON could not be parsed.
    Json {
        path: String,
        source: serde_json::Error,
    },
    /// Native JSON could not be produced.
    Encode(serde_json::Error),
    /// The `.FCStd` backend failed.
    Fcstd { path: String, source: FcstdError },
    /// The `.FCStd` writer refused to save a value it cannot represent.
    FcstdWrite { path: String, source: FcstdWriteError },
}

impl FormatError {
    pub(crate) fn io(path: &str, source: io::Error) -> Self {
        FormatError::Io {
            path: path.to_owned(),
            source,
        }
    }

    pub(crate) fn json(path: &str, source: serde_json::Error) -> Self {
        FormatError::Json {
            path: path.to_owned(),
            source,
        }
    }
}

impl fmt::Display for FormatError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            FormatError::UnknownExtension { path } => write!(
                f,
                "unknown document extension for '{path}': expected '.ferrocad' \
                 (or '.fe2o3') or '.FCStd'"
            ),
            FormatError::NotNative { path, format } => write!(
                f,
                "'{path}' is not a FerroCAD document: envelope format '{format}' \
                 (expected '{NATIVE_FORMAT}')"
            ),
            FormatError::NewerVersion { path, version } => write!(
                f,
                "'{path}' was written by a newer FerroCAD (format version {version}; \
                 this build reads up to version {})",
                native::NATIVE_VERSION
            ),
            FormatError::NeitherZipNorNative { path } => write!(
                f,
                "'{path}' is not a ZIP archive and carries no FerroCAD native envelope"
            ),
            FormatError::Io { path, source } => write!(f, "cannot access '{path}': {source}"),
            FormatError::Json { path, source } => {
                write!(f, "malformed FerroCAD document '{path}': {source}")
            }
            FormatError::Encode(source) => {
                write!(f, "cannot encode the document as FerroCAD JSON: {source}")
            }
            FormatError::Fcstd { path, source } => write!(f, "cannot read '{path}': {source}"),
            FormatError::FcstdWrite { path, source } => {
                write!(f, "cannot write '{path}': {source}")
            }
        }
    }
}

impl std::error::Error for FormatError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            FormatError::Io { source, .. } => Some(source),
            FormatError::Json { source, .. } | FormatError::Encode(source) => Some(source),
            FormatError::Fcstd { source, .. } => Some(source),
            FormatError::FcstdWrite { source, .. } => Some(source),
            _ => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Document, Property};

    fn temp_path(name: &str) -> String {
        std::env::temp_dir()
            .join(format!("ferrocad-format-{}-{name}", std::process::id()))
            .to_string_lossy()
            .into_owned()
    }

    fn sample_document() -> SavedDocument {
        let mut doc = Document::new();
        let id = doc.add_object("Box", "App::FeaturePython");
        assert!(doc.set_label(id, "a box"));
        doc.to_saved("Sample")
    }

    #[test]
    fn from_path_selects_by_suffix_case_insensitively() {
        let cases = [
            ("model.ferrocad", Ok(DocumentFormat::Native)),
            ("model.FERROCAD", Ok(DocumentFormat::Native)),
            ("model.Ferrocad", Ok(DocumentFormat::Native)),
            ("model.fe2o3", Ok(DocumentFormat::Native)),
            ("model.Fe2O3", Ok(DocumentFormat::Native)),
            ("model.fe203", Ok(DocumentFormat::Native)),
            ("model.FCStd", Ok(DocumentFormat::Fcstd)),
            ("model.fcstd", Ok(DocumentFormat::Fcstd)),
            ("model.FCStd.bak", Err(())),
            ("model.FcStD", Ok(DocumentFormat::Fcstd)),
            ("/tmp/dir.with.dots/model.ferrocad", Ok(DocumentFormat::Native)),
            ("model", Err(())),
            ("model.json", Err(())),
            ("model.ferrocad.json", Err(())),
            (".ferrocad", Err(())),
            ("model.", Err(())),
        ];
        for (path, expected) in cases {
            match (DocumentFormat::from_path(path), expected) {
                (Ok(actual), Ok(want)) => assert_eq!(actual, want, "{path}"),
                (Err(err), Err(())) => {
                    let message = err.to_string();
                    assert!(
                        message.contains(".ferrocad")
                            && message.contains(".fe2o3")
                            && message.contains(".FCStd"),
                        "{path}: {message}"
                    );
                }
                (actual, want) => panic!("{path}: got {actual:?}, wanted {want:?}"),
            }
        }
    }

    #[test]
    fn extension_is_canonical() {
        assert_eq!(DocumentFormat::Native.extension(), "ferrocad");
        assert_eq!(DocumentFormat::Fcstd.extension(), "FCStd");
    }

    #[test]
    fn native_round_trip_carries_the_envelope() {
        let path = temp_path("native.ferrocad");
        let doc = sample_document();
        write(&doc, &path, DocumentFormat::Native).unwrap();

        let bytes = std::fs::read(&path).unwrap();
        assert_eq!(bytes[0], b'{');
        let json: Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(json["format"], "ferrocad");
        assert_eq!(json["version"], 1);
        assert_eq!(json["name"], "Sample");

        let (read_back, format) = read(&path).unwrap();
        assert_eq!(format, DocumentFormat::Native);
        assert_eq!(read_back.format, "ferrocad");
        assert_eq!(read_back.version, 1);
        assert_eq!(read_back.name, "Sample");
        assert_eq!(read_back.objects.len(), 1);
        assert_eq!(read_back.objects[0].name, "Box");
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn fe2o3_round_trips_as_native_json() {
        let path = temp_path("model.fe2o3");
        let doc = sample_document();
        write(&doc, &path, DocumentFormat::Native).unwrap();
        let (read_back, format) = read(&path).unwrap();
        assert_eq!(format, DocumentFormat::Native);
        assert_eq!(read_back.name, "Sample");
        assert_eq!(read_back.objects[0].name, "Box");
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn bare_native_json_is_version_1() {
        let path = temp_path("bare.ferrocad");
        std::fs::write(&path, br#"{"name":"Old","objects":[]}"#).unwrap();
        let (doc, format) = read(&path).unwrap();
        assert_eq!(format, DocumentFormat::Native);
        assert_eq!(doc.format, "ferrocad");
        assert_eq!(doc.version, 1);
        assert_eq!(doc.name, "Old");
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn unknown_native_format_and_future_version_are_rejected() {
        let path = temp_path("wrong-format.ferrocad");
        std::fs::write(
            &path,
            br#"{"format":"something-else","version":1,"name":"X","objects":[]}"#,
        )
        .unwrap();
        let err = read(&path).unwrap_err().to_string();
        assert!(err.contains("something-else"), "{err}");
        assert!(err.contains(&path), "{err}");

        std::fs::write(
            &path,
            br#"{"format":"ferrocad","version":2,"name":"X","objects":[]}"#,
        )
        .unwrap();
        let err = read(&path).unwrap_err().to_string();
        assert!(err.contains("newer FerroCAD"), "{err}");
        assert!(err.contains(&path), "{err}");
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn fcstd_write_and_reopen_round_trips() {
        let path = temp_path("round-trip.FCStd");
        let doc = sample_document();
        write(&doc, &path, DocumentFormat::Fcstd).unwrap();

        // The suffix now selects the real backend: a ZIP local-file header, not
        // the native JSON envelope.
        let bytes = std::fs::read(&path).unwrap();
        assert_eq!(&bytes[..4], b"PK\x03\x04");
        assert!(!bytes.starts_with(b"{"));

        let (read_back, format) = read(&path).unwrap();
        assert_eq!(format, DocumentFormat::Fcstd);
        // Upstream `.FCStd` does not persist the document name: FreeCAD derives it
        // from the file stem, and so does our reader.
        let stem = std::path::Path::new(&path)
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap();
        assert_eq!(read_back.name, stem);
        assert_eq!(read_back.objects.len(), 1);
        assert_eq!(read_back.objects[0].name, "Box");
        assert_eq!(read_back.objects[0].label, "a box");
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn fcstd_archive_carries_document_and_gui_members() {
        use crate::fcstd::read_fcstd;

        let path = temp_path("members.FCStd");
        let doc = sample_document();
        let report = write_with_report(&doc, &path, DocumentFormat::Fcstd).unwrap();
        assert!(report.is_empty(), "nothing should be dropped: {report:?}");

        let bytes = std::fs::read(&path).unwrap();
        // Every member name is stored in the central directory as plain ASCII.
        for member in ["Document.xml", "GuiDocument.xml"] {
            assert!(
                bytes
                    .windows(member.len())
                    .any(|window| window == member.as_bytes()),
                "{member} is missing from the archive"
            );
        }
        let saved = read_fcstd(&path).expect("reader accepts the archive");
        assert_eq!(saved.objects[0].name, "Box");
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn fcstd_arm_errors_on_an_unrepresentable_property() {
        let path = temp_path("unsupported.FCStd");
        let mut doc = sample_document();
        doc.objects[0].properties.insert(
            "Script".to_string(),
            Property::FileIncluded("/tmp/script.py".to_string()),
        );

        let err = write(&doc, &path, DocumentFormat::Fcstd).unwrap_err();
        let message = err.to_string();
        assert!(message.contains("cannot write"), "{message}");
        assert!(message.contains("Box.Script"), "{message}");
        assert!(message.contains(&path), "{message}");
        // A refused save must not leave the native JSON in place of an archive.
        assert!(!std::path::Path::new(&path).exists());
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn native_arm_never_emits_a_zip() {
        let path = temp_path("native-not-zip.ferrocad");
        let doc = sample_document();
        write(&doc, &path, DocumentFormat::Native).unwrap();
        let bytes = std::fs::read(&path).unwrap();
        assert_eq!(bytes[0], b'{');
        assert!(!bytes.starts_with(b"PK\x03\x04"));
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn zip_named_ferrocad_is_rejected() {
        let path = temp_path("renamed.ferrocad");
        std::fs::write(&path, b"PK\x03\x04not really a document").unwrap();
        let err = read(&path).unwrap_err();
        assert!(
            matches!(err, FormatError::Json { .. }),
            "the native arm must not fall back to FCStd: {err}"
        );
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn truncated_zip_named_fcstd_reports_a_zip_error() {
        let path = temp_path("truncated.FCStd");
        std::fs::write(&path, b"PK\x03\x04 truncated archive").unwrap();
        let err = read(&path).unwrap_err();
        let message = err.to_string();
        assert!(message.contains("not a ZIP archive"), "{message}");
        assert!(!message.contains("malformed FerroCAD"), "{message}");
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn json_without_marker_named_fcstd_is_rejected() {
        let path = temp_path("plain.FCStd");
        std::fs::write(&path, br#"{"name":"X","objects":[]}"#).unwrap();
        let message = read(&path).unwrap_err().to_string();
        assert!(message.contains("not a ZIP archive"), "{message}");
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn unknown_suffix_is_rejected() {
        let path = temp_path("model.json");
        let message = DocumentFormat::from_path(&path).unwrap_err().to_string();
        assert!(message.contains(".ferrocad"), "{message}");
        assert!(message.contains(".FCStd"), "{message}");
        assert!(read(&path).is_err());
        assert!(!std::path::Path::new(&path).exists());
    }
}