#[cfg(feature = "threads")]
use std::path::Path;
use serde::{Deserialize, Serialize};
use super::session::Workspace;
use crate::storage::StorageError;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ProjectDataset {
pub name: String,
pub source: String,
pub format: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ProjectView {
pub name: String,
pub kind: String,
#[serde(default)]
pub payload: serde_json::Value,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ProjectScript {
pub name: String,
pub source: Option<String>,
pub path: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Project {
pub version: u32,
pub name: String,
#[serde(default)]
pub datasets: Vec<ProjectDataset>,
#[serde(default)]
pub views: Vec<ProjectView>,
#[serde(default)]
pub scripts: Vec<ProjectScript>,
#[serde(default)]
pub settings: std::collections::BTreeMap<String, String>,
#[serde(default)]
pub workspace: Option<Workspace>,
}
impl Default for Project {
fn default() -> Self {
Self::new("Untitled")
}
}
impl Project {
pub const VERSION: u32 = 1;
pub fn new(name: impl Into<String>) -> Self {
Self {
version: Self::VERSION,
name: name.into(),
datasets: Vec::new(),
views: Vec::new(),
scripts: Vec::new(),
settings: std::collections::BTreeMap::new(),
workspace: None,
}
}
pub fn dataset(&mut self, name: impl Into<String>, source: impl Into<String>, format: impl Into<String>) {
self.datasets.push(ProjectDataset {
name: name.into(),
source: source.into(),
format: format.into(),
});
}
pub fn view(&mut self, name: impl Into<String>, kind: impl Into<String>, payload: serde_json::Value) {
self.views.push(ProjectView {
name: name.into(),
kind: kind.into(),
payload,
});
}
pub fn script(&mut self, name: impl Into<String>, source: impl Into<String>) {
self.scripts.push(ProjectScript {
name: name.into(),
source: Some(source.into()),
path: None,
});
}
#[cfg(feature = "threads")]
pub fn save(&self, path: impl AsRef<Path>) -> Result<(), ProjectError> {
let text = serde_json::to_vec_pretty(self).map_err(ProjectError::Json)?;
crate::storage::atomic_write(path.as_ref(), &text).map_err(ProjectError::Storage)
}
#[cfg(feature = "threads")]
pub fn load(path: impl AsRef<Path>) -> Result<Self, ProjectError> {
let text = crate::storage::read_to_string(path).map_err(ProjectError::Storage)?;
let project: Self = serde_json::from_str(&text).map_err(ProjectError::Json)?;
if project.version > Self::VERSION {
return Err(ProjectError::Version(project.version));
}
Ok(project)
}
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ProjectError {
#[error("project JSON: {0}")]
Json(serde_json::Error),
#[error("{0}")]
Storage(StorageError),
#[error("project version {0} is newer than 1")]
Version(u32),
}
#[cfg(all(test, feature = "threads", not(target_family = "wasm")))]
mod tests {
use super::*;
#[test]
fn a_project_round_trips() {
let mut project = Project::new("study");
project.dataset("signal", "data.csv", "csv");
project.view("plot", "plot", serde_json::json!({"title": "signal"}));
project.script("load", "print('hello')");
project.workspace = Some(Workspace::default());
let directory = std::env::temp_dir().join(format!("crisol-project-{}", std::process::id()));
std::fs::create_dir_all(&directory).expect("directory");
let path = directory.join("study.crisol");
project.save(&path).expect("save");
let restored = Project::load(&path).expect("load");
assert_eq!(restored, project);
let _ = std::fs::remove_dir_all(directory);
}
#[test]
fn a_newer_version_is_rejected() {
let directory = std::env::temp_dir().join(format!("crisol-project-new-{}", std::process::id()));
std::fs::create_dir_all(&directory).expect("directory");
let path = directory.join("newer.crisol");
std::fs::write(&path, r#"{"version":9,"name":"x"}"#).expect("write");
assert!(matches!(Project::load(&path), Err(ProjectError::Version(9))));
let _ = std::fs::remove_dir_all(directory);
}
}