diff --git a/src/grimoire/services/moment_actions.py b/src/grimoire/services/moment_actions.py index 37a2fcbe..4f544df9 100644 --- a/src/grimoire/services/moment_actions.py +++ b/src/grimoire/services/moment_actions.py @@ -91,8 +91,10 @@ PROCESS_SKILL_PREFIX = "grimoire-proc-" PROCESS_MOMENTS_FIELD = "moments" PROCESS = "process" -_SEGMENT_SPLIT = re.compile(r"&&|\|\||[;|\n]") _ENV_ASSIGN = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=\S*\s+") +# `< str: def _segments(command: str) -> list[str]: - out = [] - for part in _SEGMENT_SPLIT.split(command or ""): - seg = part.strip().lstrip("(").strip() + """The commands a shell line runs, each from its head. + + Split where the shell separates commands (`&&`, `||`, `;`, `|`, a + newline) — but only outside quotes, and never inside a heredoc's body. A + quoted argument and the text a heredoc feeds a program are data, not + commands: `grep "a && git push"` runs grep, and a script written with + `cat < None: + seg = "".join(buf).strip().lstrip("(").strip() + buf.clear() while _ENV_ASSIGN.match(seg): seg = _ENV_ASSIGN.sub("", seg, count=1) seg = _squash(seg) if seg: out.append(seg) + + i, n, quote = 0, len(text), "" + while i < n: + c = text[i] + if quote: + if c == "\\" and quote == '"' and i + 1 < n: + buf.append(text[i:i + 2]) + i += 2 + continue + buf.append(c) + if c == quote: + quote = "" + i += 1 + continue + if c == "\\" and i + 1 < n: + # A backslash-newline continues the line; anything else is escaped. + if text[i + 1] != "\n": + buf.append(text[i:i + 2]) + i += 2 + continue + if c in "'\"": + quote = c + buf.append(c) + i += 1 + continue + if text.startswith("<<", i) and not text.startswith("<<<", i): + m = _HEREDOC.match(text, i) + if m: + heredocs.append((m.group(3), m.group(1) == "-")) + buf.append(m.group(0)) + i = m.end() + continue + if text.startswith("&&", i) or text.startswith("||", i): + flush() + i += 2 + continue + if c in ";|": + flush() + i += 1 + continue + if c == "\n": + flush() + i += 1 + # The bodies of this line's heredocs, in order, are skipped whole. + for word, tabs in heredocs: + while i < n: + end = text.find("\n", i) + line = text[i:end if end != -1 else n] + i = end + 1 if end != -1 else n + if (line.lstrip("\t") if tabs else line) == word: + break + heredocs.clear() + continue + buf.append(c) + i += 1 + flush() return out diff --git a/tests/test_moment_actions.py b/tests/test_moment_actions.py index cab3ceb2..a38b922b 100644 --- a/tests/test_moment_actions.py +++ b/tests/test_moment_actions.py @@ -62,6 +62,30 @@ def test_a_command_prefix_needs_a_word_boundary_and_the_head_of_a_segment(comman assert "work.deliver" not in _reached("Bash", {"command": command}) +@pytest.mark.parametrize("command", [ + # A heredoc's body is data fed to a program, whatever its lines say. + "python3 - <<'EOF'\nimport os\n | curl -fsS http://x\nEOF", + "cat > hook.sh < x.sh <<'EOF'\necho hi\nEOF\ncurl http://x", + "python3 - <