Skip to content

Commit 285e58b

Browse files
committed
serverextension: Handle shell commands
1 parent 79ae3ea commit 285e58b

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

serverextension/jupyterlab_code_formatter/formatters.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111
from packaging import version
1212

1313

14+
SHELL_COMMAND_RE = re.compile(r"^!", flags=re.M)
15+
COMMENTED_SHELL_COMMAND_RE = re.compile(r"^# !#", flags=re.M)
1416
MAGIC_COMMAND_RE = re.compile(r"^%", flags=re.M)
1517
COMMENTED_MAGIC_COMMAND_RE = re.compile(r"^# %#", flags=re.M)
1618

@@ -37,8 +39,10 @@ def wrapped(self, code: str, notebook: bool, **options) -> str:
3739
has_semicolon = code.strip().endswith(";")
3840

3941
code = re.sub(MAGIC_COMMAND_RE, "# %#", code)
42+
code = re.sub(SHELL_COMMAND_RE, "# !#", code)
4043
code = func(self, code, notebook, **options)
4144
code = re.sub(COMMENTED_MAGIC_COMMAND_RE, "%", code)
45+
code = re.sub(COMMENTED_SHELL_COMMAND_RE, "!", code)
4246

4347
if notebook:
4448
code = code.rstrip()

serverextension/jupyterlab_code_formatter/tests/test_handlers.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,17 @@ def test_can_handle_magic(self):
162162
json_result = self._check_http_200_and_schema(response)
163163
assert json_result["code"][0]["code"] == expected
164164

165+
def test_can_handle_shell_cmd(self):
166+
"""Check that it's fine to run formatters for code with shell cmd."""
167+
given = '%%timeit\nsome_string = "abc"\n!pwd'
168+
expected = '%%timeit\nsome_string = "abc"\n!pwd'
169+
for formatter in ["black", "yapf", "isort"]:
170+
response = self._format_code_request(
171+
formatter=formatter, code=[given], options={},
172+
)
173+
json_result = self._check_http_200_and_schema(response)
174+
assert json_result["code"][0]["code"] == expected
175+
165176
def test_can_use_styler(self):
166177
given = "a = 3; 2"
167178
expected = "a <- 3\n2"

0 commit comments

Comments
 (0)