PageRenderTime 64ms CodeModel.GetById 35ms RepoModel.GetById 0ms app.codeStats 0ms

/IPython/frontend/html/notebook/filenbmanager.py

https://github.com/juliantaylor/ipython
Python | 346 lines | 320 code | 8 blank | 18 comment | 1 complexity | 7ade3bac1ce005b4a89119ad2055c72c MD5 | raw file
  1. """A notebook manager that uses the local file system for storage.
  2. Authors:
  3. * Brian Granger
  4. """
  5. #-----------------------------------------------------------------------------
  6. # Copyright (C) 2011 The IPython Development Team
  7. #
  8. # Distributed under the terms of the BSD License. The full license is in
  9. # the file COPYING, distributed as part of this software.
  10. #-----------------------------------------------------------------------------
  11. #-----------------------------------------------------------------------------
  12. # Imports
  13. #-----------------------------------------------------------------------------
  14. import datetime
  15. import io
  16. import os
  17. import glob
  18. import shutil
  19. from tornado import web
  20. from .nbmanager import NotebookManager
  21. from IPython.nbformat import current
  22. from IPython.utils.traitlets import Unicode, Dict, Bool, TraitError
  23. #-----------------------------------------------------------------------------
  24. # Classes
  25. #-----------------------------------------------------------------------------
  26. class FileNotebookManager(NotebookManager):
  27. save_script = Bool(False, config=True,
  28. help="""Automatically create a Python script when saving the notebook.
  29. For easier use of import, %run and %load across notebooks, a
  30. <notebook-name>.py script will be created next to any
  31. <notebook-name>.ipynb on each save. This can also be set with the
  32. short `--script` flag.
  33. """
  34. )
  35. checkpoint_dir = Unicode(config=True,
  36. help="""The location in which to keep notebook checkpoints
  37. By default, it is notebook-dir/.ipynb_checkpoints
  38. """
  39. )
  40. def _checkpoint_dir_default(self):
  41. return os.path.join(self.notebook_dir, '.ipynb_checkpoints')
  42. def _checkpoint_dir_changed(self, name, old, new):
  43. """do a bit of validation of the checkpoint dir"""
  44. if not os.path.isabs(new):
  45. # If we receive a non-absolute path, make it absolute.
  46. abs_new = os.path.abspath(new)
  47. self.checkpoint_dir = abs_new
  48. return
  49. if os.path.exists(new) and not os.path.isdir(new):
  50. raise TraitError("checkpoint dir %r is not a directory" % new)
  51. if not os.path.exists(new):
  52. self.log.info("Creating checkpoint dir %s", new)
  53. try:
  54. os.mkdir(new)
  55. except:
  56. raise TraitError("Couldn't create checkpoint dir %r" % new)
  57. filename_ext = Unicode(u'.ipynb')
  58. # Map notebook names to notebook_ids
  59. rev_mapping = Dict()
  60. def get_notebook_names(self):
  61. """List all notebook names in the notebook dir."""
  62. names = glob.glob(os.path.join(self.notebook_dir,
  63. '*' + self.filename_ext))
  64. names = [os.path.splitext(os.path.basename(name))[0]
  65. for name in names]
  66. return names
  67. def list_notebooks(self):
  68. """List all notebooks in the notebook dir."""
  69. names = self.get_notebook_names()
  70. data = []
  71. for name in names:
  72. if name not in self.rev_mapping:
  73. notebook_id = self.new_notebook_id(name)
  74. else:
  75. notebook_id = self.rev_mapping[name]
  76. data.append(dict(notebook_id=notebook_id,name=name))
  77. data = sorted(data, key=lambda item: item['name'])
  78. return data
  79. def new_notebook_id(self, name):
  80. """Generate a new notebook_id for a name and store its mappings."""
  81. notebook_id = super(FileNotebookManager, self).new_notebook_id(name)
  82. self.rev_mapping[name] = notebook_id
  83. return notebook_id
  84. def delete_notebook_id(self, notebook_id):
  85. """Delete a notebook's id in the mapping."""
  86. name = self.mapping[notebook_id]
  87. super(FileNotebookManager, self).delete_notebook_id(notebook_id)
  88. del self.rev_mapping[name]
  89. def notebook_exists(self, notebook_id):
  90. """Does a notebook exist?"""
  91. exists = super(FileNotebookManager, self).notebook_exists(notebook_id)
  92. if not exists:
  93. return False
  94. path = self.get_path_by_name(self.mapping[notebook_id])
  95. return os.path.isfile(path)
  96. def get_name(self, notebook_id):
  97. """get a notebook name, raising 404 if not found"""
  98. try:
  99. name = self.mapping[notebook_id]
  100. except KeyError:
  101. raise web.HTTPError(404, u'Notebook does not exist: %s' % notebook_id)
  102. return name
  103. def get_path(self, notebook_id):
  104. """Return a full path to a notebook given its notebook_id."""
  105. name = self.get_name(notebook_id)
  106. return self.get_path_by_name(name)
  107. def get_path_by_name(self, name):
  108. """Return a full path to a notebook given its name."""
  109. filename = name + self.filename_ext
  110. path = os.path.join(self.notebook_dir, filename)
  111. return path
  112. def read_notebook_object_from_path(self, path):
  113. """read a notebook object from a path"""
  114. info = os.stat(path)
  115. last_modified = datetime.datetime.utcfromtimestamp(info.st_mtime)
  116. with open(path,'r') as f:
  117. s = f.read()
  118. try:
  119. # v1 and v2 and json in the .ipynb files.
  120. nb = current.reads(s, u'json')
  121. except Exception as e:
  122. raise web.HTTPError(500, u'Unreadable JSON notebook: %s' % e)
  123. return last_modified, nb
  124. def read_notebook_object(self, notebook_id):
  125. """Get the Notebook representation of a notebook by notebook_id."""
  126. path = self.get_path(notebook_id)
  127. if not os.path.isfile(path):
  128. raise web.HTTPError(404, u'Notebook does not exist: %s' % notebook_id)
  129. last_modified, nb = self.read_notebook_object_from_path(path)
  130. # Always use the filename as the notebook name.
  131. nb.metadata.name = os.path.splitext(os.path.basename(path))[0]
  132. return last_modified, nb
  133. def write_notebook_object(self, nb, notebook_id=None):
  134. """Save an existing notebook object by notebook_id."""
  135. try:
  136. new_name = nb.metadata.name
  137. except AttributeError:
  138. raise web.HTTPError(400, u'Missing notebook name')
  139. if notebook_id is None:
  140. notebook_id = self.new_notebook_id(new_name)
  141. if notebook_id not in self.mapping:
  142. raise web.HTTPError(404, u'Notebook does not exist: %s' % notebook_id)
  143. old_name = self.mapping[notebook_id]
  144. old_checkpoints = self.list_checkpoints(notebook_id)
  145. path = self.get_path_by_name(new_name)
  146. try:
  147. self.log.debug("Autosaving notebook %s", path)
  148. with open(path,'w') as f:
  149. current.write(nb, f, u'json')
  150. except Exception as e:
  151. raise web.HTTPError(400, u'Unexpected error while autosaving notebook: %s' % e)
  152. # save .py script as well
  153. if self.save_script:
  154. pypath = os.path.splitext(path)[0] + '.py'
  155. self.log.debug("Writing script %s", pypath)
  156. try:
  157. with io.open(pypath,'w', encoding='utf-8') as f:
  158. current.write(nb, f, u'py')
  159. except Exception as e:
  160. raise web.HTTPError(400, u'Unexpected error while saving notebook as script: %s' % e)
  161. # remove old files if the name changed
  162. if old_name != new_name:
  163. # update mapping
  164. self.mapping[notebook_id] = new_name
  165. self.rev_mapping[new_name] = notebook_id
  166. del self.rev_mapping[old_name]
  167. # remove renamed original, if it exists
  168. old_path = self.get_path_by_name(old_name)
  169. if os.path.isfile(old_path):
  170. self.log.debug("unlinking notebook %s", old_path)
  171. os.unlink(old_path)
  172. # cleanup old script, if it exists
  173. if self.save_script:
  174. old_pypath = os.path.splitext(old_path)[0] + '.py'
  175. if os.path.isfile(old_pypath):
  176. self.log.debug("unlinking script %s", old_pypath)
  177. os.unlink(old_pypath)
  178. # rename checkpoints to follow file
  179. for cp in old_checkpoints:
  180. checkpoint_id = cp['checkpoint_id']
  181. old_cp_path = self.get_checkpoint_path_by_name(old_name, checkpoint_id)
  182. new_cp_path = self.get_checkpoint_path_by_name(new_name, checkpoint_id)
  183. if os.path.isfile(old_cp_path):
  184. self.log.debug("renaming checkpoint %s -> %s", old_cp_path, new_cp_path)
  185. os.rename(old_cp_path, new_cp_path)
  186. return notebook_id
  187. def delete_notebook(self, notebook_id):
  188. """Delete notebook by notebook_id."""
  189. nb_path = self.get_path(notebook_id)
  190. if not os.path.isfile(nb_path):
  191. raise web.HTTPError(404, u'Notebook does not exist: %s' % notebook_id)
  192. # clear checkpoints
  193. for checkpoint in self.list_checkpoints(notebook_id):
  194. checkpoint_id = checkpoint['checkpoint_id']
  195. path = self.get_checkpoint_path(notebook_id, checkpoint_id)
  196. self.log.debug(path)
  197. if os.path.isfile(path):
  198. self.log.debug("unlinking checkpoint %s", path)
  199. os.unlink(path)
  200. self.log.debug("unlinking notebook %s", nb_path)
  201. os.unlink(nb_path)
  202. self.delete_notebook_id(notebook_id)
  203. def increment_filename(self, basename):
  204. """Return a non-used filename of the form basename<int>.
  205. This searches through the filenames (basename0, basename1, ...)
  206. until is find one that is not already being used. It is used to
  207. create Untitled and Copy names that are unique.
  208. """
  209. i = 0
  210. while True:
  211. name = u'%s%i' % (basename,i)
  212. path = self.get_path_by_name(name)
  213. if not os.path.isfile(path):
  214. break
  215. else:
  216. i = i+1
  217. return name
  218. # Checkpoint-related utilities
  219. def get_checkpoint_path_by_name(self, name, checkpoint_id):
  220. """Return a full path to a notebook checkpoint, given its name and checkpoint id."""
  221. filename = "{name}-{checkpoint_id}{ext}".format(
  222. name=name,
  223. checkpoint_id=checkpoint_id,
  224. ext=self.filename_ext,
  225. )
  226. path = os.path.join(self.checkpoint_dir, filename)
  227. return path
  228. def get_checkpoint_path(self, notebook_id, checkpoint_id):
  229. """find the path to a checkpoint"""
  230. name = self.get_name(notebook_id)
  231. return self.get_checkpoint_path_by_name(name, checkpoint_id)
  232. def get_checkpoint_info(self, notebook_id, checkpoint_id):
  233. """construct the info dict for a given checkpoint"""
  234. path = self.get_checkpoint_path(notebook_id, checkpoint_id)
  235. stats = os.stat(path)
  236. last_modified = datetime.datetime.utcfromtimestamp(stats.st_mtime)
  237. info = dict(
  238. checkpoint_id = checkpoint_id,
  239. last_modified = last_modified,
  240. )
  241. return info
  242. # public checkpoint API
  243. def create_checkpoint(self, notebook_id):
  244. """Create a checkpoint from the current state of a notebook"""
  245. nb_path = self.get_path(notebook_id)
  246. # only the one checkpoint ID:
  247. checkpoint_id = "checkpoint"
  248. cp_path = self.get_checkpoint_path(notebook_id, checkpoint_id)
  249. self.log.debug("creating checkpoint for notebook %s", notebook_id)
  250. if not os.path.exists(self.checkpoint_dir):
  251. os.mkdir(self.checkpoint_dir)
  252. shutil.copy2(nb_path, cp_path)
  253. # return the checkpoint info
  254. return self.get_checkpoint_info(notebook_id, checkpoint_id)
  255. def list_checkpoints(self, notebook_id):
  256. """list the checkpoints for a given notebook
  257. This notebook manager currently only supports one checkpoint per notebook.
  258. """
  259. checkpoint_id = "checkpoint"
  260. path = self.get_checkpoint_path(notebook_id, checkpoint_id)
  261. if not os.path.exists(path):
  262. return []
  263. else:
  264. return [self.get_checkpoint_info(notebook_id, checkpoint_id)]
  265. def restore_checkpoint(self, notebook_id, checkpoint_id):
  266. """restore a notebook to a checkpointed state"""
  267. self.log.info("restoring Notebook %s from checkpoint %s", notebook_id, checkpoint_id)
  268. nb_path = self.get_path(notebook_id)
  269. cp_path = self.get_checkpoint_path(notebook_id, checkpoint_id)
  270. if not os.path.isfile(cp_path):
  271. self.log.debug("checkpoint file does not exist: %s", cp_path)
  272. raise web.HTTPError(404,
  273. u'Notebook checkpoint does not exist: %s-%s' % (notebook_id, checkpoint_id)
  274. )
  275. # ensure notebook is readable (never restore from an unreadable notebook)
  276. last_modified, nb = self.read_notebook_object_from_path(cp_path)
  277. shutil.copy2(cp_path, nb_path)
  278. self.log.debug("copying %s -> %s", cp_path, nb_path)
  279. def delete_checkpoint(self, notebook_id, checkpoint_id):
  280. """delete a notebook's checkpoint"""
  281. path = self.get_checkpoint_path(notebook_id, checkpoint_id)
  282. if not os.path.isfile(path):
  283. raise web.HTTPError(404,
  284. u'Notebook checkpoint does not exist: %s-%s' % (notebook_id, checkpoint_id)
  285. )
  286. self.log.debug("unlinking %s", path)
  287. os.unlink(path)
  288. def info_string(self):
  289. return "Serving notebooks from local directory: %s" % self.notebook_dir