diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2e44278..017b578 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -242,6 +242,74 @@ jobs: assert unread == [("in function", "grep -qF 'ok' out.txt")], unread PY + # logbook#82, and the control that goes with it. Two shapes: one where + # the `elif` condition decides the step and one where nothing does. + # + # `negated` is what pins the fix. It counts `needs-no-match`, which is + # what `elif grep -q 'B'` is -- its own `then` branch exits. On `main` + # the walk broke on the `elif` line, the condition came out + # `decorative`, and this number was 0. A fix that simply declined every + # `elif` would also get the finding off 'B', so the second step is here + # to go red if `decorative` stops being reachable through one. + # + # `printf` for the same reason as the two steps around it: these lines + # are arguments, not script, so the matchers in them stay out of this + # repository's own count. + - name: the shapes logbook#82 was filed for + run: | + set -euo pipefail + mkdir -p elifs/.github/workflows + printf '%s\n' \ + "'on': push" \ + "jobs:" \ + " j:" \ + " steps:" \ + " - run: |" \ + " if grep -q 'A' f; then" \ + " echo a" \ + " elif grep -q 'B' f; then" \ + " exit 1" \ + " fi" \ + " - run: |" \ + " if grep -q 'C' f; then" \ + " echo c" \ + " elif grep -q 'D' f; then" \ + " echo d" \ + " fi" \ + > elifs/.github/workflows/ci.yml + + # Status captured rather than inherited: the control shapes are + # real findings, so this run exits 1 by design and `set -e` would + # end the step before a single assertion below ran. + set +e + deadassert elifs --json > elifs.json; status=$? + set -e + test "$status" -eq 1 + + python - <<'PY' + import json + d = json.load(open("elifs.json")) + kinds = {(f["kind"], f["pattern"]) for f in d["findings"]} + + # The false positive itself. 'B' decides its step, so no finding may + # call it dead -- on `main` this was ("decorative", "B"). + assert ("decorative", "B") not in kinds, kinds + + # And it is read the right way round, not merely declined: `negated` + # counts `needs-no-match` and is 0 on `main`. + assert d["negated"] == 1, d["negated"] + + # The condition above it, gated by the `elif`: the step exits 0 when + # 'A' misses and 'B' misses, so `needs-match` was a claim the step + # does not make. Declined, with the either-or sentence. + declined = {(x["where"], "either-or" in x["why"]) for x in d["undecided"]} + assert declined == {("ci.yml:6", True)}, d["undecided"] + + # The control: `decorative` is still reachable through an `elif`. + assert ("decorative", "C") in kinds, kinds + assert ("decorative", "D") in kinds, kinds + PY + # logbook#71: a `$` with nothing after it is a regex anchor, and used to # send the whole assertion to `not decided` as a "shell expansion". The # three lines below are the three answers this has to keep apart, and diff --git a/README.md b/README.md index 8810500..4c82865 100644 --- a/README.md +++ b/README.md @@ -180,8 +180,12 @@ stops being reported. 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:`, + only when neither pattern matches, so neither decides the step alone. The + same holds when the second matcher is an `elif` rather than an `else`: + `if grep -q A f; then :; elif grep -q B f; then exit 1; fi` fails only when + `A` misses *and* `B` matches, so `A` is declined — while `B`, read where it + is actually reached, is the verdict there and comes out `needs-no-match`. An + `if` with no `fi` cannot be read at all. All of those 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`. diff --git a/src/deadassert/shell.py b/src/deadassert/shell.py index 3f9f500..96c1b21 100644 --- a/src/deadassert/shell.py +++ b/src/deadassert/shell.py @@ -520,29 +520,75 @@ def _branch_polarity(lines: list[tuple[int, str]], index: int) -> tuple[str, str 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. + + `elif` is the same walk with two corrections, both logbook#82. An `elif` + is *the subject* when the matcher is in its own condition: its branch is + its own `then`, and the walk has to start already inside the enclosing + block, because `depth` is counted from the tokens on each line and the + `if` in `elif` is preceded by `el` rather than a separator -- so it was + never counted, the walk broke on its first line, and the function fell + through to `decorative` over no branches at all. + + An `elif` is *part of the else-path* when the matcher is in an earlier + condition in the same chain. A later condition holding a matcher gates + everything the else-path can do, so a failure reached past one is not a + failure "no matcher gets a say in" -- it is logbook#78's either-or with + the second matcher one line further away. `if A; then :; elif B; then + exit 1; fi` exits 1 only when `A` misses *and* `B` matches, which is not + what `needs-match` claims about `A`. + + Polarity is what this condition's status does to the step *when it is + reached*, which is the convention everywhere else here: a matcher nested + inside another `if` is read the same way, and an `elif` is gated by the + conditions above it exactly as nesting gates that one. """ - depth = 0 + subject = lines[index][1] + #: An `elif` subject is already inside its enclosing `if`. Seeding this + #: is the whole of logbook#82's first half: counted from the line's own + #: tokens it stays 0, and `if depth <= 0: break` then ends the walk + #: before a single branch has been read. + depth = 1 if subject.startswith("elif") else 0 + #: Whether the walk ever got inside the block it is about. A walk that + #: did not has established nothing, and must not report `decorative` -- + #: logbook#77's lesson one function up, made an invariant here. + entered = depth >= 1 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} + #: Set once a later `elif` condition holds a matcher: from there on the + #: else-path is gated by it, so nothing it does is unconditional. + gated = 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 + # matcher's verdict, not an unconditional failure. Neither is one + # reached past an `elif` condition that holds a matcher. + unconditional = not asserts and not (which == "else" and gated) + alone[which] = alone[which] or unconditional if asserts: fails[which] = True - for _, text in lines[index:]: + for offset, (_, text) in enumerate(lines[index:]): for token in re.findall(r"(?:^|[;\s])(if|fi)(?=[;\s]|$)", text): depth += 1 if token == "if" else -1 - if depth == 1 and re.match(r"^(?:else|elif)\b", text): + # Asked per token, not per line: a one-line `if ... fi` opens and + # closes the block before the line ends, so a depth read after the + # line says the walk was never inside it. That shape is live, and + # `TestOneLineIf` caught this guard getting it wrong. + entered = entered or depth >= 1 + # `offset` keeps the subject line out of this: an `elif` subject is + # its own `then` branch, and flipping on it would credit everything + # it does to an `else` that has not started. + if offset and depth == 1 and re.match(r"^(?:else|elif)\b", text): branch = "else" + condition = re.match(r"^elif\s+(.*?)(?:;\s*then\b|$)", text) + if condition and _bare_assertion(condition.group(1)): + gated = True body = text head = re.match(r"^(?:el)?if\s+(.*?)(?:;\s*then\b|$)", text) if head and text.startswith(("if", "elif")): @@ -572,6 +618,8 @@ def note(which: str, part: str) -> None: return "needs-match", None if fails["then"] and fails["else"]: return "undecided", "either branch of the `if` can fail the step" + if not entered: + return "undecided", "the `if` structure could not be read, so no branch was examined" return "decorative", None diff --git a/tests/test_shell.py b/tests/test_shell.py index 6416da3..925c586 100644 --- a/tests/test_shell.py +++ b/tests/test_shell.py @@ -436,6 +436,189 @@ def test_a_then_branch_that_asserts_is_left_alone(self): assert shell.scan(script)[0].polarity == "needs-no-match" +class TestElifConditions: + r"""A matcher in an `elif` condition, and what the chain does to the one above it. + + Before logbook#82 the first of these read `decorative` -- a finding kind, + so the tool reported a load-bearing assertion as dead. `_branch_polarity` + was called with the `elif`'s own index and `depth` is counted from the + tokens on each line, where the `if` in `elif` is preceded by `el` rather + than a separator. It was never counted, `if depth <= 0: break` ended the + walk on the first line, and the function fell through to its last line: a + verdict over no branches at all. + + Every expectation below was taken from running the shape under `bash -e` + for each combination of which patterns are present in `f`, never from + reading the code. The exit statuses, with the file holding the patterns + named in each column: + + none A B C AB BC AC ABC + 1 elif-then-exit 0 0 1 . 0 1 . 0 + 2 elif-harmless 0 0 0 . 0 0 . 0 + 3 elif-else-exit 1 0 0 . 0 0 . 0 + 4 elif-bang-then-exit 1 0 0 . 0 0 . 0 + 6 nested-if-in-elif 0 0 1 0 0 1 0 0 + 8 elif-chain-three-way 0 0 1 1 0 1 0 0 + + Polarity is what the condition's status does to the step *when it is + reached*, which is the convention the rest of the module already uses: a + matcher nested inside another `if` is read the same way, and an `elif` is + gated by the conditions above it exactly as nesting gates that one. + """ + + def test_an_elif_condition_with_a_failing_then_needs_no_match(self): + """logbook#82's repro. This read `decorative` before. + + Shape 1: the step exits 1 exactly when `B` is present and `A` is not, + so `B`'s own `then` branch is the verdict and the polarity is the way + round that says "this rots silently if the output stops being + produced". + """ + script = "if grep -q 'A' f; then\n echo a\nelif grep -q 'B' f; then\n exit 1\nfi" + found = {a.pattern: a for a in shell.scan(script)} + assert found["B"].polarity == "needs-no-match" + assert found["B"].polarity != "decorative" + + def test_the_condition_above_it_is_gated_by_the_elif(self): + """The other half of logbook#82, and the half with a live polarity. + + For `A`, the `exit 1` on the else-path sits behind `B`: shape 1 exits + 0 with `A` absent and `B` absent. `needs-match` -- "the step fails + when the pattern is absent" -- is a claim the step does not make, and + it is a *live* polarity, so it counted and could stand as a witness. + This is logbook#78 with the second matcher one line further away. + """ + script = "if grep -q 'A' f; then\n echo a\nelif grep -q 'B' f; then\n exit 1\nfi" + found = {a.pattern: a for a in shell.scan(script)} + assert found["A"].polarity == "undecided" + assert "either-or" in (found["A"].undecided or "") + + def test_an_elif_whose_branches_do_nothing_is_still_decorative(self): + """The control. `decorative` must stay reachable through an `elif`. + + Shape 2 exits 0 for every combination, so both conditions really are + decorative. A fix that declined every `elif` would pass the two tests + above and lose the finding this tool exists to report. + """ + script = "if grep -q 'A' f; then\n echo a\nelif grep -q 'B' f; then\n echo b\nfi" + assert [a.polarity for a in shell.scan(script)] == ["decorative", "decorative"] + + def test_an_elif_whose_else_exits_unconditionally_needs_a_match(self): + """Shape 3, where nothing gets a say in the `else`. + + Reached with `A` absent, the step exits 1 unless `B` matches, so the + `elif` condition is the whole verdict from there. + """ + script = ( + "if grep -q 'A' f; then\n" + " echo a\n" + "elif grep -q 'B' f; then\n" + " echo b\n" + "else\n" + " exit 1\n" + "fi" + ) + found = {a.pattern: a for a in shell.scan(script)} + assert found["B"].polarity == "needs-match" + + def test_a_negated_elif_condition_is_the_other_way_round(self): + """Shape 4. The `!` is handled in `scan`, but on a polarity this + function now actually produces -- before, it inverted `decorative`, + which is to say it did nothing.""" + script = "if grep -q 'A' f; then\n echo a\nelif ! grep -q 'B' f; then\n exit 1\nfi" + found = {a.pattern: a for a in shell.scan(script)} + assert found["B"].polarity == "needs-match" + + def test_a_nested_if_in_the_elif_body_does_not_end_the_walk(self): + """Shape 6. The seeded depth has to stay a real depth counter. + + An `if`/`fi` pair inside the body returns to the same depth it + started at, so the walk must still be running when `exit 1` arrives + two lines later. + """ + script = ( + "if grep -q 'A' f; then\n" + " echo a\n" + "elif grep -q 'B' f; then\n" + " if true; then\n" + " echo inner\n" + " fi\n" + " exit 1\n" + "fi" + ) + found = {a.pattern: a for a in shell.scan(script)} + assert found["B"].polarity == "needs-no-match" + + def test_a_three_way_chain_declines_the_middle_condition(self): + """Shape 8, and the reason the gating is not simply ignored. + + With `A` absent the step exits 1 when `B` matches, and also when `B` + misses and `C` matches -- both branches of `B`'s walk can fail, which + is the sentence this already had. `C`, last in the chain, has nothing + below it and is the verdict where it is reached. + """ + script = ( + "if grep -q 'A' f; then\n" + " echo a\n" + "elif grep -q 'B' f; then\n" + " exit 1\n" + "elif grep -q 'C' f; then\n" + " exit 1\n" + "fi" + ) + found = {a.pattern: a for a in shell.scan(script)} + assert found["B"].polarity == "undecided" + assert found["B"].undecided == "either branch of the `if` can fail the step" + assert found["C"].polarity == "needs-no-match" + + def test_a_then_branch_whose_only_failure_is_a_matcher_is_over_decided(self): + """Pinned, not fixed: logbook#89, and not an `elif` problem at all. + + `alone` is tracked for both branches and read only for the `else`, so + the mirror of logbook#78 in the `then` branch still reports a live + polarity. Under `bash -e` this exits 1 only when `A` matches and `C` + misses -- `A` present with `C` present exits 0 -- so `needs-no-match` + is not true of `A`. Pinned here so the behaviour is written down + rather than folklore, and so fixing logbook#89 has to come past it. + """ + found = {a.pattern: a for a in shell.scan("if grep -q 'A' f; then\n grep -q 'C' f\nfi")} + assert found["A"].polarity == "needs-no-match" + + +class TestAVerdictOverNoBranches: + r"""`decorative` must not be reachable from a walk that read nothing. + + This is logbook#77's lesson one function up, made an invariant: a walk + that never got inside the block has not established that neither branch + can fail, and `decorative` says exactly that. It is what would have made + logbook#82 announce itself in `not decided:` instead of answering wrongly. + + It is unreachable through `scan` today, and deliberately kept anyway. + `scan` only calls `_branch_polarity` on a line matching `^(?:el)?if\s+`: + an `elif` seeds the depth, and an `if` is matched by the depth regex on + its own first line. So the guard is tested by calling the function + directly, which is the only honest way to show the sentence can print. + """ + + def test_a_walk_that_never_entered_the_block_declines(self): + polarity, why = shell._branch_polarity([(1, "while grep -q 'x' f")], 0) + assert polarity == "undecided" + assert why == "the `if` structure could not be read, so no branch was examined" + + def test_a_one_line_if_still_enters_its_block(self): + """The guard's own near-miss, caught by `TestOneLineIf`. + + A one-line `if ... fi` opens and closes the block on one line, so a + depth read after the line says the walk was never inside it. Asked + per token instead. This shape is live -- the org writes it -- so the + first version of the guard would have turned a real `decorative` into + a decline. + """ + found = one("if grep -q 'y' f; then echo noted; fi") + assert found.polarity == "decorative" + assert found.undecided is None + + class TestUndecidedReasonsAreReachable: """Every sentence `scan` builds for a shape it cannot decide must print.