Skip to content

Commit

Permalink
More tests on new_untitled
Browse files Browse the repository at this point in the history
  • Loading branch information
mwouts committed May 28, 2020
1 parent 5e05a9d commit 9376703
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
31 changes: 28 additions & 3 deletions jupytext/contentsmanager.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""ContentsManager that allows to open Rmd, py, R and ipynb files as notebooks
"""
import os
import itertools
from datetime import timedelta, datetime
from collections import namedtuple
import nbformat
Expand Down Expand Up @@ -314,20 +315,44 @@ def new_untitled(self, path="", type="", ext=""):
We override the base function because that one does not take the 'ext' argument
into account when type=="notebook". See https://github.com/mwouts/jupytext/issues/443
"""
if type != "notebook":
return super(JupytextContentsManager, self).new_untitled(path)
if type != "notebook" and ext != ".ipynb":
return super(JupytextContentsManager, self).new_untitled(
path, type, ext
)

ext = ext or ".ipynb"
path = path.strip("/")
if not self.dir_exists(path):
raise HTTPError(404, "No such directory: %s" % path)

model = {"type": "notebook"}
untitled = self.untitled_notebook

name = self.increment_filename(untitled + ext, path)
name = self.increment_notebook_filename(untitled + ext, path)
path = u"{0}/{1}".format(path, name)
return self.new(model, path)

def increment_notebook_filename(self, filename, path=""):
"""Increment a notebook filename until it is unique, regardless of extension"""
# Extract the full suffix from the filename (e.g. .tar.gz)
path = path.strip("/")
basename, dot, ext = filename.partition(".")
ext = dot + ext

for i in itertools.count():
if i:
insert_i = "{}".format(i)
else:
insert_i = ""
basename_i = basename + insert_i
name = basename_i + ext
if not any(
self.exists(u"{}/{}{}".format(path, basename_i, nb_ext))
for nb_ext in self.notebook_extensions.split(",")
):
break
return name

def trust_notebook(self, path):
"""Trust the current notebook"""
if path.endswith(".ipynb") or path not in self.paired_notebooks:
Expand Down
4 changes: 3 additions & 1 deletion tests/test_contentsmanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -1708,5 +1708,7 @@ def test_new_untitled(tmpdir):
cm = jupytext.TextFileContentsManager()
cm.root_dir = str(tmpdir)

assert cm.new_untitled(type="notebook", ext=".md")["path"] == "Untitled.md"
assert cm.new_untitled(type="notebook")["path"] == "Untitled.ipynb"
assert cm.new_untitled(type="notebook", ext=".md")["path"] == "Untitled1.md"
assert cm.new_untitled(type="notebook", ext=".py")["path"] == "Untitled2.py"
assert cm.new_untitled(type="notebook")["path"] == "Untitled3.ipynb"

0 comments on commit 9376703

Please sign in to comment.