diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1099f15..2e44278 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -284,6 +284,80 @@ jobs: assert all("shell expansion" in x["why"] for x in d["undecided"]), d["undecided"] PY + # logbook#77 and logbook#78: four control-flow shapes the tool + # recognises and cannot decide. Each one built a sentence saying so and + # then could not print it -- the loop condition was dropped before an + # `Assertion` existed, and the other three were labelled `needs-match`, + # which is live, counted, and usable as the witness that a string can + # appear. + # + # `printf` and `\$` for the same reason as the two steps above: these + # lines are arguments, not script, so the matchers in them stay out of + # this repository's own count. + - name: the shapes logbook#77 and logbook#78 were filed for + run: | + set -euo pipefail + mkdir -p branches/.github/workflows + printf '%s\n' \ + "'on': push" \ + "jobs:" \ + " j:" \ + " steps:" \ + " - run: |" \ + " if grep -q '^ over ssh *nothing\$' rows.txt; then" \ + " echo 'this bash does not source it'" \ + " else" \ + " grep -q '^ over ssh *\.bashrc\$' rows.txt" \ + " fi" \ + " - run: |" \ + " if grep -q 'plain row changed' rows.txt; then" \ + " echo noted" \ + " else" \ + " exit 1" \ + " fi" \ + " - run: |" \ + " while grep -q 'still building' status.txt; do" \ + " sleep 1" \ + " done" \ + " - run: |" \ + " if grep -q 'either way' out.txt; then" \ + " exit 1" \ + " else" \ + " echo other" \ + " exit 1" \ + " fi" \ + " - run: |" \ + " if grep -q 'unterminated' out.txt; then" \ + " exit 1" \ + > branches/.github/workflows/ci.yml + cat branches/.github/workflows/ci.yml + deadassert branches | tee branches.txt + deadassert branches --json > branches.json + python - <<'PY' + import json + d = json.load(open("branches.json")) + + # All four declined, each for its own stated reason. The lines + # matter: a reason landing on the wrong one of these would still + # give the right count. + why = {x["where"]: x["why"] for x in d["undecided"]} + assert sorted(why) == ["ci.yml:18", "ci.yml:22", "ci.yml:29", "ci.yml:6"], sorted(why) + assert "one side of an either-or" in why["ci.yml:6"], why["ci.yml:6"] + assert why["ci.yml:18"] == "the matcher is a loop condition, not a verdict", why + assert why["ci.yml:22"] == "either branch of the `if` can fail the step", why + assert why["ci.yml:29"] == "the `if` has no matching `fi` in this script", why + + # Six matchers in the file, four declined, so these two are the + # ones read -- and they are the whole discrimination. Line 9 is the + # matcher in the either-or's `else`, which is as load bearing as it + # ever was. Line 12 is a condition whose `else` exits on its own: + # nothing gets a say in that branch, so the condition really is the + # verdict and `needs-match` is right. Declining line 12 as well + # would be the easy over-correction, and it would show up here. + assert d["assertions"] == 2, d["assertions"] + assert d["findings"] == [], d["findings"] + PY + # The assertion above is only worth anything if it can go red. Break # one assertion in a copy of this file and check that it does. - name: a broken assertion in this file is caught diff --git a/README.md b/README.md index 903c7ff..8810500 100644 --- a/README.md +++ b/README.md @@ -176,6 +176,15 @@ stops being reported. function asserts nothing at all. That is not worked out here, so the body is declined rather than half-read, and every matcher in one is printed under `not read:`. +- **Control flow that is not a verdict is declined, not guessed.** A matcher + in a `while`/`until` condition is a poll, not an assertion — the loop ends, + the step carries on. A condition whose `else` branch *also* asserts is one + side of an either-or: `if grep -q A f; then :; else grep -q B f; fi` fails + only when neither pattern matches, so neither decides the step alone. An + `if` with no `fi` cannot be read at all. All three go in `not decided:`, + out of the counts, and — this is the part with teeth — cannot stand as the + witness that a string is ever produced. A condition whose `else` exits on + its own *is* the whole verdict, and is still read as `needs-match`. - **`unwitnessed` is a smell, not a proof.** It says nothing in *these workflows* establishes the string can appear. The proof may well live in a unit test, where it is arguably better placed. What the finding is really @@ -272,16 +281,17 @@ is small on purpose, and it is printed rather than hidden. ## Measured on something real Run across the 31 repositories of the organisation this was written in — 37 -workflow files, 364 `run:` scripts: +workflow files, 366 `run:` scripts: | | count | | --- | --- | -| assertions read | 183 | +| assertions read | 191 | | negated (`needs-no-match`) | 22 | | `unwitnessed` | 0 | | `prefix` | 0 | | `swallowed` / `masked` / `decorative` | 0 | -| not read | 79, in 24 scripts | +| not decided | 20 | +| not read | 87, in 26 scripts | No findings left anywhere, which is not the tool scoring zero — it is the end of a sweep. The first run found 33, 12 `unwitnessed` and 21 `prefix` @@ -295,9 +305,9 @@ allowing a non-zero findings exit before the output is asserted, which is correct usage. An early version of this tool reported all of them and was wrong to. -The last row is the one that changes how you should read the others. **79 -assertions in these files are not read at all** — 71 Python asserts, 5 -`diff`, 2 `jq -e` and 1 in a function body — against 183 that are, and they +The last row is the one that changes how you should read the others. **87 +assertions in these files are not read at all** — 79 Python asserts, 5 +`diff`, 2 `jq -e` and 1 in a function body — against 191 that are, and they are concentrated: 15 repositories have at least one, and 3 have nothing *but* unread assertions, so the verdict on them used to be `Nothing to check.` An all-clear here is a verdict about the greps in this organisation, diff --git a/src/deadassert/shell.py b/src/deadassert/shell.py index 308659c..3f9f500 100644 --- a/src/deadassert/shell.py +++ b/src/deadassert/shell.py @@ -14,7 +14,7 @@ output it names changes, the assertion keeps passing, forever, while no longer checking anything. It rots silently. -Three things in here exist because the first version got them wrong against +Four things in here exist because the first version got them wrong against real workflow files, and each one was a false positive rather than a miss: 1. A leading `!` negates the whole **pipeline**, not the command it sits in @@ -27,6 +27,18 @@ 3. `line=$(whichrc -q | grep '\\.bash_login:') || true` is a capture, not a swallowed assertion. The `|| true` is correct there -- no match is an expected answer, and the test comes later, on the variable. +4. A branch that fails *because a second matcher missed* does not make the + condition the verdict. `if grep -q A f; then :; else grep -q B f; fi` + fails only when neither pattern matches, so neither one decides the step + on its own, and calling the condition `needs-match` is a claim the step + does not make -- logbook#78. + +Where a shape is recognised but cannot be decided, the assertion carries +`polarity="undecided"` and a sentence saying why, and `analyse` prints it +under `not decided:`. Getting that wiring wrong is quiet in a particular way: +a reason attached to an assertion still labelled `needs-match` is never +printed *and* the assertion is counted and may stand as a witness. Three of +these sentences could not print at all before logbook#77 and logbook#78. """ from __future__ import annotations @@ -495,17 +507,37 @@ def _redirects_stdout(segment: str) -> bool: return bool(re.search(r"(?])>{1,2}\s*\S", segment)) -def _branch_polarity(lines: list[tuple[int, str]], index: int) -> tuple[str | None, str | None]: +def _branch_polarity(lines: list[tuple[int, str]], index: int) -> tuple[str, str | None]: """For an `if` at `index`, which branch can fail the step. A branch "can fail" if it holds an explicit `exit N`/`false`/`return N`, or a bare matcher assertion, which under `bash -e` fails the step by itself. Rule 2 in this module's docstring: leaving the second case out made a real `if`/`else` in `whichrc` look decorative. + + *How* a branch fails is tracked separately, because it changes what the + condition means -- rule 4, and logbook#78. A branch that fails on its own + makes the condition the whole verdict. A branch that fails only when a + *second* matcher misses makes the two patterns alternatives, and then + neither one decides the step by itself. """ depth = 0 branch = "then" + #: Whether the branch can fail the step at all. fails = {"then": False, "else": False} + #: Whether it has a way of failing that no matcher gets a say in. + alone = {"then": False, "else": False} + + def note(which: str, part: str) -> None: + asserts = _bare_assertion(part) + if _FAILING.search(part): + fails[which] = True + # An `exit` reached through `|| { ... }` on a matcher is that + # matcher's verdict, not an unconditional failure. + alone[which] = alone[which] or not asserts + if asserts: + fails[which] = True + for _, text in lines[index:]: for token in re.findall(r"(?:^|[;\s])(if|fi)(?=[;\s]|$)", text): depth += 1 if token == "if" else -1 @@ -522,20 +554,24 @@ def _branch_polarity(lines: list[tuple[int, str]], index: int) -> tuple[str | No inline = re.split(r";\s*(?:else|elif)\b", body, maxsplit=1) if len(inline) == 2: for part, which in zip((piece.strip() for piece in inline), ("then", "else")): - if _FAILING.search(part) or _bare_assertion(part): - fails[which] = True - elif _FAILING.search(body) or _bare_assertion(body): - fails[branch] = True + note(which, part) + else: + note(branch, body) if depth <= 0: break if depth > 0: - return None, "the `if` has no matching `fi` in this script" + return "undecided", "the `if` has no matching `fi` in this script" if fails["then"] and not fails["else"]: return "needs-no-match", None if fails["else"] and not fails["then"]: + if not alone["else"]: + return "undecided", ( + "the matcher is one side of an either-or: the `else` branch asserts too, " + "so the step fails only when neither pattern matches" + ) return "needs-match", None if fails["then"] and fails["else"]: - return None, "either branch of the `if` can fail the step" + return "undecided", "either branch of the `if` can fail the step" return "decorative", None @@ -588,10 +624,17 @@ def scan(script: str) -> list[Assertion]: condition = text head = re.match(r"^(?:el)?if\s+(.*?)(?:;\s*then\b|$)", text) + loop = re.match(r"^(?:while|until)\s+(.*?)(?:;\s*do\b|$)", text) if head and text.startswith(("if", "elif")): condition = head.group(1) polarity, undecided = _branch_polarity(lines, index) - elif re.match(r"^(?:while|until)\b", text): + elif loop: + # The keyword has to come off the front, exactly as the `if` path + # takes its condition out. Left on, `_matcher_head` reads `while` + # as the program, no matcher is found, no `Assertion` is appended, + # and the sentence built on the next line is thrown away with the + # loop variable -- logbook#77. + condition = loop.group(1) undecided = "the matcher is a loop condition, not a verdict" polarity = "undecided" diff --git a/tests/test_analyse.py b/tests/test_analyse.py index c92b717..cfc8c54 100644 --- a/tests/test_analyse.py +++ b/tests/test_analyse.py @@ -323,3 +323,51 @@ def test_an_unreadable_workflow_is_recorded_not_raised(self, tmp_path): def test_a_named_file_that_is_not_there(self, tmp_path): with pytest.raises(analyse.CorpusError, match="not a file"): analyse.analyse(".", paths=[str(tmp_path / "nope.yml")]) + + +class TestEitherOrDoesNotWitness: + """logbook#78's consequence with teeth. + + A `needs-match` pattern is a witness: proof that a string can appear. One + side of an either-or is not proof of that -- the other side may be what + appears -- so while it was labelled `needs-match` it could stand as the + witness that suppresses a real `unwitnessed` finding somewhere else. + """ + + either_or = ( + "if grep -q 'command over ssh *nothing' rows.txt; then\n" + " echo 'this bash does not source it'\n" + "else\n" + " grep -q 'command over ssh *.bashrc' rows.txt\n" + "fi" + ) + negated = "if grep -qF 'command over ssh *nothing' out.txt; then\n exit 1\nfi" + + def test_it_does_not_suppress_an_unwitnessed_finding(self, tmp_path): + result = analyse.analyse(repo(tmp_path, self.either_or, self.negated)) + assert kinds(result) == ["unwitnessed"] + + def test_an_unconditional_else_does_still_witness(self, tmp_path): + """The control: a condition that really is the whole verdict. + + Same two steps, except the `else` exits on its own. Here the + condition is a genuine `needs-match` and witnessing is correct, so + the finding is suppressed -- and the test above is measuring the + either-or and not just the pattern's spelling. + """ + decisive = ( + "if grep -q 'command over ssh *nothing' rows.txt; then\n" + " echo 'this bash does not source it'\n" + "else\n" + " exit 1\n" + "fi" + ) + result = analyse.analyse(repo(tmp_path, decisive, self.negated)) + assert result.findings == [] + + def test_it_leaves_the_counts_and_lands_in_not_decided(self, tmp_path): + result = analyse.analyse(repo(tmp_path, self.either_or)) + reasons = [why for _, why in result.undecided] + assert len(reasons) == 1 and "either-or" in reasons[0] + # The else branch's own matcher is still read and still counted. + assert [a.pattern for _, a in result.assertions] == ["command over ssh *.bashrc"] diff --git a/tests/test_shell.py b/tests/test_shell.py index faec729..6416da3 100644 --- a/tests/test_shell.py +++ b/tests/test_shell.py @@ -121,7 +121,13 @@ class TestBareAssertionCanFailABranch: `whichrc` decorative when its else branch asserts. """ - def test_else_branch_holding_only_a_bare_grep(self): + def test_else_branch_holding_only_a_bare_grep_is_not_decorative(self): + """The `whichrc` step this rule was written for. + + It must not read `decorative` -- the else branch really can fail the + step. It must not read `needs-match` either: that is logbook#78, and + `TestEitherOr` below is where the rest of this shape is pinned. + """ script = ( "if grep -q '^ ssh *nothing$' rows.txt; then\n" " echo 'this bash does not source it'\n" @@ -129,8 +135,26 @@ def test_else_branch_holding_only_a_bare_grep(self): " grep -q '^ ssh *\\.bashrc$' rows.txt\n" "fi" ) - found = shell.scan(script) - assert [a.polarity for a in found] == ["needs-match", "needs-match"] + condition = shell.scan(script)[0] + assert condition.polarity != "decorative" + assert condition.polarity == "undecided" + + def test_else_branch_with_an_unconditional_exit_still_needs_a_match(self): + """The control for logbook#78, and the whole discrimination. + + Nothing gets a say in whether this `else` fails, so the condition is + the entire verdict and `needs-match` is exactly right. Verified + against `bash -e`: with the pattern absent this script exits 1. + """ + script = ( + "if grep -q '^ ssh *nothing$' rows.txt; then\n" + " echo 'this bash does not source it'\n" + "else\n" + " echo 'no row' >&2\n" + " exit 1\n" + "fi" + ) + assert polarity(script) == "needs-match" class TestFlags: @@ -340,3 +364,124 @@ def test_spans_cover_both_definition_forms(self): assert shell.function_spans("function f {\n :\n}") == [(1, 3, "f")] assert shell.function_spans("f() { :; }") == [(1, 1, "f")] assert shell.function_spans("echo not-a-function") == [] + + +class TestEitherOr: + """`if grep A; then :; else grep B; fi` -- logbook#78. + + The step fails only when *neither* pattern matches, so neither pattern + decides it alone. Confirmed against `bash -e` with a file holding only + `B`: the script exits 0, which is what makes `needs-match` on `A` a + false label rather than a pessimistic one. + """ + + script = "if grep -q 'A' out.txt; then\n echo 'a note'\nelse\n grep -q 'B' out.txt\nfi" + + def test_the_condition_is_undecided_with_a_reason(self): + condition = shell.scan(self.script)[0] + assert condition.polarity == "undecided" + assert "either-or" in (condition.undecided or "") + + def test_the_else_branch_matcher_is_still_read(self): + """Only the condition's label was wrong; the else branch is unchanged. + + A matcher in a branch body is live if that branch runs, which this + module does not work out for any branch -- not a change made here. + """ + found = shell.scan(self.script) + assert [a.pattern for a in found] == ["A", "B"] + assert found[1].polarity == "needs-match" + + def test_an_exit_reached_through_the_else_matcher_is_still_either_or(self): + """`|| { exit 1; }` on the else matcher does not make it unconditional. + + The `exit` is that matcher's verdict. Reading it as an unconditional + failure would put this shape back on `needs-match`. + """ + script = ( + "if grep -q 'A' out.txt; then\n" + " echo 'a note'\n" + "else\n" + " grep -q 'B' out.txt || { echo 'neither' >&2; exit 1; }\n" + "fi" + ) + assert shell.scan(script)[0].polarity == "undecided" + + def test_a_matcher_and_an_exit_on_one_line_is_over_declined(self): + """Known over-decline, pinned so it is visible rather than folklore. + + `else grep -q B f; exit 1` fails whatever `B` does -- verified + against `bash -e`, exit 1 with `B` present -- so `needs-match` on the + condition is right and this declines it anyway. The multi-line + spelling of the same branch gets it right, because `note` is called + once per logical line and the `exit` arrives on its own; here both + commands reach it as one part. Declining is the safe direction and + no repository in the organisation writes it this way (0 of 37 + workflow files), so this is filed rather than fixed: splitting a part + on a top-level `;` has to stay out of `|| { ... }`, which is a + splitter with its own edge cases and not an end-of-shift change. + """ + script = "if grep -q 'A' f; then echo note; else grep -q 'B' f; exit 1; fi" + assert shell.scan(script)[0].polarity == "undecided" + + def test_a_then_branch_that_asserts_is_left_alone(self): + """`if grep A; then grep B; fi` is an implication, not a disjunction. + + Deliberately not changed: the step fails when `A` appears and `B` + does not, so `needs-no-match` on `A` is the generous-but-defensible + reading every branch body already gets. Pinned so that changing it + is a decision rather than an accident. + """ + script = "if grep -q 'A' out.txt; then\n grep -q 'B' out.txt\nfi" + assert shell.scan(script)[0].polarity == "needs-no-match" + + +class TestUndecidedReasonsAreReachable: + """Every sentence `scan` builds for a shape it cannot decide must print. + + Three of them could not. Two were attached to an assertion that was then + labelled `needs-match` -- live, counted, and usable as a witness -- and + `analyse` only reads `undecided` when the polarity says so. The third + (logbook#77) was thrown away with the loop variable. + """ + + def test_a_loop_condition_is_reported(self): + found = one("while grep -q 'y' f; do sleep 1; done") + assert found.polarity == "undecided" + assert found.undecided == "the matcher is a loop condition, not a verdict" + assert found.pattern == "y" + + @pytest.mark.parametrize( + "script", + [ + "while grep -q 'y' f; do exit 1; done", + "until grep -q 'y' f; do sleep 1; done", + "while ! grep -q 'y' f; do sleep 1; done", + "while grep -q 'y' f\ndo\n sleep 1\ndone", + ], + ) + def test_every_loop_form_reaches_it(self, script): + assert polarity(script) == "undecided" + + def test_a_loop_over_read_is_not_a_matcher_at_all(self): + """`while read -r f; do grep -q x "$f"; done`. + + The org's only `while` is this shape. The condition holds no matcher, + and the matcher in the body is live under `set -e` -- so the loop + keyword must not drag the body into `not decided:`. + """ + found = shell.scan('while read -r f; do\n grep -q "x" "$f"\ndone') + assert [a.polarity for a in found] == ["needs-match"] + + def test_a_producing_grep_in_a_loop_condition_is_still_not_an_assertion(self): + assert shell.scan("while grep -c 'y' f; do sleep 1; done") == [] + + def test_both_branches_able_to_fail_is_reported(self): + found = one("if grep -q 'A' f; then\n exit 1\nelse\n echo x\n exit 1\nfi") + assert found.polarity == "undecided" + assert found.undecided == "either branch of the `if` can fail the step" + + def test_an_if_with_no_fi_is_reported(self): + found = one("if grep -q 'A' f; then\n exit 1\n") + assert found.polarity == "undecided" + assert found.undecided == "the `if` has no matching `fi` in this script"