Skip to content

Commit 8c501c5

Browse files
committed
Quote arguments with whitespace when printing command
Currently, printing baked commands doesn't represent the way arguments are actually passed down to the program when values contain spaces. The solution is to take such values in single quotes. This is primarily to be able to copy printed commands and run them in a shell. BEFORE: ```python >>> from sh import ls >>> print(ls.bake('How I Met Your Mother')) /bin/ls How I Met Your Mother ``` AFTER: ```python >>> print(ls.bake('How I Met Your Mother')) /bin/ls 'How I Met Your Mother' ```
1 parent 3bf6891 commit 8c501c5

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

sh.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1391,10 +1391,10 @@ def bake(self, *args, **kwargs):
13911391
return fn
13921392

13931393
def __str__(self):
1394-
baked_args = " ".join(self._partial_baked_args)
1395-
if baked_args:
1396-
baked_args = " " + baked_args
1397-
return self._path + baked_args
1394+
if not self._partial_baked_args:
1395+
return self._path
1396+
baked_args = " ".join(shlex_quote(arg) for arg in self._partial_baked_args)
1397+
return f"{self._path} {baked_args}"
13981398

13991399
def __eq__(self, other):
14001400
return str(self) == str(other)

tests/sh_test.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2686,6 +2686,18 @@ def test_baked_command_can_be_printed(self):
26862686
ll = ls.bake("-l")
26872687
self.assertTrue(str(ll).endswith("/ls -l"))
26882688

2689+
def test_baked_command_can_be_printed_with_whitespace_args(self):
2690+
from sh import ls
2691+
2692+
ls_himym = ls.bake("How I Met Your Mother")
2693+
self.assertTrue(str(ls_himym).endswith("/ls 'How I Met Your Mother'"))
2694+
ls_himym = ls.bake("How I 'Met' Your Mother")
2695+
self.assertTrue(
2696+
str(ls_himym).endswith("""/ls 'How I '"'"'Met'"'"' Your Mother'""")
2697+
)
2698+
ls_himym = ls.bake('How I "Met" Your Mother')
2699+
self.assertTrue(str(ls_himym).endswith("""/ls 'How I "Met" Your Mother'"""))
2700+
26892701
# https://github.com/amoffat/sh/issues/185
26902702
def test_done_callback(self):
26912703
import time

0 commit comments

Comments
 (0)