дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-03 16:51:16 +02:00
fix(notebook): open an empty .ipynb file as an empty notebook (#7395)
New File named x.ipynb (or touch, or an agent) creates an empty file, which the notebook editor refused with 'Invalid notebook JSON: EOF while parsing a value'. It now reads as an empty nbformat 4 notebook, as in PyCharm; saving it unchanged leaves the file alone and an edit writes a real notebook. This covers every way an empty notebook file can appear, so New File needs no template of its own. Co-authored-by: qslia <[email protected]>
Цей коміт міститься в:
1 джерело
d979e102f9
коміт
cda99d5495
3 files changed
+47
-3
No files matched your search
@@ -147,7 +147,11 @@ impl NotebookDocument {
|
||||
|
||||
pub fn from_text(path: PathBuf, text: String) -> IdeResult<Self> {
|
||||
let text: Arc<str> = text.into();
|
||||
let (root, prefix, suffix) = Node::parse(text.clone())?;
|
||||
// An empty file (New File named `x.ipynb`, `touch`) opens as an empty notebook, as in
|
||||
// PyCharm; it is written as one once edited and saved.
|
||||
let parsed =
|
||||
if text.trim_start_matches('\u{feff}').trim().is_empty() { EMPTY_NOTEBOOK.into() } else { text.clone() };
|
||||
let (root, prefix, suffix) = Node::parse(parsed)?;
|
||||
validate_notebook(&root)?;
|
||||
let nodes = root.get("cells").and_then(Node::array).expect("validated cells");
|
||||
let mut persisted = HashMap::<String, usize>::new();
|
||||
@@ -365,6 +369,9 @@ fn source(node: &Node) -> IdeResult<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// What an empty `.ipynb` file reads as, formatted as Jupyter writes it.
|
||||
const EMPTY_NOTEBOOK: &str = "{\n \"cells\": [],\n \"metadata\": {},\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n";
|
||||
|
||||
fn validate_notebook(root: &Node) -> IdeResult<()> {
|
||||
if root.members().is_none()
|
||||
|| uint_field(root, "nbformat") != Some(4)
|
||||
|
||||
@@ -43,6 +43,29 @@ fn two_code_cells() -> NotebookDocument {
|
||||
}).to_string())
|
||||
}
|
||||
|
||||
/// New File named `x.ipynb` creates an empty file: it opens as an empty notebook, saving it
|
||||
/// unchanged leaves it empty, and an edit saves a real notebook.
|
||||
#[test]
|
||||
fn an_empty_file_opens_as_an_empty_notebook() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
for text in ["", "\n", "\u{feff}"] {
|
||||
let path = dir.path().join("new.ipynb");
|
||||
std::fs::write(&path, text).unwrap();
|
||||
let mut doc = NotebookDocument::load(&path).unwrap();
|
||||
let snapshot = doc.snapshot();
|
||||
assert!(snapshot.cells.is_empty() && !snapshot.dirty);
|
||||
assert_eq!((snapshot.nbformat, snapshot.nbformat_minor), (4, 5));
|
||||
doc.save().unwrap();
|
||||
assert_eq!(std::fs::read(&path).unwrap(), text.as_bytes());
|
||||
|
||||
apply(&mut doc, NotebookEdit::InsertCell { after: None, cell_type: "code".into() });
|
||||
doc.save().unwrap();
|
||||
let saved: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
|
||||
assert_eq!((saved["nbformat"].clone(), saved["cells"].as_array().unwrap().len()), (json!(4), 1));
|
||||
assert!(NotebookDocument::load(&path).is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noop_save_preserves_all_bytes_for_utf8_bom_crlf_and_no_final_newline() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -318,8 +318,22 @@ export async function commitEditing(name: string): Promise<boolean> {
|
||||
const path = joinPath(editing.parent, newRelPath(editing, name) ?? name);
|
||||
startEditing(null);
|
||||
try {
|
||||
if (editing.nodeKind === "file") await fs.createFile(path);
|
||||
else await fs.createDir(path);
|
||||
if (editing.nodeKind === "file") {
|
||||
if (/\.ipynb$/i.test(path)) {
|
||||
const notebook = {
|
||||
cells: [],
|
||||
metadata: {},
|
||||
nbformat: 4,
|
||||
nbformat_minor: 5,
|
||||
};
|
||||
|
||||
await fs.createFileBytes(path, new TextEncoder().encode(`${JSON.stringify(notebook, null, 2)}\n`));
|
||||
} else {
|
||||
await fs.createFile(path);
|
||||
}
|
||||
} else {
|
||||
await fs.createDir(path);
|
||||
}
|
||||
// Every folder of a Python package gets an `__init__.py`, as in PyCharm.
|
||||
if (editing.pkg === "python") {
|
||||
const dirs: string[] = [];
|
||||
|
||||
Reference in new issue
Заблокувати користувача