diff --git a/REUSE.toml b/REUSE.toml
index b85a94c3..0c7e2a08 100644
--- a/REUSE.toml
+++ b/REUSE.toml
@@ -16,6 +16,7 @@ path = [
"examples/package/rpm/hello.source/rpm/packaging.json",
"tine.lock.json",
"git/fixture/**",
+ "project/fixture/**",
"tools/starlark-fmt.json",
]
SPDX-FileCopyrightText = "Amutable GmbH "
diff --git a/docs/design/architecture.md b/docs/design/architecture.md
index c86b3ae5..16f5371b 100644
--- a/docs/design/architecture.md
+++ b/docs/design/architecture.md
@@ -252,6 +252,34 @@ tine exports the pinned binary's path as `BUCK2_BINARY`. A tool running under a
`tine` wrapper, but directly calls the exported binary (`util.buck2_argv()`), inherits the current
mounts, and runs against the shared configuration the invoking command already wrote.
+### Project source trees
+
+A directory source cannot include a subdirectory that has a `BUCK` file of its own:
+
+ Directory `` of package `tine//project/fixture` may not cover any subpackages, but includes subpackage `sub`.
+
+`project.source_tree()` collects the files of a project the way `prelude/utils/source_listing_impl.bzl`
+does. `project.source_listing()` declares a `source_tree_listing` target in every `BUCK` file. The target
+lists the files of its package and depends on the `source_tree_listing` target of each direct subpackage.
+A build of the tree gets the project path of its package, with the listed files as hidden inputs, and
+reads the directory in place. A copy would get new timestamps whenever an edit makes Buck copy the tree
+again, and a dev build would then recompile everything after every edit.
+
+The list leaves out a few files that the build still sees:
+
+- `glob()` matches a name that starts with a dot only with a pattern component such as `.*`. The listing
+ has patterns for up to four such names in a path relative to the `BUCK` file, and leaves out a file with
+ more.
+- A cell that tine adds below the project root has its own packages, and the listing does not include
+ them.
+- The listing of the root package leaves out `.buckconfig.local`. tine writes the mounts and the address of
+ the cache into it, and as an input it would give a build different cache keys on different machines.
+
+A build of a tree at the project root sees an empty `buck-out`. The sandbox puts the upper and work
+directories of the overlay of the tree in the scratch directory of the action, which is in `buck-out`.
+overlayfs fails a lookup of them through the overlay with `ELOOP`. `source_overlay()` in `rootfs.py`
+therefore mounts a tmpfs over `buck-out` in the overlay.
+
### Component model
The package model separates identity and policy from the exact inputs used by an action:
diff --git a/docs/user/rpm.md b/docs/user/rpm.md
index a211fa19..c27af511 100644
--- a/docs/user/rpm.md
+++ b/docs/user/rpm.md
@@ -31,6 +31,75 @@ rpm.package(
`package` is the `Name:` of the spec, and `subpackages` lists the binary packages that the build produces.
Each subpackage is a sub-target, such as `:hello[hello]`.
+## Building a project from its own checkout
+
+An upstream project, such as systemd, can build RPMs of itself from the checkout that contains its `BUCK`
+files. If your project has no `BUCK` file in a subdirectory, pass the directory of the root `BUCK` file as
+`source_tree`:
+
+```starlark
+load("@tine//package_system/rpm:defs.bzl", "rpm")
+
+rpm.package(
+ name = "systemd.rpm",
+ package = "systemd",
+ spec = "systemd.spec",
+ source_tree = ".",
+ buildroot = "catalog//:fedora.rawhide.buildroot",
+ release = "1",
+ source_date_epoch = 1744207869,
+ subpackages = [],
+)
+```
+
+Buck rejects `.` as soon as a subdirectory contains a `BUCK` file, because a directory source cannot include
+another Buck package. In that case, declare the tree with `project.source_tree()` in the root `BUCK` file and
+pass its label instead:
+
+```starlark
+load("@tine//package_system/rpm:defs.bzl", "rpm")
+load("@tine//project:defs.bzl", "project")
+
+project.source_tree(name = "source")
+
+rpm.package(
+ name = "systemd.rpm",
+ package = "systemd",
+ spec = "systemd.spec",
+ source_tree = ":source",
+ buildroot = "catalog//:fedora.rawhide.buildroot",
+ release = "1",
+ source_date_epoch = 1744207869,
+ subpackages = [],
+)
+```
+
+`project.source_tree()` lists the files of its own directory. It cannot list the files below another `BUCK`
+file, so every other `BUCK` file in the project lists its own files with `project.source_listing()`:
+
+```starlark
+load("@tine//project:defs.bzl", "project")
+
+project.source_listing()
+```
+
+If a `BUCK` file lacks the call, the build fails with an ``Unknown target `source_tree_listing` `` error that
+names the directory of that `BUCK` file.
+
+The build reads the tree as it is on disk, like a local checkout; see [Building from a local checkout
+instead](git.md#building-from-a-local-checkout-instead) for which files are inputs. `tine buck build
+--show-output :source` prints the path of a file that lists the inputs. [Project source
+trees](../design/architecture.md#project-source-trees) describes the few files that the list leaves out.
+
+A dev build keeps its build directory between builds, and an edit recompiles only what it changes. Pass
+`dev = True` to `rpm.package()` for a dev build, or list the directory of the `BUCK` file that declares the
+tree under `[tine] dev`, with `.` for the project root:
+
+```toml
+[buckconfig.tine]
+dev = "."
+```
+
## Build dependencies
The build installs the BuildRequires of the spec over the shared base buildroot. `build_requires` lists
diff --git a/git/defs.bzl b/git/defs.bzl
index 8edc6eeb..7bde0706 100644
--- a/git/defs.bzl
+++ b/git/defs.bzl
@@ -5,6 +5,7 @@
load("@prelude//:rules.bzl", "git_fetch")
load("//project:defs.bzl", "project")
+load("//project:source.bzl", "SourceTreeInfo")
_MOUNT_TARGET_LABEL = "tine:mount-target"
@@ -21,6 +22,7 @@ def _checkout_impl(ctx: AnalysisContext) -> list[Provider]:
default_output = tree,
sub_targets = {path: [DefaultInfo(default_output = tree.project(path))] for path in ctx.attrs.sub_targets},
),
+ SourceTreeInfo(dev = False, path = tree, sources = None),
]
_checkout = rule(
diff --git a/package/build.bzl b/package/build.bzl
index 8408778c..fc87ce9d 100644
--- a/package/build.bzl
+++ b/package/build.bzl
@@ -7,6 +7,7 @@ load("//:specs.bzl", "specs")
load("//box:defs.bzl", "box")
load("//git:defs.bzl", "git")
load("//project:defs.bzl", "project")
+load("//project:source.bzl", "SourceTreeInfo")
load(":buildroot.bzl", "BuildrootInfo")
load(":manager.bzl", "PackageManagerInfo")
load(":repository.bzl", "LocalPackageInfo")
@@ -29,8 +30,10 @@ PACKAGE_BUILD_ATTRS = {
default = [],
doc = "our packages that the solves of the BuildRequires prefer over upstream ones",
),
- "configured_dev": attrs.bool(
- doc = "whether project configuration selects this package for dev mode",
+ "configured_dev": attrs.option(
+ attrs.bool(),
+ default = None,
+ doc = "whether `dev` or `[tine] dev` selects dev mode for this package, or None when neither does",
),
"in_place_packaging": attrs.option(
attrs.string(),
@@ -48,7 +51,8 @@ PACKAGE_BUILD_ATTRS = {
doc = "the SOURCE_DATE_EPOCH of the build, or None to take it from the package's changelog where the recipe has one",
),
"source_tree": attrs.option(
- attrs.source(allow_directory = True),
+ # A label names a `project.source_tree()` or a checkout, and a directory of the package coerces as a source.
+ attrs.one_of(attrs.dep(providers = [SourceTreeInfo]), attrs.source(allow_directory = True)),
default = None,
doc = "a prepared tree built in place of the declared sources",
),
@@ -147,12 +151,13 @@ def package_build_source(
in_place_recipe_value: str | None,
in_place_packaging: str | None,
in_place_packaging_distro: str | Select | None,
-) -> (str | None, bool):
+) -> (str | None, bool | None):
"""Check the in-place arguments of a package-build macro, and return its source tree and dev mode.
- `in_place_recipe` names the macro's argument for a recipe in the source tree, and
- `in_place_recipe_value` is its value. Without `source_tree`, the macro builds the checkout slot
- `.source` once the slot contains files. `owner` starts a failure message.
+ The dev mode is None when neither `dev` nor `[tine] dev` selects it. `in_place_recipe` names the macro's
+ argument for a recipe in the source tree, and `in_place_recipe_value` is its value. Without `source_tree`,
+ the macro builds the checkout slot `.source` once the slot contains files. `owner` starts a failure
+ message.
"""
if in_place_packaging != None and in_place_recipe_value != None:
fail("{}: {} sets both in_place_packaging and {}".format(owner, name, in_place_recipe))
@@ -162,4 +167,6 @@ def package_build_source(
source = name + ".source"
populated = git.checkout(name = source)
source_tree = ":" + source if populated else None
- return source_tree, project.is_dev(name, source = source_tree, override = dev)
+ if dev == None and project.is_dev(name, source = source_tree):
+ dev = True
+ return source_tree, dev
diff --git a/package_system/rpm/build_test.py b/package_system/rpm/build_test.py
index 5ad1e950..3db8c3a8 100644
--- a/package_system/rpm/build_test.py
+++ b/package_system/rpm/build_test.py
@@ -56,6 +56,7 @@ def specification(
*,
build_dir: Path | None = None,
spec_file: Path | None = None,
+ in_place_spec: str | None = None,
subpackages: list[str] | None = None,
sources: list[Path] | None = None,
strict_subpackages: bool = True,
@@ -65,6 +66,7 @@ def specification(
build_dir=str(build_dir) if build_dir is not None else None,
lower=["buildroot"],
spec_file=str(spec_file or self.spec_file),
+ in_place_spec=in_place_spec,
sources=[str(source) for source in sources] if sources is not None else [str(self.auxiliary)],
dist=".test",
# rpm_package keeps the build directory of every dev build, and only of a dev build.
@@ -175,7 +177,7 @@ def test_in_place_spec_and_extras_come_from_the_source_tree(self) -> None:
local_spec.write_text("Name: from-checkout\nSource1: helper\n")
(packaging / "helper").write_text("checkout helper\n")
- specification = self.specification(source, spec_file=local_spec)
+ specification = self.specification(source, in_place_spec="packaging/fedora/local.spec")
def inspect(topdir: Path) -> None:
frozen = (topdir / "SPECS" / "local.spec").read_text()
@@ -201,6 +203,24 @@ def inspect(topdir: Path) -> None:
self.assertFalse((topdir / "SOURCES" / "auxiliary").exists())
self.assertEqual(local_spec.read_text(), "Name: from-checkout\nSource1: helper\n")
+ def test_a_declared_spec_in_the_source_tree_is_not_in_place(self) -> None:
+ # A source tree can be the project root, which also contains the declared spec. Without
+ # `in_place_spec`, the build must stage the declared spec and sources as for an archive build.
+ # Pass a source tree that contains the spec and check that rpmbuild takes the sources from
+ # SOURCES.
+ source = self.scratch / "checkout"
+ source.mkdir()
+ (source / "declared.spec").write_text("Name: declared\n")
+
+ command, cwd, _environment, topdir, _binds = self.invoke(
+ self.specification(source, spec_file=source / "declared.spec")
+ )
+
+ self.assertEqual(command[-1], "/build/SPECS/declared.spec")
+ self.assertFalse([argument for argument in command if argument.startswith("_sourcedir")])
+ self.assertEqual(cwd, Path("/build/CHECKOUT"))
+ self.assertEqual(sorted(path.name for path in (topdir / "SOURCES").iterdir()), ["auxiliary"])
+
def pinned_packaging(self) -> tuple[Path, Path]:
"""Return a checkout and a dist-git tree with a spec, a patch and a directory of tests."""
source = self.scratch / "checkout"
@@ -264,7 +284,7 @@ def test_imported_packaging_fails_on_a_subpackage_mismatch(self) -> None:
def test_spec_path_cannot_escape_the_source_tree(self) -> None:
source = self.scratch / "checkout"
source.mkdir()
- spec = self.specification(source, spec_file=source / ".." / self.spec_file.name)
+ spec = self.specification(source, in_place_spec="../" + self.spec_file.name)
with (
contextlib.chdir(self.project),
mock.patch.object(tempfile, "tempdir", str(self.scratch)),
@@ -276,9 +296,9 @@ def test_spec_path_cannot_escape_the_source_tree(self) -> None:
def test_missing_spec_has_a_useful_error(self) -> None:
source = self.scratch / "checkout"
source.mkdir()
- for spec_file in (source / "missing.spec", self.scratch / "missing.spec"):
- with self.subTest(spec_file=spec_file):
- spec = self.specification(source, spec_file=spec_file)
+ for in_place_spec, spec_file in (("missing.spec", None), (None, self.scratch / "missing.spec")):
+ with self.subTest(in_place_spec=in_place_spec, spec_file=spec_file):
+ spec = self.specification(source, spec_file=spec_file, in_place_spec=in_place_spec)
case = tempfile.mkdtemp(dir=self.scratch)
with (
contextlib.chdir(self.project),
@@ -425,7 +445,7 @@ def test_spec_symlink_cannot_escape_the_staged_checkout(self) -> None:
source = self.scratch / "checkout"
source.mkdir()
(source / "escape.spec").symlink_to(self.spec_file)
- spec = self.specification(source, spec_file=source / "escape.spec")
+ spec = self.specification(source, in_place_spec="escape.spec")
topdir = self.scratch / "topdir"
with (
contextlib.chdir(self.project),
diff --git a/package_system/rpm/buildrequires_test.py b/package_system/rpm/buildrequires_test.py
index f8108953..b66fd6cc 100644
--- a/package_system/rpm/buildrequires_test.py
+++ b/package_system/rpm/buildrequires_test.py
@@ -102,6 +102,7 @@ def specification(
self,
*,
spec_file: Path | None = None,
+ in_place_spec: str | None = None,
sources: list[Path] | None = None,
source_tree: Path | None = None,
rpmbuild_options: list[str] | None = None,
@@ -111,6 +112,7 @@ def specification(
return buildrequires.Spec(
lower=["buildroot"],
spec_file=str(spec_file or self.spec_file),
+ in_place_spec=in_place_spec,
sources=[str(source) for source in (sources if sources is not None else [self.extra])],
source_tree=str(source_tree) if source_tree is not None else None,
dist=".test",
@@ -168,7 +170,7 @@ def test_in_place_queries_define_the_debug_prefix_map(self) -> None:
)
)
found = buildrequires.query(
- self.specification(spec_file=checkout / "example.spec", sources=[], source_tree=checkout)
+ self.specification(in_place_spec="example.spec", sources=[], source_tree=checkout)
)
self.assertIn("flags-devel", found)
@@ -207,7 +209,7 @@ def test_only_an_in_place_build_defines_build_in_place(self) -> None:
self.assertIn(
"in-place-devel",
buildrequires.query(
- self.specification(spec_file=checkout / "example.spec", sources=[], source_tree=checkout)
+ self.specification(in_place_spec="example.spec", sources=[], source_tree=checkout)
),
)
@@ -239,7 +241,7 @@ def test_an_in_place_spec_parses_in_the_checkout_like_the_build(self) -> None:
(checkout / "rpm" / "example.spec").write_text(spec)
found = buildrequires.query(
- self.specification(spec_file=checkout / "rpm" / "example.spec", sources=[], source_tree=checkout)
+ self.specification(in_place_spec="rpm/example.spec", sources=[], source_tree=checkout)
)
self.assertIn("include-devel", found)
@@ -258,7 +260,7 @@ def test_parse_time_writes_do_not_modify_the_checkout(self) -> None:
(checkout / "example.spec").write_text(spec)
found = buildrequires.query(
- self.specification(spec_file=checkout / "example.spec", sources=[], source_tree=checkout)
+ self.specification(in_place_spec="example.spec", sources=[], source_tree=checkout)
)
self.assertIn("generated-devel", found)
@@ -325,7 +327,7 @@ def test_an_in_place_spec_needs_no_source_archive(self) -> None:
)
)
found = buildrequires.query(
- self.specification(spec_file=checkout / "example.spec", sources=[], source_tree=checkout)
+ self.specification(in_place_spec="example.spec", sources=[], source_tree=checkout)
)
self.assertIn("example-compiler", found)
diff --git a/package_system/rpm/rpmbuild.py b/package_system/rpm/rpmbuild.py
index 8a150d2b..a118f50f 100644
--- a/package_system/rpm/rpmbuild.py
+++ b/package_system/rpm/rpmbuild.py
@@ -26,6 +26,9 @@ class Parse(TypedDict):
"""The fields of a driver spec that select how rpm parses the RPM spec."""
spec_file: str
+ # `in_place_spec` is the path of the spec relative to the source tree, or None for a spec that the build
+ # doesn't read from the source tree.
+ in_place_spec: str | None
# `sources` lists the Source and Patch files, and directories whose top-level files are Source and Patch
# files.
sources: list[str]
@@ -85,12 +88,13 @@ def stage(topdir: Path, parse: Parse, source_tree: str | None) -> Staged:
# readonly_project() already created BUILD if it mounted the persistent build directory there.
(topdir / builder.BUILD).mkdir(exist_ok=True)
checkout = topdir / builder.CHECKOUT
- spec_file = Path(parse["spec_file"])
+ in_place_spec = parse["in_place_spec"] if source_tree is not None else None
+ spec_file = Path(in_place_spec if in_place_spec is not None else parse["spec_file"])
staged_spec = topdir / "SPECS" / spec_file.name
chroot_spec = builder.CHROOT_TOPDIR / "SPECS" / spec_file.name
- if source_tree is not None and spec_file.is_relative_to(source_tree):
- relative_spec = spec_file.relative_to(source_tree)
- if ".." in relative_spec.parts:
+ if in_place_spec is not None:
+ relative_spec = spec_file
+ if relative_spec.is_absolute() or ".." in relative_spec.parts:
util.fail(f"rpmbuild: RPM spec must stay within the source tree: {relative_spec}")
source_spec = checkout / relative_spec
# stage() reads the spec outside the chroot. Without the check, a spec symlink that points out of
diff --git a/package_system/rpm/rpmbuild_test.py b/package_system/rpm/rpmbuild_test.py
index ec459486..af3096b4 100644
--- a/package_system/rpm/rpmbuild_test.py
+++ b/package_system/rpm/rpmbuild_test.py
@@ -29,6 +29,7 @@ def setUp(self) -> None:
def stage(self, *, spec_file: Path | None = None, sources: list[Path] | None = None) -> rpmbuild.Staged:
parse = rpmbuild.Parse(
spec_file=str(spec_file or self.spec_file),
+ in_place_spec=None,
sources=[str(source) for source in (sources if sources is not None else [self.source])],
dist=".test",
source_date_epoch=1754006400,
diff --git a/package_system/rpm/rules.bzl b/package_system/rpm/rules.bzl
index eda6eb99..273736f4 100644
--- a/package_system/rpm/rules.bzl
+++ b/package_system/rpm/rules.bzl
@@ -11,6 +11,7 @@ load("//package:buildroot.bzl", "BuildrootInfo", "package_buildroot", "recipe_de
load("//package:packaging.bzl", "pinned_packaging")
load("//package:repository.bzl", "RepositoryPin", "declare_remote_repository")
load("//package:system.bzl", "PackageSystemInfo")
+load("//project:source.bzl", "SourceTreeInfo")
PACKAGE_SYSTEM = "@tine//package_system/rpm:package_system"
@@ -46,7 +47,7 @@ def _query_buildrequires(
actions: AnalysisActions,
query: RunInfo,
parse: dict[str, typing.Any],
- source_tree: Artifact | None,
+ source_tree: cmd_args | None,
lower: list[Artifact],
) -> Artifact:
"""Return a JSON list of the BuildRequires of the spec that `parse` describes and the layers `lower` lack."""
@@ -68,19 +69,35 @@ def _query_buildrequires(
def _rpm_package_impl(ctx: AnalysisContext) -> list[Provider]:
base_buildroot = ctx.attrs.buildroot[BuildrootInfo]
- source_tree = ctx.attrs.source_tree
- in_place_spec = ctx.attrs.in_place_spec if source_tree != None else None
+ tree = ctx.attrs.source_tree
+ if isinstance(tree, Dependency):
+ tree = tree[SourceTreeInfo]
+ elif tree != None:
+ tree = SourceTreeInfo(dev = False, path = tree, sources = None)
+
+ # The macro checks `[tine] dev` for the checkout path that the label of the tree names. A build of a
+ # `project.source_tree()` reads the directory of the package of the tree instead. The tree checks
+ # `[tine] dev` for that directory.
+ configured_dev = ctx.attrs.configured_dev
+ if configured_dev == None:
+ configured_dev = tree != None and tree.dev
+ source_tree = specs.argument(tree.path) if tree != None else None
+ in_place_spec = ctx.attrs.in_place_spec if tree != None else None
spec_file = ctx.attrs.spec
- if source_tree != None and in_place_spec != None:
- spec_file = source_tree.project(in_place_spec)
+ if in_place_spec != None:
+ # The drivers read an in-place spec from the source tree through `in_place_spec`.
+ spec_file = in_place_spec
pinned = None
- if source_tree != None and ctx.attrs.in_place_packaging != None:
+ if tree != None and ctx.attrs.in_place_packaging != None:
+ pin = ctx.attrs.in_place_packaging
+ if tree.sources != None and pin not in tree.sources:
+ fail("rpm_package: the source tree contains no in_place_packaging file {}".format(repr(pin)))
pinned = pinned_packaging(
ctx,
base_buildroot,
"git-core",
ctx.attrs._packaging,
- source_tree.project(ctx.attrs.in_place_packaging),
+ tree.sources[pin] if tree.sources != None else tree.path.project(pin),
ctx.attrs.in_place_packaging_distro,
)
spec_file = pinned.project(ctx.attrs.package + ".spec")
@@ -95,9 +112,10 @@ def _rpm_package_impl(ctx: AnalysisContext) -> list[Provider]:
# The build and the BuildRequires query parse the spec with the same fields.
parse = {
"dist": ctx.attrs.dist,
- "in_place_rpmbuild_options": ctx.attrs.in_place_rpmbuild_options if source_tree != None else [],
+ "in_place_rpmbuild_options": ctx.attrs.in_place_rpmbuild_options if tree != None else [],
+ "in_place_spec": in_place_spec,
# package_build() keeps the build directory of a dev build, because rpm_package passes keep_build_dir.
- "incremental": ctx.attrs.configured_dev,
+ "incremental": configured_dev,
"release": ctx.attrs.release,
"rpmbuild_options": ctx.attrs.rpmbuild_options,
"source_date_epoch": ctx.attrs.source_date_epoch,
@@ -126,7 +144,7 @@ def _rpm_package_impl(ctx: AnalysisContext) -> list[Provider]:
package_system = ctx.attrs._package_system,
base = base_buildroot,
stack = stack,
- configured_dev = ctx.attrs.configured_dev,
+ configured_dev = configured_dev,
keep_build_dir = True,
packages = "rpms",
subpackages = ctx.attrs.subpackages,
diff --git a/project/defs.bzl b/project/defs.bzl
index a3c4c7d6..7a34c09a 100644
--- a/project/defs.bzl
+++ b/project/defs.bzl
@@ -3,6 +3,8 @@
"""Source directories, dev mode and build outputs of a project, exported as the `project` namespace."""
+load(":source.bzl", "all_files", "source_listing", "source_tree_rule")
+
_SECTION = "tine"
_DEV = "dev"
@@ -27,7 +29,7 @@ def _source_path(source: str) -> str:
elif path:
package = path
target = target.split("[", 1)[0].removesuffix(".git")
- return _project_path(package, target, cell = cell)
+ return _project_path(package, target, cell = cell) or "."
def is_dev(
name: str,
@@ -39,18 +41,24 @@ def is_dev(
if override != None:
return override
- configured = [entry.strip() for entry in read_root_config(_SECTION, _DEV, "").split(",")]
- project_path = _project_path(package_name(), name, cell = get_cell_name())
+ # An unset `[tine] dev` splits into one empty entry, and an empty entry would match an empty project path.
+ configured = [entry.strip() for entry in read_root_config(_SECTION, _DEV, "").split(",") if entry.strip()]
+ project_path = _project_path(package_name(), name, cell = get_cell_name()) or "."
if source == None:
return project_path in configured
return _source_path(source) in configured
def has_files(directory: str) -> bool:
"""Whether `directory` in this package contains a file that Buck does not ignore."""
+ return bool(all_files(directory))
+
+def source_tree(name: str, **kwargs) -> None:
+ """Declare `name` as the source tree of this package and of its subpackages, which a build reads in place.
- # A glob() pattern matches a file that starts with a dot, or a file in a directory that starts with
- # a dot, only if the pattern itself contains that dot.
- return bool(glob([directory + "/**", directory + "/**/.*", directory + "/**/.*/**"]))
+ The default output of `name` lists the files that the tree tracks as inputs.
+ """
+ directory = _project_path(package_name(), "", cell = get_cell_name()) or "."
+ source_tree_rule(name = name, dev = is_dev(""), directory = directory, listing = source_listing(), **kwargs)
def populated(directory: str) -> bool:
"""Whether `directory` in this package contains a file, or is mounted for dev mode."""
@@ -111,4 +119,6 @@ project = struct(
is_label = is_label,
kept_dir = kept_dir,
populated = populated,
+ source_listing = source_listing,
+ source_tree = source_tree,
)
diff --git a/project/fixture/.dotdir/.dotfile b/project/fixture/.dotdir/.dotfile
new file mode 100644
index 00000000..5a18cd2f
--- /dev/null
+++ b/project/fixture/.dotdir/.dotfile
@@ -0,0 +1 @@
+source
diff --git a/project/fixture/.dotdir/.inner/file b/project/fixture/.dotdir/.inner/file
new file mode 100644
index 00000000..5a18cd2f
--- /dev/null
+++ b/project/fixture/.dotdir/.inner/file
@@ -0,0 +1 @@
+source
diff --git a/project/fixture/.dotdir/file b/project/fixture/.dotdir/file
new file mode 100644
index 00000000..5a18cd2f
--- /dev/null
+++ b/project/fixture/.dotdir/file
@@ -0,0 +1 @@
+source
diff --git a/project/fixture/.dotfile b/project/fixture/.dotfile
new file mode 100644
index 00000000..5a18cd2f
--- /dev/null
+++ b/project/fixture/.dotfile
@@ -0,0 +1 @@
+source
diff --git a/project/fixture/BUCK b/project/fixture/BUCK
new file mode 100644
index 00000000..9e867b2c
--- /dev/null
+++ b/project/fixture/BUCK
@@ -0,0 +1,100 @@
+# SPDX-FileCopyrightText: Amutable GmbH
+# SPDX-License-Identifier: MPL-2.0
+
+"""A project tree with BUCK files in subdirectories, as one source tree."""
+
+load("//box:defs.bzl", "box")
+load("//package_system/rpm:defs.bzl", "rpm")
+load("//project:defs.bzl", "project")
+
+_DISTRO = "catalog//:fedora.rawhide.distribution"
+
+_FILES = """\
+.dotdir/.dotfile
+.dotdir/.inner/file
+.dotdir/file
+.dotfile
+BUCK
+file
+source-tree.spec
+sub/.dotdir/file
+sub/.dotfile
+sub/BUCK
+sub/deeper/nested/BUCK
+sub/deeper/nested/file
+sub/file
+sub/link
+sub/plain/file
+"""
+
+project.source_tree(name = "tree")
+
+# The tree must track every file of this package and of its subpackages: dotfiles, files below nested
+# dot directories, and the files of `sub/deeper/nested`, which is a subpackage of a subpackage.
+box.sh_test(
+ name = "source-tree-test",
+ distributed = False,
+ box = "tine//tools:dev.box",
+ script = """
+ diff -u - "$1" <<'FILES'
+{}FILES
+ """.format(_FILES),
+ args = ["$(location :tree)"],
+)
+
+# source-tree.spec copies the source tree into the package. `tree.rpm` is a regular build and `dev.rpm` a
+# dev build. `tree.rpm` and `dev.rpm` read this package directory in place.
+[
+ rpm.package(
+ name = name,
+ distro = _DISTRO,
+ package = "source-tree",
+ buildroot = "catalog//:fedora.rawhide.buildroot",
+ dev = dev,
+ in_place_spec = "source-tree.spec",
+ release = "1",
+ source_date_epoch = 1754006400,
+ source_tree = ":tree",
+ subpackages = ["source-tree"],
+ )
+ for name, dev in (
+ ("tree.rpm", None),
+ ("dev.rpm", True),
+ )
+]
+
+# `tree.rpm` and `dev.rpm` must contain every file of the tree, and `sub/link` must keep its target. A
+# git-ignored file in this directory, such as an editor backup, can add files to the packages, so the test
+# checks only for the expected ones. The build of `dev.rpm` must keep its build directory, which only a dev
+# build does.
+box.sh_test(
+ name = "source-tree-rpm-test",
+ distro = _DISTRO,
+ labels = ["image"],
+ box = "catalog//:fedora.rawhide.box",
+ script = """
+ [[ -d "$3" ]]
+ expected=$(LC_ALL=C sort <<'FILES'
+{}FILES
+ )
+ for package in "$1" "$2"; do
+ listing=$(
+ rpm -qp --queryformat '[%{{FILEMODES:perms}} %{{FILENAMES}}\\n]' "$package" |
+ sed -n 's|^[-l][^ ]* /usr/share/source-tree/||p' |
+ LC_ALL=C sort
+ )
+ missing=$(LC_ALL=C comm -23 <(printf '%s\\n' "$expected") <(printf '%s\\n' "$listing"))
+ if [[ -n "$missing" ]]; then
+ printf '%s lacks:\\n%s\\n' "$package" "$missing" >&2
+ exit 1
+ fi
+ rpm -qp --queryformat '[%{{FILENAMES}} %{{FILELINKTOS}}\\n]' "$package" |
+ grep -qx '/usr/share/source-tree/sub/link file'
+ done
+ """.format(_FILES),
+ args = [
+ "$(location :tree.rpm[source-tree])",
+ "$(location :dev.rpm[source-tree])",
+ "$(location :dev.rpm[build])",
+ ],
+)
diff --git a/project/fixture/file b/project/fixture/file
new file mode 100644
index 00000000..5a18cd2f
--- /dev/null
+++ b/project/fixture/file
@@ -0,0 +1 @@
+source
diff --git a/project/fixture/source-tree.spec b/project/fixture/source-tree.spec
new file mode 100644
index 00000000..0c0d1120
--- /dev/null
+++ b/project/fixture/source-tree.spec
@@ -0,0 +1,19 @@
+# SPDX-FileCopyrightText: Amutable GmbH
+# SPDX-License-Identifier: MPL-2.0
+
+Name: source-tree
+Version: 1
+Release: %autorelease
+Summary: Copy the source tree into the package
+License: MPL-2.0
+BuildArch: noarch
+
+%description
+An integration fixture for project.source_tree().
+
+%install
+mkdir -p %{buildroot}%{_datadir}/source-tree
+cp -a . %{buildroot}%{_datadir}/source-tree/
+
+%files
+%{_datadir}/source-tree
diff --git a/project/fixture/sub/.dotdir/file b/project/fixture/sub/.dotdir/file
new file mode 100644
index 00000000..5a18cd2f
--- /dev/null
+++ b/project/fixture/sub/.dotdir/file
@@ -0,0 +1 @@
+source
diff --git a/project/fixture/sub/.dotfile b/project/fixture/sub/.dotfile
new file mode 100644
index 00000000..5a18cd2f
--- /dev/null
+++ b/project/fixture/sub/.dotfile
@@ -0,0 +1 @@
+source
diff --git a/project/fixture/sub/BUCK b/project/fixture/sub/BUCK
new file mode 100644
index 00000000..ce26435d
--- /dev/null
+++ b/project/fixture/sub/BUCK
@@ -0,0 +1,6 @@
+# SPDX-FileCopyrightText: Amutable GmbH
+# SPDX-License-Identifier: MPL-2.0
+
+load("//project:defs.bzl", "project")
+
+project.source_listing()
diff --git a/project/fixture/sub/deeper/nested/BUCK b/project/fixture/sub/deeper/nested/BUCK
new file mode 100644
index 00000000..ce26435d
--- /dev/null
+++ b/project/fixture/sub/deeper/nested/BUCK
@@ -0,0 +1,6 @@
+# SPDX-FileCopyrightText: Amutable GmbH
+# SPDX-License-Identifier: MPL-2.0
+
+load("//project:defs.bzl", "project")
+
+project.source_listing()
diff --git a/project/fixture/sub/deeper/nested/file b/project/fixture/sub/deeper/nested/file
new file mode 100644
index 00000000..5a18cd2f
--- /dev/null
+++ b/project/fixture/sub/deeper/nested/file
@@ -0,0 +1 @@
+source
diff --git a/project/fixture/sub/file b/project/fixture/sub/file
new file mode 100644
index 00000000..5a18cd2f
--- /dev/null
+++ b/project/fixture/sub/file
@@ -0,0 +1 @@
+source
diff --git a/project/fixture/sub/link b/project/fixture/sub/link
new file mode 120000
index 00000000..1a010b1c
--- /dev/null
+++ b/project/fixture/sub/link
@@ -0,0 +1 @@
+file
\ No newline at end of file
diff --git a/project/fixture/sub/plain/file b/project/fixture/sub/plain/file
new file mode 100644
index 00000000..5a18cd2f
--- /dev/null
+++ b/project/fixture/sub/plain/file
@@ -0,0 +1 @@
+source
diff --git a/project/source.bzl b/project/source.bzl
new file mode 100644
index 00000000..3eee9dd9
--- /dev/null
+++ b/project/source.bzl
@@ -0,0 +1,99 @@
+# SPDX-FileCopyrightText: Amutable GmbH
+# SPDX-License-Identifier: MPL-2.0
+
+"""The source tree of a project that has BUCK files in subdirectories.
+
+A directory source cannot contain a subpackage, so each package lists its own files and collects the
+listings of its direct subpackages. The pattern follows `prelude/utils/source_listing_impl.bzl`.
+"""
+
+load("@prelude//utils:source_listing.bzl", "SourceListingInfo")
+
+# In a glob() pattern, `*` and `**` never match a name that starts with a dot. Only a pattern component
+# such as `.*` matches that name. A pattern therefore matches a path only if the path contains exactly as
+# many names that start with a dot as the pattern contains such components. all_files() uses two patterns
+# for each count from 1 to _DOT_NAMES: one for a path that ends in such a name, and one for the files
+# below it.
+_DOT_NAMES = 4
+
+# The prelude names its own source listings `source_listing`. A different name lets a package contain both.
+_LISTING = "source_tree_listing"
+
+def all_files(directory: str = "") -> list[str]:
+ """Return the files below `directory` in this package with at most _DOT_NAMES names in their path that start with a dot."""
+ prefix = directory + "/" if directory else ""
+ patterns = []
+ for count in range(_DOT_NAMES + 1):
+ pattern = "**" + "".join(["/.*" if index == 0 else "/**/.*" for index in range(count)])
+ patterns += [prefix + pattern] + ([prefix + pattern + "/**"] if count else [])
+ return glob(patterns)
+
+def _source_listing_impl(ctx: AnalysisContext) -> list[Provider]:
+ prefix = ctx.label.package + "/" if ctx.label.package else ""
+ sources = {}
+ for dep in ctx.attrs.deps:
+ subpackage = dep.label.package.removeprefix(prefix)
+ sources.update({subpackage + "/" + path: artifact for path, artifact in dep[SourceListingInfo].sources.items()})
+ for source in ctx.attrs.srcs:
+ sources[source.short_path] = source
+ return [DefaultInfo(), SourceListingInfo(sources = sources)]
+
+_source_listing = rule(
+ impl = _source_listing_impl,
+ attrs = {
+ "deps": attrs.list(attrs.dep(providers = [SourceListingInfo]), doc = "the listings of the direct subpackages"),
+ "srcs": attrs.list(attrs.source(), doc = "the files of the package"),
+ },
+)
+
+def source_listing() -> str:
+ """List the files of this package and of its subpackages as the target `:source_tree_listing`.
+
+ Every BUCK file below a `source_tree()` must call this. The listing of the parent package depends on the
+ listing of each subpackage, so a BUCK file without the call fails the build. Returns the label of the
+ listing.
+ """
+ prefix = package_name() + "/" if package_name() else ""
+
+ # tine writes the version of the project, its mounts and the address of the cache into
+ # `.buckconfig.local`. As an input, the file would give a build different cache keys on different
+ # machines.
+ srcs = [path for path in all_files() if path != ".buckconfig.local" or package_name()]
+ _source_listing(
+ name = _LISTING,
+ srcs = srcs,
+ deps = ["//{}{}:{}".format(prefix, subpackage, _LISTING) for subpackage in __internal__.sub_packages()],
+ visibility = ["PUBLIC"],
+ )
+ return ":" + _LISTING
+
+SourceTreeInfo = provider(
+ doc = "A source tree that a build reads in place.",
+ fields = {
+ # `dev` is True when `[tine] dev` lists the directory that a build of the tree reads.
+ "dev": provider_field(bool),
+ # `path` is the directory of a checkout, or the project path of a package directory with its listed files
+ # as hidden inputs.
+ "path": provider_field(Artifact | cmd_args),
+ # `sources` maps the path of each listed file in the tree to the file, or is None for a checkout.
+ "sources": provider_field(dict[str, Artifact] | None),
+ },
+)
+
+def _source_tree_impl(ctx: AnalysisContext) -> list[Provider]:
+ sources = ctx.attrs.listing[SourceListingInfo].sources
+ listing = ctx.actions.write(ctx.label.name + ".txt", "".join([path + "\n" for path in sorted(sources)]))
+
+ # A build reads the package directory in place. The listed files are hidden inputs, so that an edit to
+ # one of them reruns the build.
+ path = cmd_args(ctx.attrs.directory, hidden = sources.values())
+ return [DefaultInfo(default_output = listing), SourceTreeInfo(dev = ctx.attrs.dev, path = path, sources = sources)]
+
+source_tree_rule = rule(
+ impl = _source_tree_impl,
+ attrs = {
+ "dev": attrs.bool(doc = "whether `[tine] dev` lists the project path of the package"),
+ "directory": attrs.string(doc = "the project path of the package"),
+ "listing": attrs.dep(providers = [SourceListingInfo]),
+ },
+)
diff --git a/rootfs/rootfs.py b/rootfs/rootfs.py
index 45f8479a..0da8213c 100644
--- a/rootfs/rootfs.py
+++ b/rootfs/rootfs.py
@@ -229,9 +229,21 @@ def source_overlay(source: Path, target: Path) -> Generator[Path]:
# A `tine mount` covers a directory of the project, so directory submounts need overlays of their own.
# statmount() returns mount points with their symlinks resolved, so `source` needs them resolved too.
resolved = source.resolve()
+
+ # Buck creates the scratch directory of an action in its output directory in the project, and the
+ # sandbox mounts the scratch directory at /var/tmp. When `source` contains Buck's output directory, the
+ # upper and work directories below are in the lower directory as well. A lookup of them through the
+ # overlay then fails with ELOOP. The overlay shows an empty directory in place of Buck's output directory
+ # instead.
+ output = None
+ if scratch_path := os.environ.get("BUCK_SCRATCH_PATH"):
+ output = Path(Path(scratch_path).parts[0]).resolve()
+ if output == resolved or not output.is_relative_to(resolved):
+ output = None
layers = [(source, target)]
# overlayfs only takes directories as layers, so `target` shows the file that a file mount covers.
points = [Path(point) for point in submounts(str(resolved)) if Path(point).is_dir()]
+ points = [point for point in points if output is None or not point.is_relative_to(output)]
layers += [(point, target / point.relative_to(resolved)) for point in points]
with ExitStack() as stack:
scratch = Path(stack.enter_context(tempfile.TemporaryDirectory(prefix="source.")))
@@ -255,6 +267,8 @@ def source_overlay(source: Path, target: Path) -> Generator[Path]:
"has mounts declared with `tine mount`."
)
raise
+ if output is not None:
+ stack.enter_context(Tmpfs(target / output.relative_to(resolved))).mount()
yield target
diff --git a/rootfs/rootfs_test.py b/rootfs/rootfs_test.py
index 651a23ed..c0f0d11b 100644
--- a/rootfs/rootfs_test.py
+++ b/rootfs/rootfs_test.py
@@ -83,6 +83,29 @@ def test_preserves_the_tree_without_decoding_image_markers(self) -> None:
self.assertEqual(list(upper.iterdir()), [])
self.assertEqual(list(self.scratch.glob("source.*")), [])
+ def test_hides_the_buck_output_directory_that_contains_the_scratch_directory(self) -> None:
+ # When the source is the project root, it contains Buck's output directory, and the overlay's
+ # upper and work directories are in the scratch directory below it. Put the scratch directory
+ # in the project's buck-out, overlay the project, and check that the overlay shows an empty
+ # buck-out and that a walk of the whole overlay succeeds.
+ scratch_path = Path("buck-out/v2/tmp/action")
+ temporary = self.project / scratch_path / "var-tmp"
+ temporary.mkdir(parents=True)
+ (self.project / "buck-out/v2/output").write_text("output", encoding="utf-8")
+ with (
+ mock.patch.dict(os.environ, {"BUCK_SCRATCH_PATH": str(scratch_path), "TMPDIR": str(temporary)}),
+ chdir(self.project),
+ rootfs.source_overlay(Path("."), self.scratch / "target") as tree,
+ ):
+ self.assertEqual(list((tree / "buck-out").iterdir()), [])
+ self.assertEqual((tree / "input/data/file").read_text(encoding="utf-8"), "original")
+
+ # Path.walk() raises errors that rglob() would drop, such as ELOOP.
+ def fail(error: OSError) -> None:
+ raise error
+
+ self.assertTrue(list(tree.walk(on_error=fail)))
+
def test_shows_the_mounts_below_the_source_and_discards_writes_into_them(self) -> None:
# `tine mount` binds a checkout over a directory of the project, and rpmbuild builds the project
# in place.