Skip to content

Commit

Permalink
Factor communicate and watchdog logic to helper
Browse files Browse the repository at this point in the history
The goal is to improve readability by not repeating the platform
and kill_after_timeout check three times.
  • Loading branch information
EliahKagan committed Mar 7, 2024
1 parent 4191f7d commit 1ef3365
Showing 1 changed file with 18 additions and 14 deletions.
32 changes: 18 additions & 14 deletions git/cmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -1135,12 +1135,12 @@ def execute(
env.update(inline_env)

if sys.platform == "win32":
cmd_not_found_exception = OSError
if kill_after_timeout is not None:
raise GitCommandError(
redacted_command,
'"kill_after_timeout" feature is not supported on Windows.',
)
cmd_not_found_exception = OSError
else:
cmd_not_found_exception = FileNotFoundError
# END handle
Expand Down Expand Up @@ -1209,10 +1209,25 @@ def kill_process(pid: int) -> None:
pass
return

# END kill_process
def communicate() -> Tuple[AnyStr, AnyStr]:
watchdog.start()
out, err = proc.communicate()
watchdog.cancel()
if kill_check.is_set():
err = 'Timeout: the command "%s" did not complete in %d ' "secs." % (
" ".join(redacted_command),
kill_after_timeout,
)
if not universal_newlines:
err = err.encode(defenc)
return out, err

# END helpers

kill_check = threading.Event()
watchdog = threading.Timer(kill_after_timeout, kill_process, args=(proc.pid,))
else:
communicate = proc.communicate

# Wait for the process to return.
status = 0
Expand All @@ -1221,18 +1236,7 @@ def kill_process(pid: int) -> None:
newline = "\n" if universal_newlines else b"\n"
try:
if output_stream is None:
if sys.platform != "win32" and kill_after_timeout is not None:
watchdog.start()
stdout_value, stderr_value = proc.communicate()
if sys.platform != "win32" and kill_after_timeout is not None:
watchdog.cancel()
if kill_check.is_set():
stderr_value = 'Timeout: the command "%s" did not complete in %d ' "secs." % (
" ".join(redacted_command),
kill_after_timeout,
)
if not universal_newlines:
stderr_value = stderr_value.encode(defenc)
stdout_value, stderr_value = communicate()
# Strip trailing "\n".
if stdout_value.endswith(newline) and strip_newline_in_stdout: # type: ignore
stdout_value = stdout_value[:-1]
Expand Down

0 comments on commit 1ef3365

Please sign in to comment.