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;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DocumentFormat {
Native,
Fcstd,
}
impl DocumentFormat {
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),
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(),
}),
}
}
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())
}
}
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))
}
pub fn write(
doc: &SavedDocument,
path: &str,
format: DocumentFormat,
) -> Result<(), FormatError> {
write_with_report(doc, path, format).map(|_| ())
}
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,
})
}
}
}
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,
});
}
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)
}
#[derive(Debug)]
pub enum FormatError {
UnknownExtension { path: String },
NotNative { path: String, format: String },
NewerVersion { path: String, version: u32 },
NeitherZipNorNative { path: String },
Io { path: String, source: io::Error },
Json {
path: String,
source: serde_json::Error,
},
Encode(serde_json::Error),
Fcstd { path: String, source: FcstdError },
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();
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);
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();
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}");
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());
}
}