Tighten endless-wait: a timeout inside a loop caps nothing, and cover each branch
This commit is contained in:
@@ -3,6 +3,7 @@
|
||||
Both kinds hang the session that waits on them: `until [ -s f ] && ! pgrep -f "chunk-pr merg"; do sleep 15; done` matches its own shell, so its condition never holds.
|
||||
Shell forms it does not read: a loop inside a function, a variable or a script file, and a count or deadline it does not recognise (it refuses the loop, and an override waives that).
|
||||
"""
|
||||
import itertools
|
||||
import re
|
||||
|
||||
from command_lines.shell_command import launched, segments, Simple
|
||||
@@ -11,49 +12,45 @@ from command_lines.shell_command import launched, segments, Simple
|
||||
KEYWORDS = frozenset({"!", "do", "else", "then", "{"})
|
||||
LOOPS = frozenset({"for", "until", "while"})
|
||||
SHELLS = frozenset({"bash", "dash", "sh", "zsh"})
|
||||
# A word with which a loop counts its rounds or compares a clock: `[ "$n" -lt 40 ]`, `$SECONDS`.
|
||||
# A word with which a loop counts its rounds: `[ "$n" -lt 40 ]`.
|
||||
COUNTERS = frozenset({"-ge", "-gt", "-le", "-lt"})
|
||||
# `for ((;;))` has no condition. The lexer splits at its parentheses, so the check reads the command's text.
|
||||
FOREVER = re.compile(r"\bfor\s*\(\(\s*[^;)]*;\s*;")
|
||||
# A signal given to pkill, as -9 or -KILL, which is not a cluster of options.
|
||||
SIGNAL = re.compile(r"-(?:\d+|[A-Z]{2,})")
|
||||
# pgrep's and pkill's options that take a value, as short letters and as long names.
|
||||
VALUED = frozenset("dFgGPrstuU")
|
||||
VALUED_LONG = frozenset({"--delimiter", "--euid", "--group", "--ns", "--nslist", "--parent", "--pgroup", "--pidfile", "--runstates", "--session", "--signal", "--terminal", "--uid"})
|
||||
HOW = "use `~/.claude/bin/wait-for <file> [<pattern>] --timeout <seconds>`"
|
||||
|
||||
|
||||
def endless_waits(command: str, simples: list[Simple]) -> list[tuple[str, str]]:
|
||||
"""Each endless wait the command starts, as its detail and the directory it runs in."""
|
||||
return waits(command, simples, False)
|
||||
|
||||
|
||||
def waits(command: str, simples: list[Simple], capped: bool) -> list[tuple[str, str]]:
|
||||
"""capped is whether a `timeout` outside the simple commands ends them all, as for the inside of `timeout 60 bash -c '…'`."""
|
||||
found = [] if capped else [(f"a loop that sleeps, `{' '.join(loop[0].words)[:60]}`, has neither a time limit nor a count cap; {HOW}, or give the loop a deadline compared with `date`, `timeout`, or a count as in `for i in $(seq 1 40)`", loop[0].directory) for loop in loops(simples) if endless(loop, command)]
|
||||
def endless_waits(command: str, simples: list[Simple], capped: bool = False) -> list[tuple[str, str]]:
|
||||
"""Each endless wait the command starts, as its detail and the directory it runs in. capped is whether a `timeout` ends every loop in the simple commands, as it does inside `timeout 60 bash -c '…'`."""
|
||||
found = [] if capped else [(f"a loop that sleeps, `{' '.join(loop[0].words)[:60]}`, has neither a time limit nor a count cap; {HOW}, or give the loop a deadline compared with `date` or $SECONDS, or a counter, as in `for i in $(seq 1 40)`", loop[0].directory) for loop in loops(simples) if endless(loop, command)]
|
||||
for simple in simples:
|
||||
if (pattern := self_match(simple.words, command)) is not None:
|
||||
found.append((f"`{pattern}` is matched by the command line that holds this `pgrep -f` or `pkill -f`, so it finds its own shell; {HOW}, a `pgrep -x` on the process name, or a pattern the command doesn't contain, such as `[c]hunk` for `chunk`", simple.directory))
|
||||
if (script := shell_script(simple.words)) is not None:
|
||||
found += waits(command, [Simple(words, simple.directory) for words in segments(script)], capped or launched(simple.words, {"timeout"}) is not None)
|
||||
found += endless_waits(command, [Simple(words, simple.directory) for words in segments(script)], capped or launched(simple.words, {"timeout"}) is not None)
|
||||
return found
|
||||
|
||||
|
||||
def core(words: list[str]) -> list[str]:
|
||||
"""The words of a segment without the keywords before its command."""
|
||||
start = next((i for i, word in enumerate(words) if word not in KEYWORDS), len(words))
|
||||
return words[start:]
|
||||
return list(itertools.dropwhile(KEYWORDS.__contains__, words))
|
||||
|
||||
|
||||
def loops(simples: list[Simple]) -> list[list[Simple]]:
|
||||
"""Each loop as the segments from its keyword to its `done`, those of a loop nested in it included."""
|
||||
open_loops: list[list[Simple]] = []
|
||||
closed = []
|
||||
for simple in simples:
|
||||
words = core(simple.words)
|
||||
for simple in (Simple(core(simple.words), simple.directory) for simple in simples):
|
||||
first = simple.words[0] if simple.words else ""
|
||||
for loop in open_loops:
|
||||
loop.append(Simple(words, simple.directory))
|
||||
if words[:1] and words[0] in LOOPS:
|
||||
open_loops.append([Simple(words, simple.directory)])
|
||||
elif words[:1] == ["done"] and open_loops:
|
||||
loop.append(simple)
|
||||
if first in LOOPS:
|
||||
open_loops.append([simple])
|
||||
elif first == "done" and open_loops:
|
||||
closed.append(open_loops.pop())
|
||||
return closed + open_loops
|
||||
|
||||
@@ -67,10 +64,10 @@ def endless(loop: list[Simple], command: str) -> bool:
|
||||
# A list ends the loop; an arithmetic for, whose words end at the lexer's split at `((`, does only where it has a condition.
|
||||
return head == ["for"] and FOREVER.search(command) is not None
|
||||
# `while ((i < 10))` splits the same way, so a bare keyword reads as a count.
|
||||
if head == [head[0]]:
|
||||
if len(head) == 1:
|
||||
return False
|
||||
words = {word for simple in loop for word in simple.words}
|
||||
return not (COUNTERS & words or any("SECONDS" in word for word in words) or any(launched(simple.words, {"date", "timeout"}) for simple in loop))
|
||||
return not (COUNTERS & words or any("SECONDS" in word for word in words) or any(launched(simple.words, {"date"}) for simple in loop))
|
||||
|
||||
|
||||
def shell_script(words: list[str]) -> str | None:
|
||||
@@ -91,12 +88,9 @@ def self_match(words: list[str], command: str) -> str | None:
|
||||
for word in rest:
|
||||
if word.startswith("--"):
|
||||
full = full or word == "--full"
|
||||
if "=" not in word and word in VALUED_LONG:
|
||||
if word in VALUED_LONG:
|
||||
next(rest, None)
|
||||
elif word.startswith("-") and len(word) > 1:
|
||||
# A signal, such as -9 or -KILL, isn't a cluster of options.
|
||||
if word[1:].isdigit() or (word[1:].isupper() and len(word) > 2):
|
||||
continue
|
||||
elif word.startswith("-") and len(word) > 1 and not SIGNAL.fullmatch(word):
|
||||
for at, letter in enumerate(word[1:], 1):
|
||||
full = full or letter == "f"
|
||||
if letter in VALUED:
|
||||
@@ -104,7 +98,7 @@ def self_match(words: list[str], command: str) -> str | None:
|
||||
if at == len(word) - 1:
|
||||
next(rest, None)
|
||||
break
|
||||
else:
|
||||
elif not word.startswith("-") or len(word) == 1:
|
||||
patterns.append(word)
|
||||
return next((pattern for pattern in patterns if full and matches(pattern, command)), None)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user