From 7405b84f0c12670cfe1b3cb490f136f40ee8496b Mon Sep 17 00:00:00 2001 From: Marc Wouts Date: Sat, 12 Oct 2019 19:37:55 +0200 Subject: [PATCH] Scripts with at least one unescaped magic command are 'hydrogen' scripts #339 --- jupytext/formats.py | 5 +++-- tests/test_formats.py | 7 +++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/jupytext/formats.py b/jupytext/formats.py index f2976439b..af9e79165 100644 --- a/jupytext/formats.py +++ b/jupytext/formats.py @@ -17,6 +17,7 @@ from .stringparser import StringParser from .languages import _SCRIPT_EXTENSIONS, _COMMENT_CHARS from .pandoc import pandoc_version, is_pandoc_available +from .magics import is_magic class JupytextFormatError(ValueError): @@ -219,8 +220,8 @@ def guess_format(text, ext): # Or a Sphinx-gallery script? if ext in _SCRIPT_EXTENSIONS: comment = _SCRIPT_EXTENSIONS[ext]['comment'] + language = _SCRIPT_EXTENSIONS[ext]['language'] twenty_hash = ''.join(['#'] * 20) - magic_re = re.compile(r'^(%|%%|%%%)[a-zA-Z]') double_percent_re = re.compile(r'^{}( %%|%%)$'.format(comment)) double_percent_and_space_re = re.compile(r'^{}( %%|%%)\s'.format(comment)) nbconvert_script_re = re.compile(r'^{}( | In\[[0-9 ]*\]:?)'.format(comment)) @@ -245,7 +246,7 @@ def guess_format(text, ext): nbconvert_script_re.match(line): double_percent_count += 1 - if magic_re.match(line): + if not line.startswith(comment) and is_magic(line, language): magic_command_count += 1 if line.startswith(twenty_hash) and ext == '.py': diff --git a/tests/test_formats.py b/tests/test_formats.py index afde9ff7c..aa343270e 100644 --- a/tests/test_formats.py +++ b/tests/test_formats.py @@ -26,6 +26,13 @@ def test_guess_format_sphinx(nb_file): assert guess_format(stream.read(), ext='.py')[0] == 'sphinx' +def test_guess_format_hydrogen(): + text = """# %% +cat hello.txt +""" + assert guess_format(text, ext='.py')[0] == 'hydrogen' + + def test_divine_format(): assert divine_format('{"cells":[]}') == 'ipynb' assert divine_format('''def f(x):