Skip to content
Python

fix(shell): a multi-line PowerShell command no longer hangs

Devika Vermad0c47ea75423
diff --git a/coworker/sandbox/runner/executor.py b/coworker/sandbox/runner/executor.py
index e6e2cb96..21dcd8cc 100644
--- a/coworker/sandbox/runner/executor.py
+++ b/coworker/sandbox/runner/executor.py
@@ -298,6 +298,12 @@ class LocalExecutor(Executor):
# Run the command, then emit a marker line with exit code + cwd.
self._proc.stdin.write(command + "\n")
+ if self._is_windows and "\n" in command.strip("\n"):
+ # The REPL keeps reading a statement that spans lines (`foreach (...) {` ... `}`)
+ # until an empty line, as in an interactive console. Without one, the trailer
+ # was read into the block and the call hung until its timeout. The parse check
+ # above guarantees the command is complete, so this line only ends it.
+ self._proc.stdin.write("\n")
self._proc.stdin.write(self._trailer())
self._proc.stdin.flush()
diff --git a/tests/test_shell.py b/tests/test_shell.py
index 7f0b3ec4..7ed74a32 100644
--- a/tests/test_shell.py
+++ b/tests/test_shell.py
@@ -149,6 +149,36 @@ def test_powershell_parse_check_leaves_valid_commands_alone(executor, tmp_path):
assert executor.run("cmd /c exit 3")["exit_code"] == 3
[email protected](not _WIN, reason="PowerShell's REPL waits for an empty line after a block")
+ "command, expected",
+ [
+ ('foreach ($i in 1..2) {\n Write-Output "n$i"\n}', ["n1", "n2"]),
+ ('foreach ($i in 1..2) {\n\n Write-Output "n$i"\n}', ["n1", "n2"]), # empty line inside
+ ("if ($true) {\n Write-Output yes\n} else {\n Write-Output no\n}", ["yes"]),
+ ("Write-Output a\nWrite-Output b\n", ["a", "b"]),
+ ],
+)
+def test_powershell_multi_line_command_finishes(executor, command, expected):
+ # Used to hang until the timeout: the trailer was read into the open block.
+ start = time.monotonic()
+ result = executor.run(command, timeout=8)
+ assert result["timed_out"] is False
+ assert result["exit_code"] == 0
+ assert result["output"].split() == expected
+ assert time.monotonic() - start < 6.0
+
+
[email protected](not _WIN, reason="PowerShell multi-line commands")
+def test_powershell_multi_line_keeps_exit_codes_and_state(executor):
+ assert executor.run("Write-Output a\ncmd /c exit 4")["exit_code"] == 4 # last line decides
+ assert executor.run("cmd /c exit 4\nWrite-Output a")["exit_code"] == 0
+ defined = executor.run("$cwMulti = 7\nfunction Get-CwMulti {\n 'from-function'\n}")
+ assert defined["exit_code"] == 0
+ used = executor.run("Get-CwMulti; $cwMulti")
+ assert used["output"].split() == ["from-function", "7"]
+
+
def test_timeout_kills_command(executor):
start = time.monotonic()
result = executor.run(SLEEP_5, timeout=1)