diff --git a/CHANGELOG.md b/CHANGELOG.md index 8aadd575..88879826 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ Covers `bits`, `lcg.bits` (recipes), and `bits-recipe-tools`. Entries tagged **[ --- # Unreleased +- **[Improvement]** Generated recipes can provide an in-process `generate` callable, with a visible warning and legacy `command` fallback on failure. Existing command-only generators are unchanged; generated text differences can rehash the generator's packages once. # 0.8.0 — 2026-12-02 - **[Fix]** `bits build --dry-run` (and the prefetch planner): a package already installed is shown as installed even when its cached tarball has been pruned from `sw/TARS`; the plan recognises the install tree by its `.build-hash`, as the build itself does before it looks for a tarball, instead of planning a needless rebuild. diff --git a/bits_helpers/recipe.py b/bits_helpers/recipe.py index c3644e02..31049099 100644 --- a/bits_helpers/recipe.py +++ b/bits_helpers/recipe.py @@ -21,7 +21,7 @@ from bits_helpers.cmd import getoutput from bits_helpers.git import git -from bits_helpers.log import dieOnError +from bits_helpers.log import dieOnError, warning from bits_helpers.paths import RECIPE_SUBDIR, checkForFilename, getConfigPaths, resolveFilename class SpecError(Exception): @@ -59,10 +59,25 @@ def getRecipeReader(url: str, dist=None, genPackages={}, repo_dir=None): # Generate a recipe of package class GeneratedPackage: def __init__(self, obj) -> None: - self.command = obj["command"] self.url = obj["url"] + self.generate = obj.get("generate") + self.command = obj.get("command") + if self.generate is None and self.command is None: + raise ValueError("Generated package %s needs 'generate' or 'command'" % self.url) def __call__(self): - return getoutput(self.command).strip() + if self.generate is not None: + try: + recipe = self.generate() + if not isinstance(recipe, str): + raise TypeError("generated recipe %s: callable must return a string, got %s" % + (self.url, type(recipe).__name__)) + return recipe.strip() + except Exception as exc: + if self.command is None: + raise + warning("generated recipe %s: callable failed (%s); falling back to command", + self.url, exc) + return getoutput(self.command).strip() # Read a recipe from a file class FileReader: diff --git a/docs/REFERENCE.md b/docs/REFERENCE.md index 367eb957..d9cbc9e7 100644 --- a/docs/REFERENCE.md +++ b/docs/REFERENCE.md @@ -546,6 +546,19 @@ A recipe is a file named after its package in lower case (`.sh`, e.g. ` 1. A **YAML header** — package metadata, dependencies, and environment. 2. A **Bash build script** — the actual build steps. +Generated packages declared by a repository's `packages.py` may provide a +`generate` callable that returns the complete recipe as a string. This runs in +the bits process, avoiding a subprocess for each generated recipe. Existing +`command` generators keep working. If both are present, bits tries `generate` +first and warns before falling back to `command` if it raises or returns a +non-string value. A callable should avoid side effects: if it fails after +changing state, the fallback command runs with those changes still in place. + +The generated recipe text is an input to the package hash. Adopting `generate` +changes a package's hash and causes one rebuild if its returned text differs +from the command's output after recipe hash normalization (which ignores blank +lines and full-line comments). This affects only packages from that generator. + ### Minimal recipe ```yaml diff --git a/tests/test_parseRecipe.py b/tests/test_parseRecipe.py index f7ef0f70..6bd34900 100644 --- a/tests/test_parseRecipe.py +++ b/tests/test_parseRecipe.py @@ -3,9 +3,10 @@ import unittest import platform +from unittest.mock import ANY, patch from bits_helpers.defaults import parseDefaults from bits_helpers.recipe import parseRecipe, getRecipeReader -from bits_helpers.recipe import FileReader, GitReader +from bits_helpers.recipe import FileReader, GitReader, GeneratedPackage from bits_helpers.defaults import validateDefaults, incompatibleFlavorDefaults from bits_helpers.recipe import SpecError from collections import OrderedDict @@ -72,6 +73,47 @@ def __call__(self): else: return self.buffer +class TestGeneratedPackage(unittest.TestCase): + def test_callable_only(self): + reader = GeneratedPackage({"url": "generate:foo@1", "generate": lambda: " recipe \n"}) + with patch("bits_helpers.recipe.getoutput") as command: + self.assertEqual(reader(), "recipe") + command.assert_not_called() + + def test_callable_failure_falls_back_with_warning(self): + def broken(): + raise ValueError("bad generator") + reader = GeneratedPackage({"url": "generate:foo@1", "generate": broken, "command": "legacy"}) + with patch("bits_helpers.recipe.getoutput", return_value=" legacy recipe \n") as command, \ + patch("bits_helpers.recipe.warning") as warning: + self.assertEqual(reader(), "legacy recipe") + command.assert_called_once_with("legacy") + warning.assert_called_once_with( + "generated recipe %s: callable failed (%s); falling back to command", + "generate:foo@1", ANY) + + def test_callable_failure_without_command_raises(self): + def broken(): + raise ValueError("bad generator") + reader = GeneratedPackage({"url": "generate:foo@1", "generate": broken}) + with self.assertRaisesRegex(ValueError, "bad generator"): + reader() + + def test_command_only(self): + reader = GeneratedPackage({"url": "generate:foo@1", "command": "legacy"}) + with patch("bits_helpers.recipe.getoutput", return_value=" legacy recipe \n") as command: + self.assertEqual(reader(), "legacy recipe") + command.assert_called_once_with("legacy") + + def test_missing_generator_names_package(self): + with self.assertRaisesRegex(ValueError, "generate:foo@1"): + GeneratedPackage({"url": "generate:foo@1"}) + + def test_callable_non_string_names_package(self): + reader = GeneratedPackage({"url": "generate:foo@1", "generate": lambda: None}) + with self.assertRaisesRegex(TypeError, "generate:foo@1.*string.*NoneType"): + reader() + class TestRecipes(unittest.TestCase): def test_recipes(self) -> None: err, meta, body = parseRecipe(BufferReader("test1.sh", TEST1))