pub mod ipynb;
pub mod percent;
use crate::{Notebook, ParseError, SerializeError};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NotebookFormat {
Ipynb,
Percent,
}
impl NotebookFormat {
pub fn from_extension(ext: &str) -> Option<Self> {
match ext.to_lowercase().as_str() {
"ipynb" => Some(NotebookFormat::Ipynb),
"pct.py" => Some(NotebookFormat::Percent),
_ => None,
}
}
pub fn from_path(path: &std::path::Path) -> Option<Self> {
let file_name = path.file_name()?.to_str()?;
if file_name.ends_with(".pct.py") {
return Some(NotebookFormat::Percent);
}
let ext = path.extension()?.to_str()?;
Self::from_extension(ext)
}
pub fn extension(&self) -> &'static str {
match self {
NotebookFormat::Ipynb => "ipynb",
NotebookFormat::Percent => "pct.py",
}
}
pub fn parse(&self, input: &str) -> Result<Notebook, ParseError> {
match self {
NotebookFormat::Ipynb => ipynb::parse(input),
NotebookFormat::Percent => percent::parse(input),
}
}
pub fn serialize(&self, notebook: &Notebook) -> Result<String, SerializeError> {
match self {
NotebookFormat::Ipynb => ipynb::serialize(notebook),
NotebookFormat::Percent => percent::serialize(notebook),
}
}
pub fn serialize_with_header(
&self,
notebook: &Notebook,
include_header: bool,
) -> Result<String, SerializeError> {
match self {
NotebookFormat::Ipynb => ipynb::serialize(notebook),
NotebookFormat::Percent => {
let options = percent::PercentOptions {
header_style: if include_header {
percent::HeaderStyle::Full
} else {
percent::HeaderStyle::None
},
};
percent::serialize_with_options(notebook, &options)
}
}
}
}
impl std::fmt::Display for NotebookFormat {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
NotebookFormat::Ipynb => write!(f, "ipynb"),
NotebookFormat::Percent => write!(f, "percent"),
}
}
}