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
85 changes: 85 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,91 @@ jobs:
assert d["findings"] == [], d["findings"]
PY

# logbook#89 and logbook#81, which were one defect: both questions
# `_branch_polarity` asks of a branch are about one command, and a
# branch body was handed to them whole. On `main` this fixture produces
# *two false findings* rather than two wrong labels -- the polarity it
# invents at line 6 is live, so the line goes on to be reported
# `unwitnessed`, and line 15 is reported `decorative`, which says a
# working assertion is dead.
#
# `printf` for the reason the steps above use it: a heredoc's lines are
# physical lines of *this* script, and a fixture about dead assertions
# would arrive as findings against the file that built it.
- name: the shapes logbook#89 and logbook#81 were filed for
run: |
set -euo pipefail
mkdir -p either/.github/workflows
printf '%s\n' \
"'on': push" \
"jobs:" \
" j:" \
" steps:" \
" - run: |" \
" if grep -q 'either way' out.txt; then" \
" grep -q 'or this way' out.txt" \
" fi" \
" - run: |" \
" if grep -q 'the bad line' out.txt; then" \
" grep -q 'and its detail' out.txt" \
" exit 1" \
" fi" \
" - run: |" \
" if grep -q 'one line either way' out.txt; then grep -q 'or that' out.txt; fi" \
" - run: |" \
" if grep -q 'first row' rows.txt; then echo noted; else grep -q 'second row' rows.txt; exit 1; fi" \
" - run: |" \
" if grep -q 'present' out.txt; then echo noted; else grep -q 'absent' out.txt || { echo neither; exit 1; }; fi" \
> either/.github/workflows/ci.yml
cat either/.github/workflows/ci.yml

# Status captured rather than inherited: line 10 is a real finding
# on purpose -- it is the control for the shape that must stay live
# -- so this run exits 1 by design and `set -e` would end the step
# before a single assertion below ran.
set +e
deadassert either | tee either.txt; status=$?
deadassert either --json > either.json
set -e
test "$status" -eq 1

python - <<'PY'
import json
d = json.load(open("either.json"))

# Lines 6 and 15 are logbook#89: the `then` branch asserts, so the
# step fails only when the condition matches and the branch matcher
# misses, and the condition is not the verdict. Line 19 is
# logbook#78's `else` shape, unchanged, and its own control: the
# `exit` there is behind `|| { ... }` on a matcher, which is one
# command, so splitting must not reach the `;` inside the braces.
why = {x["where"]: x["why"] for x in d["undecided"]}
assert sorted(why) == ["ci.yml:15", "ci.yml:19", "ci.yml:6"], sorted(why)
assert "`then` branch" in why["ci.yml:6"], why["ci.yml:6"]
assert "`then` branch" in why["ci.yml:15"], why["ci.yml:15"]
assert "`else` branch" in why["ci.yml:19"], why["ci.yml:19"]

# Line 17 is logbook#81, and it is read rather than declined: its
# `else` holds a matcher and then an unconditional `exit`, so the
# condition is the whole verdict. Not in `undecided` above, and
# counted here.
assert d["assertions"] == 4, d["assertions"]

# Line 10 is the control the whole step rests on: a `then` branch
# that asserts *and* exits is still `needs-no-match`, which is the
# shape of every real guard in this organisation. It is the one
# negated assertion in the file and the one finding.
assert d["negated"] == 1, d["negated"]
found = {(f["kind"], f["line"]) for f in d["findings"]}
assert found == {("unwitnessed", 10)}, d["findings"]

# And the two findings `main` invents, named so a regression says
# which one came back: the `unwitnessed` is downstream of a false
# live polarity, the `decorative` calls a working assertion dead.
assert ("unwitnessed", 6) not in found, d["findings"]
assert ("decorative", 15) not in found, 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
35 changes: 24 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,17 +178,30 @@ stops being reported.
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. 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`.
the step carries on. A condition whose branch *also* asserts is one side of
an either-or and is declined, whichever branch it is:
`if grep -q A f; then :; else grep -q B f; fi` fails only when neither
pattern matches, and `if grep -q A f; then grep -q B f; fi` fails only when
`A` matches and `B` misses, so in neither one does `A` decide 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.

What is *not* declined is a branch that fails on its own. The branch is read
as the command list it is, so `else grep -q B f; exit 1` is the whole
verdict — the `exit` runs whatever `B` does — and stays `needs-match`, while
`else grep -q B f || { exit 1; }` is `B`'s own verdict and is declined. One
`;` apart, opposite answers.
- **A matcher inside a nested `if` in the branch is not seen.** `if grep -q A
f; then if grep -q B f; then exit 1; fi; fi` fails only when both match, and
it is read as though `A` decided it alone. This is the one place the reading
above is still too generous, and it is known rather than fixed: the branch is
split into commands, and a nested `if` is one command whose condition is not
read. It is the next thing to do here.
- **`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
156 changes: 146 additions & 10 deletions src/deadassert/shell.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,131 @@ def group_delta(text: str) -> int:
return delta


#: Keywords that open a compound command, and the words that close one. A `;`
#: inside one of these separates commands *inside the nested block*, not the
#: commands of the list being read, so it must not split one.
_BLOCK_OPEN = ("if", "while", "until", "for", "case", "select")
_BLOCK_CLOSE = ("fi", "done", "esac")

#: What may stand immediately before a word for that word to be a command
#: rather than an argument. Without this `echo fi` closes a block.
_COMMAND_AFTER = ";&|({"
_COMMAND_KEYWORD = re.compile(r"(?:^|[;\s&|(){])(?:then|else|elif|do|in)$")

#: A command list keeps going after `then`, `else`, `do` and `in` exactly as
#: it does after a `;` -- the reason `_FAILING` lists them too. Stripped off
#: the front of a part so the command behind one is visible to both.
LEADING_KEYWORD = re.compile(r"^(?:then|else|elif|do|in)\s+")


def _is_command(text: str, index: int) -> bool:
"""Whether the word at `index` stands where a command can start."""
before = text[:index].rstrip()
if not before:
return True
return before[-1] in _COMMAND_AFTER or bool(_COMMAND_KEYWORD.search(before))


def command_parts(text: str) -> list[str]:
"""`text` split on the `;` that separate one command from the next.

The scanning rules are `group_delta`'s, for the same reason: a `;` only
separates commands at the top level, and not one inside quotes,
`$(...)`, `${...}`, backticks, a `{ ... }` group, a `(...)` subshell or a
nested `if`/`while`/`case`. Each part comes back stripped, with any
leading `then`/`else`/`do` dropped, because a part is handed to
`_bare_assertion` and `command_head` starts its match at the program
name -- `then grep -q X f` reads as a command called `then`.

Why this is a splitter and not a regex: the two shapes it has to keep
apart are one `;` deep each.

grep -q 'B' f; exit 1 two commands -- the exit is nobody's verdict
grep -q 'B' f || { echo; exit 1; } one command -- the exit is grep's verdict

`&&` and `||` are left alone on purpose: they make what follows
conditional on a verdict, which is the distinction `_branch_polarity`
exists to read. A lone `&` separates commands too and is also left
alone -- not splitting declines rather than over-claims, and nothing in
37 workflow files backgrounds a command in a branch.
"""
parts: list[str] = []
start = 0
quote: str | None = None
#: Closers owed to `$(`, `${` and backticks, as in `group_delta`.
stack: list[str] = []
braces = 0
parens = 0
block = 0
index = 0
while index < len(text):
ch = text[index]
if quote:
if ch == quote:
quote = None
index += 1
continue
if ch in "'\"":
quote = ch
index += 1
continue
if ch == "`":
if stack and stack[-1] == "`":
stack.pop()
else:
stack.append("`")
index += 1
continue
if ch == "$" and index + 1 < len(text) and text[index + 1] in "({":
stack.append(")" if text[index + 1] == "(" else "}")
index += 2
continue
if ch == "(" and stack:
stack.append(")")
index += 1
continue
if ch in ")}" and stack and stack[-1] == ch:
stack.pop()
index += 1
continue
if stack:
index += 1
continue
if ch == "{" and (index == 0 or text[index - 1] in _GROUP_OPEN_AFTER):
if text[index + 1 : index + 2] in ("", " ", "\t"):
braces += 1
index += 1
continue
if ch == "}" and (index == 0 or text[index - 1] in " \t;&("):
braces -= 1
index += 1
continue
if ch == "(":
parens += 1
index += 1
continue
if ch == ")":
parens = max(parens - 1, 0)
index += 1
continue
if ch.isalpha() or ch == "_":
word = re.match(r"\w+", text[index:]).group(0)
if _is_command(text, index):
if word in _BLOCK_OPEN:
block += 1
elif word in _BLOCK_CLOSE:
block -= 1
index += len(word)
continue
if ch == ";" and braces <= 0 and parens <= 0 and block <= 0:
parts.append(text[start:index])
start = index + 1
index += 1
parts.append(text[start:])
stripped = (LEADING_KEYWORD.sub("", part.strip()) for part in parts)
return [part for part in stripped if part]


def function_spans(script: str) -> list[tuple[int, int, str]]:
"""`(first line, last line, name)` for each function definition.

Expand Down Expand Up @@ -562,16 +687,22 @@ def _branch_polarity(lines: list[tuple[int, str]], index: int) -> tuple[str, str
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. 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
# Asked per command, not per part. A branch body is a command list,
# and both questions below are about one command: `grep -q B f`
# followed by `exit 1` fails whatever `B` does, while
# `grep -q B f || { exit 1; }` fails only when `B` misses, and read
# as one blob those two are indistinguishable -- logbook#81.
for piece in command_parts(part):
asserts = _bare_assertion(piece)
if asserts:
fails[which] = True
if _FAILING.search(piece):
fails[which] = True
# An `exit` reached through `|| { ... }` on a matcher is that
# 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

for offset, (_, text) in enumerate(lines[index:]):
for token in re.findall(r"(?:^|[;\s])(if|fi)(?=[;\s]|$)", text):
Expand Down Expand Up @@ -608,6 +739,11 @@ def note(which: str, part: str) -> None:
if depth > 0:
return "undecided", "the `if` has no matching `fi` in this script"
if fails["then"] and not fails["else"]:
if not alone["then"]:
return "undecided", (
"the matcher is one side of an either-or: the `then` branch asserts too, "
"so a match here is not on its own what fails the step"
)
return "needs-no-match", None
if fails["else"] and not fails["then"]:
if not alone["else"]:
Expand Down
Loading
Loading