Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 74 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
22 changes: 16 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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`
Expand All @@ -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,
Expand Down
61 changes: 52 additions & 9 deletions src/deadassert/shell.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -495,17 +507,37 @@ def _redirects_stdout(segment: str) -> bool:
return bool(re.search(r"(?<![0-9<>])>{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
Expand All @@ -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


Expand Down Expand Up @@ -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"

Expand Down
48 changes: 48 additions & 0 deletions tests/test_analyse.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Loading
Loading