Skip to main content

parse_notebook

Function parse_notebook 

Source
pub fn parse_notebook(json: &str) -> Result<Notebook, NotebookError>
Examples found in repository?
examples/upgrade_notebook.rs (line 23)
5fn main() {
6    let args: Vec<String> = env::args().collect();
7
8    if args.len() < 2 {
9        eprintln!("Usage: {} <notebook.ipynb>", args[0]);
10        eprintln!("Parses and upgrades a notebook to v4.5 format");
11        std::process::exit(1);
12    }
13
14    let path = Path::new(&args[1]);
15
16    if !path.exists() {
17        eprintln!("Error: File not found: {:?}", path);
18        std::process::exit(1);
19    }
20
21    let notebook_json = fs::read_to_string(path).expect("Failed to read notebook file");
22
23    match nbformat::parse_notebook(&notebook_json) {
24        Ok(nbformat::Notebook::V3(v3_notebook)) => {
25            match nbformat::upgrade_v3_notebook(v3_notebook) {
26                Ok(v4_notebook) => {
27                    let output = nbformat::serialize_notebook(&nbformat::Notebook::V4(v4_notebook))
28                        .expect("Failed to serialize upgraded notebook");
29
30                    println!("{}", output);
31                }
32                Err(e) => {
33                    eprintln!("Error upgrading notebook: {}", e);
34                    std::process::exit(1);
35                }
36            }
37        }
38        Ok(nbformat::Notebook::V4(v4_notebook)) => {
39            let output = nbformat::serialize_notebook(&nbformat::Notebook::V4(v4_notebook))
40                .expect("Failed to serialize notebook");
41            println!("{}", output);
42        }
43        Ok(nbformat::Notebook::Legacy(legacy_notebook)) => {
44            match nbformat::upgrade_legacy_notebook(legacy_notebook) {
45                Ok(v4_notebook) => {
46                    let output = nbformat::serialize_notebook(&nbformat::Notebook::V4(v4_notebook))
47                        .expect("Failed to serialize upgraded notebook");
48
49                    println!("{}", output);
50                }
51                Err(e) => {
52                    eprintln!("Error upgrading notebook: {}", e);
53                    std::process::exit(1);
54                }
55            }
56        }
57        Ok(_) => {
58            eprintln!("Error: unsupported notebook variant");
59            std::process::exit(1);
60        }
61        Err(e) => {
62            eprintln!("Error parsing notebook: {}", e);
63            std::process::exit(1);
64        }
65    }
66}