#[cfg(feature = "threads")]
use std::path::Path;
use serde::{Deserialize, Serialize};
use crate::storage::StorageError;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
#[non_exhaustive]
pub enum NotebookCell {
Text {
source: String,
},
Query {
dataset: String,
query: String,
},
Plot {
spec: serde_json::Value,
},
Code {
language: String,
source: String,
},
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Notebook {
pub version: u32,
pub title: String,
#[serde(default)]
pub cells: Vec<NotebookCell>,
}
impl Notebook {
pub const VERSION: u32 = 1;
pub fn new(title: impl Into<String>) -> Self {
Self {
version: Self::VERSION,
title: title.into(),
cells: Vec::new(),
}
}
pub fn push(&mut self, cell: NotebookCell) {
self.cells.push(cell);
}
#[cfg(feature = "threads")]
pub fn save(&self, path: impl AsRef<Path>) -> Result<(), NotebookError> {
let text = serde_json::to_vec_pretty(self).map_err(NotebookError::Json)?;
crate::storage::atomic_write(path.as_ref(), &text).map_err(NotebookError::Storage)
}
#[cfg(feature = "threads")]
pub fn load(path: impl AsRef<Path>) -> Result<Self, NotebookError> {
let text = crate::storage::read_to_string(path).map_err(NotebookError::Storage)?;
let notebook: Self = serde_json::from_str(&text).map_err(NotebookError::Json)?;
if notebook.version > Self::VERSION {
return Err(NotebookError::Version(notebook.version));
}
Ok(notebook)
}
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum NotebookError {
#[error("notebook JSON: {0}")]
Json(serde_json::Error),
#[error("{0}")]
Storage(StorageError),
#[error("notebook version {0} is newer than 1")]
Version(u32),
}
#[cfg(all(test, feature = "threads", not(target_family = "wasm")))]
mod tests {
use super::*;
#[test]
fn a_notebook_round_trips_every_cell() {
let mut notebook = Notebook::new("study");
notebook.push(NotebookCell::Text {
source: "# Title".to_owned(),
});
notebook.push(NotebookCell::Query {
dataset: "signal".to_owned(),
query: "v > 0".to_owned(),
});
notebook.push(NotebookCell::Plot {
spec: serde_json::json!({"series": []}),
});
notebook.push(NotebookCell::Code {
language: "python".to_owned(),
source: "print(1)".to_owned(),
});
let directory = std::env::temp_dir().join(format!("crisol-notebook-{}", std::process::id()));
std::fs::create_dir_all(&directory).expect("directory");
let path = directory.join("study.ipynb.crisol");
notebook.save(&path).expect("save");
assert_eq!(Notebook::load(&path).expect("load"), notebook);
let _ = std::fs::remove_dir_all(directory);
}
}