Skip to content

Fix: Parse project names instead of grepping - #178

Merged
tykeal merged 1 commit into
mainfrom
fix/name-extraction
Oct 2, 2026
Merged

tykeal merged 1 commit into
mainfrom
fix/name-extraction

Conversation

@ModeSevenIndustrialSolutions

Copy link
Copy Markdown
Member

Summary

The project name is now parsed from pyproject.toml and setup.py rather than grepped. Valid files the old patterns missed now work, and the two cases where the wrong name was returned are fixed.

Problem (#169)

  • pyproject.toml: (?<=^name = ")([^"]*) only matched double quotes with exactly that spacing, so name = 'x', name="x" and name = "x" gave no name. It also wasn't scoped to [project], so a [[tool.uv.index]] name = "pytorch" before [project] was returned as the project name.
  • setup.py: (?<=name=")([^"]*) missed single quotes and spacing. It had no word boundary, so package_name="helper" matched and returned helper.
  • A missed name failed the action with a misleading "no project name found" error.

Changes

action.yaml: both file-grep-regex-action steps are replaced by inline steps with the same step IDs and extracted_string output, so every if: condition and the capture step are unchanged.

  • pyproject.toml: parsed with tomllib, reading [project].name, then [tool.poetry].name. Only a non-empty string counts, in both parsers, so a non-string [project] name falls through to Poetry whatever the parser mode.
    • The Poetry fallback isn't in the issue, but Poetry 1.x projects keep their name only there, and the old unscoped pattern did match them. Strict [project]-only scoping would have broken them.
  • setup.py: parsed with ast, reading the string-literal name= keyword of a setup() call. Imports, star imports, definitions, assignments and other binding statements (for targets, with/except … as, :=, match captures, del) bind names in source order; only names an assignment really rebinds count, not the base of an attribute or subscript target. Names resolve in evaluation order (a call or binding takes effect where it ends, so setup = setup(...) calls first, a for loop binds before its body, and each with item binds before the next runs), and setup counts only when bound to one from a packaging module (setuptools, distutils.core, numpy.distutils.core, skbuild), under any alias or module path. Rebinding a name also drops the dotted paths recorded beneath it, so after import helper as distutils, distutils.core.setup() doesn't count. A local def setup, a setup from another module, a star import from elsewhere, helper.setup(...) or an unbound setup() doesn't count. A def or class header (decorators, defaults, bases) runs where it's defined, so a setup() there counts at that position. Annotations don't count: they're deferred under from __future__ import annotations, lazy from Python 3.14, and never evaluated for local variables. Control flow is followed: if, loop, try and match branches each start from the same state and merge where they meet, so a binding on a path that may not run (an untaken if, a loop body, an except handler) leaves a name ambiguous rather than replacing it. A call counts only when every path that binds the name binds it to a packaging setup (paths where it's unbound are ignored, so try/except ImportError fallbacks keep working), and a call in a loop must hold on every pass. A call on a path that may not run (an if branch, an except handler, a match case, a loop or comprehension body, a later and/or operand, a branch of a conditional expression) is only a candidate: a call that certainly runs wins, so a dead branch can't supply the name ahead of the real call. In the function-body fallback, a function the file calls ranks above one it never does. A block stops at return, raise, break or continue, so code after one never supplies the name, and del leaves a name unbound. Module-level calls win; function and class bodies, which may never run, count only when module level calls no bare setup() (e.g. setup() inside a main() the file calls). Each body is then scanned as its own scope, starting from the bindings it inherits (the module's final ones, an enclosing function's, but not a class body's for its methods) with its own parameters bound locally, so a name bound in one function never leaks into another. As in Python, every name a function binds anywhere in its body (except global/nonlocal ones), including a simple x: T with no value, is local from the start, so calling it before it's bound reaches nothing. Comprehensions are scopes too: a call in one sees its loop targets and any earlier := in it, while the targets never leak out; a := inside a lambda stays in the lambda.
  • Fallback: when python3 is missing, too old for tomllib (e.g. 3.10 on ubuntu-22.04), or can't parse the file, a portable awk match is used. It is scoped to the same TOML tables, or requires name as a whole word in setup.py.
  • Validation: both steps apply the setup.cfg step's PEP 508-style name check to the whole string, because a TOML or Python escape can embed a newline.
    • The parsers run the check in Python, before printing. Bash command substitution drops NUL bytes, so "foo\^@bar" (TOML) or "foo\x00bar" (setup.py) would otherwise reach the shell as foobar and pass.
    • The awk fallback skips any file containing a raw NUL byte (neither format allows one), because mawk and gawk pass it through to the same effect.
    • The setup.cfg step gains the same raw-NUL guard, which it lacked, and now also matches the whole string and logs rejected values with %q, so all three sources are checked alike.
    • The shell-side check stays, for the fallback's output. Rejected values are logged with repr() or %q, so they can't inject workflow commands.
  • Output: written to GITHUB_OUTPUT with a random heredoc delimiter.

.github/workflows/testing.yaml: a new name-extraction job, one job per parser mode (3 jobs):

  • Modes: tomllib on the runner, no-tomllib in a real python:3.10-slim, and no-python in ubuntu:24.04. Both images are pinned by digest, and a guard step fails the job if an image doesn't provide its mode.
  • Fixtures (53): each case from the issue, Poetry-only and [project]-over-Poetry files, aliased setup imports, module-qualified and unrelated setup() calls, shadowed setup imports in either order, setup() in function bodies, a local def setup, a star import from elsewhere, an unbound setup(), a rebound packaging module root, imports in an unrelated function and a class body, attribute assignments, a shadowing parameter, a for loop rebinding setup, a comprehension variable, a comprehension target shadowing setup, a match capture rebinding setup, a setup() call in a default value, a default that runs before its def rebinds setup, a walrus in a comprehension condition, a non-string [project] name with a Poetry name, a setup() call in a deferred annotation, a with item binding before the next, a setup.cfg holding a raw NUL, del setup, a walrus inside a lambda in a comprehension, a call before a local assignment, a local annotation without a value, a packaging import in a dead branch, a try/except ImportError fallback, a loop rebinding setup after the call, a dead call before the real call, an uncalled function before main(), a conditional del before the real call, a call after return, a short-circuited call, and NUL names as escapes and raw bytes.
  • Flow: one step writes every fixture into f/NN/ with its expectations, one uses: $/ step per fixture runs with continue-on-error, and a final step asserts all four outputs of each (or that the action failed without emitting a name), reporting every failure. Fixtures that need import resolution aren't asserted in no-python mode, because the awk fallback can't resolve imports.

README.md: the lookup-order section describes the parsing, the fallback and the name check.

Validation

Fixture upstream/main this branch
pyproject name = 'my-project' ❌ no project name found ✅ my-project
pyproject name="my-project" ❌ no project name found ✅ my-project
pyproject name = "my-project" ❌ no project name found ✅ my-project
[[tool.uv.index]] name = "pytorch" before [project] ❌ pytorch ✅ my-project
setup(name='my-project') ❌ extraction failed ✅ my-project
name = "my-project", ❌ extraction failed ✅ my-project
package_name="helper" then name="my-project" ❌ helper ✅ my-project
  • Other environments: the same seven cases pass with no python3, with Python 3.9, 3.10 and 3.12, under macOS bash 3.2, and in ubuntu:24.04 with mawk and no Python. Existing fixtures (setup.cfg, fall-through, build-system-only) give the same results as before. I re-ran all seven fixtures through the extracted steps before committing.
  • Checks: prek run, zizmor --persona=auditor, actionlint, shellcheck clean. ruff --select ALL on the embedded Python is clean. aislop has nothing to score (YAML and Markdown).
  • CI: the job is in Test GitHub Action 🧪, which runs on every PR once the layer below removes its path filter.

⚠️ Behaviour changes for callers

  • Files that used to fail now succeed, and the two wrong names (pytorch, helper) are corrected.
  • A name found only in an unrelated table now gives a clear "no project name found" instead of the wrong name.
  • A non-literal name= in setup.py now yields nothing.
  • Names outside the PEP 508 character set are now rejected from these two sources too.
  • The removed sub-action used to export extracted_string as an undocumented environment variable. Nothing in this action or the org reads it.
  • In-org callers (pypi-publish-action, python-audit-action, python-project-metadata-action) pin v0.1.8, so they need a release and pin bump to pick this up.

Stack

This is the middle layer of a stack, and replaces #173, which it supersedes with the same commit:

  1. Test: Run tests on every PR and reset ERROR (Test: PR path filter skips test changes; ERROR uninitialised #170)
  2. This PR (Bug: Name regexes miss valid quoting and spacing #169)
  3. Fix: Follow setup.py calls from code that runs (Bug: setup.py extraction misreads class-body timing and recursive calls #176)

Closes #169

This comment was marked as outdated.

Base automatically changed from test/pr-trigger to main October 2, 2026 13:41
@ModeSevenIndustrialSolutions
ModeSevenIndustrialSolutions requested a review from a team October 2, 2026 13:41
The pyproject.toml and setup.py name lookups used PCRE patterns that
only matched one double-quoted spelling. Valid files using single
quotes or other spacing yielded no name, so the action failed with a
misleading "no project name found" error. Neither pattern was scoped:
a name in [[tool.uv.index]] before [project] was returned as the
project name, and package_name="helper" in setup.py matched as name.

Replace both file-grep-regex-action steps with inline steps that keep
the extracted_string output, so the fall-through conditions and the
capture step are unchanged:

- pyproject.toml is parsed with tomllib and reads [project].name,
  falling back to [tool.poetry].name so Poetry 1.x projects, which
  the old unscoped pattern matched, keep working. Only a non-empty
  string counts, in both parsers, so a non-string [project] name falls
  through to Poetry whatever the parser mode.
- setup.py is parsed with ast and reads the string-literal name keyword
  of a setup() call. Imports, star imports, definitions, assignments and
  other binding statements (for targets, with/except as, :=, match
  captures, del) bind names in source order; only names an assignment
  really rebinds count, not the base of an attribute or subscript
  target. Names are resolved in evaluation order (a call or binding
  takes effect where it ends, so setup = setup(...) calls first, a for
  loop binds before its body, and each with item binds before the next
  runs), and setup counts only when bound to one from a packaging module
  (setuptools, distutils.core, numpy.distutils.core or skbuild), under
  any alias or module path. Rebinding a name also drops the dotted paths
  recorded beneath it, so after import helper as distutils,
  distutils.core.setup() does not count. A local def setup, a setup from
  another module, a star import from elsewhere, helper.setup() or an
  unbound setup() does not count. A def or class header (decorators,
  defaults, bases) runs where it is defined, so a setup() there counts
  at that position. Annotations do not count: they are deferred under
  from __future__ import annotations, lazy from Python 3.14, and never
  evaluated for local variables. Control flow is followed: if, loop, try
  and match branches each start from the same state and merge where they
  meet, so a binding on a path that may not run (an untaken if, a loop
  body, an except handler) leaves a name ambiguous rather than replacing
  it. A call counts only when every path that binds the name binds it to
  a packaging setup, ignoring paths where it is unbound, so try/except
  ImportError fallbacks keep working. A call in a loop must hold on
  every pass. A block stops at return, raise, break or continue, so code
  after one never supplies the name, and del leaves a name unbound
  rather than rebinding it. A call on a path that may not run (an if
  branch, an except handler, a match case, a loop or comprehension body,
  a later and/or operand, a branch of a conditional expression) is only
  a candidate: a call that certainly runs wins, so a dead branch cannot
  supply the name ahead of the real call. In the function-body fallback,
  a function the file calls ranks above one it never does. Module-level
  calls win; function and class bodies, which may never run, count only
  when module level calls no bare setup() (e.g. setup() inside a main()
  the file calls). Each body is then scanned as its own scope, starting
  from the bindings it inherits (the module's final ones, an enclosing
  function's, but not a class body's for its methods) with its own
  parameters bound locally, so a name bound in one function never leaks
  into another. As in Python, every name a function binds anywhere in
  its body (except names declared global or nonlocal), including a
  simple x: T with no value, is local from the start, so calling it
  before it is bound reaches nothing. Comprehensions are scopes too: a
  call in one sees its loop targets and any earlier := in it, while the
  targets never leak out; a := inside a lambda stays in the lambda. A
  non-literal such as name=NAME, or a file with no such call, yields no
  name instead of a wrong one.

tomllib needs Python 3.11+, and runners such as ubuntu-22.04 ship
3.10, so when python3 is missing, too old, or cannot parse the file,
an awk match scoped to the same tables (or to a whole-word name= in
setup.py) stands in.

Both steps apply the setup.cfg step's PEP 508 charset check to the whole
string. The parsers check before printing, because command substitution
drops NUL bytes: "foo\u0000bar" in TOML, or "foo\x00bar" in setup.py,
would otherwise reach the shell check as "foobar" and pass. The awk
fallback skips files holding a raw NUL byte, which neither format
allows, since mawk and gawk pass it through to the same effect. The
setup.cfg step gains the same raw NUL guard, which it lacked, and now
also matches the whole string and logs a rejected value with %q, so all
three sources are checked alike. Rejected values are logged with repr()
or %q, so they cannot start a workflow command.

Add a test job per parser mode: tomllib on the runner, a real Python
3.10 without tomllib, and an image with no python3, both images pinned
by digest; a guard step fails the job if the image does not provide its
mode. Each job runs every fixture in turn and a final step checks all
four outputs of each, or that the action failed without a name,
reporting every failure. Fixtures cover each case from the issue,
Poetry-only and [project]-over-Poetry files, aliased setup imports,
module-qualified and unrelated setup() calls, shadowed setup imports in
either order, setup() in function bodies, a local def setup, a star
import from elsewhere, an unbound setup(), a rebound packaging module
root, imports in an unrelated function and a class body, attribute
assignments, a shadowing parameter, a for loop rebinding setup, a
comprehension variable, a comprehension target shadowing setup, a match
capture rebinding setup, a setup() call in a default value, a default
that runs before its def rebinds setup, a walrus in a comprehension
condition, a non-string [project] name with a Poetry name, a setup()
call in a deferred annotation, a with item binding before the next, a
setup.cfg holding a raw NUL, del setup, a walrus inside a lambda in a
comprehension, a call before a local assignment, a local annotation
without a value, a packaging import in a dead branch, a try/except
ImportError fallback, a loop rebinding setup after the call, a dead call
before the real call, an uncalled function before main, a conditional
del before the real call, a call after return, a short-circuited call,
and NUL names as escapes and raw bytes. The import-blind awk fallback is
not asserted on fixtures that need import resolution.

Closes: #169

Co-authored-by: Claude <noreply@anthropic.com>
Signed-off-by: Matthew Watkins <mwatkins@linuxfoundation.org>
@tykeal
tykeal merged commit b6e30d8 into main Oct 2, 2026
16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: Name regexes miss valid quoting and spacing

3 participants