converter.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. """API for converting notebooks between versions."""
  2. # Copyright (c) IPython Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. from . import versions
  5. from .reader import get_version
  6. def convert(nb, to_version):
  7. """Convert a notebook node object to a specific version. Assumes that
  8. all the versions starting from 1 to the latest major X are implemented.
  9. In other words, there should never be a case where v1 v2 v3 v5 exist without
  10. a v4. Also assumes that all conversions can be made in one step increments
  11. between major versions and ignores minor revisions.
  12. Parameters
  13. ----------
  14. nb : NotebookNode
  15. to_version : int
  16. Major revision to convert the notebook to. Can either be an upgrade or
  17. a downgrade.
  18. """
  19. # Get input notebook version.
  20. (version, version_minor) = get_version(nb)
  21. # Check if destination is target version, if so return contents
  22. if version == to_version:
  23. return nb
  24. # If the version exist, try to convert to it one step at a time.
  25. elif to_version in versions:
  26. # Get the the version that this recursion will convert to as a step
  27. # closer to the final revision. Make sure the newer of the conversion
  28. # functions is used to perform the conversion.
  29. if to_version > version:
  30. step_version = version + 1
  31. convert_function = versions[step_version].upgrade
  32. else:
  33. step_version = version - 1
  34. convert_function = versions[version].downgrade
  35. # Convert and make sure version changed during conversion.
  36. converted = convert_function(nb)
  37. if converted.get('nbformat', 1) == version:
  38. raise ValueError("Failed to convert notebook from v%d to v%d." % (version, step_version))
  39. # Recursively convert until target version is reached.
  40. return convert(converted, to_version)
  41. else:
  42. raise ValueError("Cannot convert notebook to v%d because that " \
  43. "version doesn't exist" % (to_version))