diff --git a/project_validator/build_systems/make.py b/project_validator/build_systems/make.py index 0a5a24de..f7bdfe1c 100644 --- a/project_validator/build_systems/make.py +++ b/project_validator/build_systems/make.py @@ -152,7 +152,7 @@ def _expanded(text: str, lookup: _Lookup, inside: frozenset[str] = frozenset()) else: names.add(part.name) parts.append(_within(values, lookup, inside | {part.name})) - joined = [("".join(chosen), when) for chosen, when in combined(*parts)] + joined = [(_called("".join(chosen)), when) for chosen, when in combined(*parts)] # Each pass that substitutes guards more names, so expanding again ends. return joined if names == inside else _within(joined, lookup, frozenset(names)) @@ -168,6 +168,40 @@ def _within(values: Choices[str], lookup: _Lookup, inside: frozenset[str]) -> Ch return list(expanded)[:MOST_CHOICES] +# A call of one of make's text functions whose arguments hold no reference left: `$(filter %.c,a.c b.h)`. +_FUNCTION = re.compile(r"\$\((?Pfilter|filter-out|findstring|strip) (?P[^$()]*)\)") + + +def _called(text: str) -> str: + """`text` with each text function whose arguments are known replaced by its result, innermost first.""" + while (found := _FUNCTION.search(text)) is not None: + text = text[: found.start()] + _result(found["name"], found["arguments"]) + text[found.end() :] + return text + + +def _result(name: str, arguments: str) -> str: + """What `$(name arguments)` gives: `strip` collapses whitespace, `findstring` is its first argument when the + second holds it, `filter` and `filter-out` keep the words of the second that match (or do not) a pattern of the + first, where `%` matches any text.""" + if name == "strip": + return " ".join(arguments.split()) + first, _, second = arguments.partition(",") + if name == "findstring": + return first if first in second else "" + patterns = first.split() + return " ".join(word for word in second.split() if any(map(_matches(word), patterns)) == (name == "filter")) + + +def _matches(word: str) -> Callable[[str], bool]: + def matches(pattern: str) -> bool: + prefix, percent, suffix = pattern.partition("%") + if not percent: + return word == pattern + return len(word) >= len(prefix) + len(suffix) and word.startswith(prefix) and word.endswith(suffix) + + return matches + + def _choices(text: str, lookup: _Lookup) -> Choices[str]: """`text` expanded in each build (see `_expanded`); the builds that give the same text are one choice.""" merged: dict[str, Condition] = {} @@ -449,7 +483,9 @@ def _make_targets(command: Command, context: Context) -> Iterator[Expansion] | N goals = [word for word in words if "=" not in word] if (path := _makefile(context, directory, options)) is None: return _configured_by_cmake(command, context, directory, goals) - overrides = {found["name"]: found["value"] for word in words if (found := make_syntax.ASSIGNMENT.match(word))} + # The command line's assignments, and MAKECMDGOALS, the goals as written (none when it names none). + assigned = {found["name"]: found["value"] for word in words if (found := make_syntax.ASSIGNMENT.match(word))} + overrides = {"MAKECMDGOALS": " ".join(goals), **assigned} makefile = _read(context, path, overrides) goals = goals or ([makefile.default] if makefile.default else []) return _goals(makefile, path, goals, command) diff --git a/tests/test_expansion.py b/tests/test_expansion.py index 724c480d..336a1c90 100644 --- a/tests/test_expansion.py +++ b/tests/test_expansion.py @@ -337,6 +337,43 @@ def test_a_recipe_whose_program_is_unknown_is_reported_once_whatever_its_argumen recipes = [fact.subject for fact in facts.of(Unknown) if fact.subject.startswith("the recipe")] self.assertEqual(recipes, ["the recipe '$(TOOL) -g'"]) + def test_the_goals_make_is_given_decide_a_conditional_on_them(self) -> None: + """uutils/coreutils builds in release only for `make install`: MAKECMDGOALS holds the goals, and `filter` is + evaluated once its arguments are known.""" + makefile = ( + "ifneq (,$(filter install, $(MAKECMDGOALS)))\n PROFILE?=release\nendif\nPROFILE ?= debug\n" + "build:\n\tcargo build --profile=$(PROFILE)\ninstall:\n\tcargo install --profile=$(PROFILE)\n" + ) + for line, expected in ( + ("make build", [("cargo", "build", "--profile=debug")]), + ("make install", [("cargo", "install", "--profile=release")]), + ): + with self.subTest(line=line): + files = {"Makefile": makefile, **github_job("ubuntu-latest", line)} + self.assertEqual(_expanded(_facts(files)), expected) + + def test_text_functions_with_known_arguments_are_evaluated(self) -> None: + """One whose arguments are not all known (`$U` is set nowhere) stays as written.""" + recipes = ( + "$(filter %.c,$(A))", + "$(filter-out %.c,$(A))", + "$(findstring y,$(A)) [$(findstring q,$(A))]", + "[$(strip a b )]", + "$(filter %.c,$U)", + ) + makefile = "A = x.c y.h z.c\nall:\n" + "".join(f"\techo {recipe}\n" for recipe in recipes) + files = {"Makefile": makefile, **github_job("ubuntu-latest", "make")} + self.assertEqual( + _expanded(_facts(files)), + [ + ("echo", "x.c", "z.c"), + ("echo", "y.h"), + ("echo", "y", "[]"), + ("echo", "[a", "b]"), + ("echo", "$(filter %.c,$U)"), + ], + ) + def test_a_rule_written_in_a_branch_runs_only_where_it_holds(self) -> None: makefile = "all: test\nifeq ($(OS),Windows_NT)\nall: package\nendif\ntest:\n\tctest\npackage:\n\tcpack\n" for runner, expected in (("ubuntu-latest", [("ctest",)]), ("windows-latest", [("ctest",), ("cpack",)])):