1"""Code for converting notebooks to and from the v2 format.
2
3Authors:
4
5* Brian Granger
6* Jonathan Frederic
7"""
8
9# -----------------------------------------------------------------------------
10# Copyright (C) 2008-2011 The IPython Development Team
11#
12# Distributed under the terms of the BSD License. The full license is in
13# the file LICENSE, distributed as part of this software.
14# -----------------------------------------------------------------------------
15
16# -----------------------------------------------------------------------------
17# Imports
18# -----------------------------------------------------------------------------
19from __future__ import annotations
20
21from .nbbase import new_code_cell, new_notebook, new_text_cell, new_worksheet
22
23# -----------------------------------------------------------------------------
24# Code
25# -----------------------------------------------------------------------------
26
27
28def upgrade(nb, from_version=1):
29 """Convert a notebook to the v2 format.
30
31 Parameters
32 ----------
33 nb : NotebookNode
34 The Python representation of the notebook to convert.
35 from_version : int
36 The version of the notebook to convert from.
37 """
38 if from_version == 1:
39 newnb = new_notebook()
40 ws = new_worksheet()
41 for cell in nb.cells:
42 if cell.cell_type == "code":
43 newcell = new_code_cell(
44 input=cell.get("code"), prompt_number=cell.get("prompt_number")
45 )
46 elif cell.cell_type == "text":
47 newcell = new_text_cell("markdown", source=cell.get("text"))
48 ws.cells.append(newcell)
49 newnb.worksheets.append(ws)
50 return newnb
51
52 raise ValueError("Cannot convert a notebook from v%s to v2" % from_version)
53
54
55def downgrade(nb):
56 """Convert a v2 notebook to v1.
57
58 Parameters
59 ----------
60 nb : NotebookNode
61 The Python representation of the notebook to convert.
62 """
63 msg = "Downgrade from notebook v2 to v1 is not supported."
64 raise Exception(msg)