[red-knot] Add notebook support (#12338)

This commit is contained in:
Micha Reiser 2024-07-17 10:26:33 +02:00 committed by GitHub
parent fe04f2b09d
commit 0c72577b5d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
12 changed files with 246 additions and 53 deletions

View file

@ -19,7 +19,7 @@ use ruff_text_size::TextSize;
use crate::cell::CellOffsets;
use crate::index::NotebookIndex;
use crate::schema::{Cell, RawNotebook, SortAlphabetically, SourceValue};
use crate::RawNotebookMetadata;
use crate::{schema, RawNotebookMetadata};
/// Run round-trip source code generation on a given Jupyter notebook file path.
pub fn round_trip(path: &Path) -> anyhow::Result<String> {
@ -52,7 +52,7 @@ pub enum NotebookError {
InvalidFormat(i64),
}
#[derive(Clone, Debug, PartialEq)]
#[derive(Clone, Debug)]
pub struct Notebook {
/// Python source code of the notebook.
///
@ -205,6 +205,28 @@ impl Notebook {
})
}
/// Creates an empty notebook.
///
///
pub fn empty() -> Self {
Self::from_raw_notebook(
RawNotebook {
cells: vec![schema::Cell::Code(schema::CodeCell {
execution_count: None,
id: None,
metadata: serde_json::Value::default(),
outputs: vec![],
source: schema::SourceValue::String(String::default()),
})],
metadata: RawNotebookMetadata::default(),
nbformat: 4,
nbformat_minor: 5,
},
false,
)
.unwrap()
}
/// Update the cell offsets as per the given [`SourceMap`].
fn update_cell_offsets(&mut self, source_map: &SourceMap) {
// When there are multiple cells without any edits, the offsets of those
@ -412,6 +434,14 @@ impl Notebook {
}
}
impl PartialEq for Notebook {
fn eq(&self, other: &Self) -> bool {
self.trailing_newline == other.trailing_newline && self.raw == other.raw
}
}
impl Eq for Notebook {}
#[cfg(test)]
mod tests {
use std::path::Path;
@ -458,6 +488,13 @@ mod tests {
));
}
#[test]
fn empty_notebook() {
let notebook = Notebook::empty();
assert_eq!(notebook.source_code(), "\n");
}
#[test_case("markdown", false)]
#[test_case("only_magic", true)]
#[test_case("code_and_magic", true)]