diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 8f5fe6df3..493ccaf2d 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -37,5 +37,8 @@ The TOML config files in `defaultconfigs/` are loaded via `internal/projectconfi **IMPORTANT**: Code generation runs automatically with build/test commands. `mage generate` (runs `go generate` for each package in parallel) is a prerequisite for building and runs automatically with `mage build` and `mage unit`. `mage docs` rebuilds the binary and updates the JSON schema (`schemas/azldev.schema.json`) and CLI docs (`docs/user/reference/cli/`). Run `mage docs` explicitly after changing config structs or Cobra command descriptions so that checked-in generated files stay current (checked by PR gates). **CRITICAL**: Run `mage scenarioUpdate` when test expectations change (updates snapshots). +Schema changes affect both `TestSnapshots` and `TestSnapshotsContainer` baselines. +If Docker is unavailable, the update can refresh only local snapshots before failing; +check both baselines against the generated schema and report the incomplete container run. Follow conventional commit format for all changes AND PR titles. A github action will fail the PR if the title does not adhere to the format. diff --git a/.github/instructions/go.instructions.md b/.github/instructions/go.instructions.md index 439a7642a..7c0f3cb4f 100644 --- a/.github/instructions/go.instructions.md +++ b/.github/instructions/go.instructions.md @@ -105,6 +105,9 @@ description: "Instructions for working on the azldev Go codebase. IMPORTANT: Alw ## Component Fingerprinting — `fingerprint:"-"` Tags +New component fields must survive `ComponentConfig.WithAbsolutePaths` without aliasing +mutable data. Its automatic clone deliberately shares only config-file back-references. + Structs in `internal/projectconfig/` are hashed by `hashstructure.Hash()` to detect component changes. Fields **included by default** (safe: false positive > false negative). When adding a new field to a fingerprinted struct, ask: **"Does changing this field change the build output?"** diff --git a/docs/developer/README.md b/docs/developer/README.md index a628ce091..a1859a819 100644 --- a/docs/developer/README.md +++ b/docs/developer/README.md @@ -17,3 +17,4 @@ To get started developing `azldev`, review the [Getting Started guide](./how-to/ * [Build reference](./reference/build.md) * [Coding standards](./reference/coding-standards.md) * [Command guidelines](./reference/command-guidelines.md) +* [Go vendor packaging design](./reference/go-vendor-packaging-design.md) diff --git a/docs/developer/reference/go-vendor-packaging-design.md b/docs/developer/reference/go-vendor-packaging-design.md new file mode 100644 index 000000000..4906ef602 --- /dev/null +++ b/docs/developer/reference/go-vendor-packaging-design.md @@ -0,0 +1,48 @@ +# Go vendor packaging: artifact acquisition + +**Decision:** Regenerate the vendor archive from the prepared Go sources each +time. TOML describes the recipe; the prepared RPM `sources` manifest records the +digest of the resulting archive. azldev does not rewrite the published spec. + +## Use cases and schema + +* **Already vendored (Fedora containerd):** name the archive explicitly and + declare replacement when reusing an upstream manifest entry. +* **Unbundled Fedora Go application:** use a packaging overlay to consume the + vendor archive, remove obsolete build requirements, and install licenses. + A Rust application such as `rust-uutils` needs Cargo tooling instead. +* **Azure Linux local spec (for example, Telegraf):** the maintained spec can + reference a stable `filename = "vendor.tar.bz2"` directly. + +```toml +[[components.containerd.source-files]] +filename = "containerd-2.3.5-vendor.tar.bz2" +replace-upstream = true +replace-reason = "Regenerate the existing vendor source" +origin.type = "go-vendor" +# origin.config-file = "go-vendor-tools.toml" +``` + +The configured basename is the output identity; the spec does not supply it. +Optional generation inputs include declaration-relative native settings, the +module directory, and extra prep packages. + +## Acquisition contract + +Source preparation, builds, and source diffs generate the vendor archive after +overlays in isolated mock. An existing archive or `sources` entry does not skip +generation. An optional TOML `hash` (with `hash-type`) verifies the newly generated +bytes before publication; without it, azldev records the computed digest. +Routine render requires that digest in TOML and writes it to `sources` without +creating an archive or starting a vendor chroot. +To revendor, change the generation inputs and prepare again. An explicit +filename does not authorize replacing an unrelated source. + +## Trade-off + +Compared with automatic spec conversion, archive-only generation keeps +upstream build scripts, subpackages, dependencies, and license policy under +maintainer control. The cost is that the maintainer must ensure the spec +extracts and actually uses the archive offline. Generation may adapt a *private* +prep copy to avoid consuming the archive it is about to produce; it does not +publish those edits. See [Generate a Go vendor source archive](../../user/how-to/vendor-go-application.md). diff --git a/docs/user/how-to/vendor-go-application.md b/docs/user/how-to/vendor-go-application.md new file mode 100644 index 000000000..88643119c --- /dev/null +++ b/docs/user/how-to/vendor-go-application.md @@ -0,0 +1,103 @@ +# Generate a Go vendor source archive + +Use the `go-vendor` source origin to regenerate dependencies for an upstream or +local Go package. azldev generates a tarball; **it does not convert the published +spec**, remove dependency requirements, set offline build flags, change licensing, +or install bundled license files. Maintain that packaging in the spec or overlays. +Rust packages need Cargo vendoring, not this Go provider. + +## Already-vendored packaging + +```toml +[[components.containerd.source-files]] +filename = "containerd-2.3.5-vendor.tar.bz2" +origin.type = "go-vendor" +replace-upstream = true +replace-reason = "Regenerate the existing vendor source from patched inputs" +# For render, copy these values from the prepared archive's `sources` entry: +# hash-type = "SHA512" +# hash = "" +# Optional native settings, relative to this TOML: +# origin.config-file = "vendor-tools.toml" +``` + +The output basename must be declared in TOML, never inferred from an upstream +Source. The spec must reference that name to consume the archive. During private +prep azldev can omit a single unconditional `tar -xf %{S:N}` (or +`tar -xf %{SOURCEN}`) and its matching Source. Ambiguous layouts require a prep +overlay. Replacing an upstream manifest entry requires explicit replacement intent. +Upstream lookaside fetching may still download the old vendor payload before +regeneration; private prep never consumes it. + +## New or downstream-owned packaging + +```toml +[[components.example.source-files]] +filename = "vendor.tar.bz2" +origin.type = "go-vendor" +origin.module-dir = "cmd/example" # optional; relative to the final prep directory +origin.prep-packages = ["patch"] # optional tools needed by prep +``` + +`filename` is required for every vendor archive. +Use a stable name in the maintained spec. An explicit filename colliding with an +upstream `sources` entry follows the existing `replace-upstream`/`replace-reason` +rules; no implicit replacement of arbitrary explicit targets is allowed. +Only one generated Go vendor archive per component is supported. + +The spec must extract the archive into the same module directory, build with +`GOFLAGS=-mod=vendor`, and prevent downloads (`GOPROXY=off`, `GOSUMDB=off`, +`GOTOOLCHAIN=local`). Retain necessary cgo/native dependencies. Review/install +bundled licenses and maintain bundled dependency Provides as required by policy. +Generation alone does not establish an offline or correctly licensed RPM. + +## Settings, hashes, and workflow + +Native settings stay in a separate file: + +```toml +# go-vendor-tools.toml +[archive] +use_module_proxy = true +``` + +An explicit file replaces native settings, including when empty; missing/invalid +files fail. Without one, azldev reuses the sidecar referenced by +`%go_vendor_license_* -c %{S:N}`, then `go-vendor-tools.toml` when present, otherwise +tool defaults. The selected file's contents affect fingerprints independently of +checkout paths. Native `general.go_mod_dir` is honored; a conflicting component +origin `module-dir` fails. Hooks execute inside the generation chroot with +`GVT_CWD` pointing at staged dist-git. Treat settings and hooks as trusted build code. + +For initial preparation, omit `hash`: azldev computes and records the generated +digest in `sources` (SHA-512 by default, or configured `hash-type`). +A configured hash is an expected result and must match **before** publication. +Without one, checksums identify each output but do not detect unexpected changes +between regenerations. Generation is not cached by archive name or configured hash. + +```sh +azldev component prepare-sources -p example -o prepared --without-git +# Copy the vendor digest and algorithm from prepared/sources into the +# component's source-files entry as hash and hash-type before rendering. +azldev component diff-sources -p example +azldev component render -p example +``` + +The project distro needs a working mock configuration with `go-vendor-tools`, +Go, RPM macros/build tools, rpmautospec, and git. Generation fetches the sources, +applies overlays, and runs a **private** `%prep` with the selected vendor Source +and its extraction removed. This avoids consuming the artifact being regenerated. +Upstream history is retained privately for rpmautospec, even with `--without-git`. +The original published spec and native config remain untouched by the generator. + +Generation occurs after overlays, even with `--skip-sources` or `--skip-overlays`; +the latter still skips overlays themselves. Module/source patches therefore feed +generation. Do not patch the old vendor archive using archive overlays: use native +dependency overrides/hooks instead. Ensure prep does not apply the same module +patch twice when rebuilding with the regenerated module files. + +Source diffs regenerate the archive. Render instead requires the TOML pin and +writes it under the configured filename without downloading or generating vendor inputs. Render +does not verify archive bytes; preparation and builds do. Validate upgrades with source diffs, +license review, and an offline RPM build; supported syntax does not guarantee +arbitrary upstream packaging will continue to work. diff --git a/docs/user/reference/cli/azldev_component_render.md b/docs/user/reference/cli/azldev_component_render.md index c7beff797..95f24f8df 100644 --- a/docs/user/reference/cli/azldev_component_render.md +++ b/docs/user/reference/cli/azldev_component_render.md @@ -16,9 +16,9 @@ Within the output directory, components are organized into letter-prefixed subdirectories based on the first character of their name (e.g., specs/c/curl, specs/v/vim). -Unlike prepare-sources, render skips downloading source tarballs from the -lookaside cache — only spec files, patches, scripts, and other git-tracked -sidecar files are included. Multiple components can be rendered at once. +Render normally skips lookaside archives, retaining specs and git-tracked sidecars. +Go vendor sources are rendered from their configured digests without generating +the archive. Multiple components can be rendered at once. When rendering all components (-a), the --clean-stale flag prunes orphan rendered-spec directories (per-component dirs that no longer correspond to diff --git a/docs/user/reference/config/components.md b/docs/user/reference/config/components.md index ce06e6f60..2f44a8876 100644 --- a/docs/user/reference/config/components.md +++ b/docs/user/reference/config/components.md @@ -379,8 +379,8 @@ The `[[components..source-files]]` array defines additional source files t | Field | TOML Key | Type | Required | Description | |-------|----------|------|----------|-------------| -| Filename | `filename` | string | **Yes** | Name of the file in the sources directory | -| Hash | `hash` | string | Conditional | Expected hash. Required unless `--allow-no-hashes` is passed to `prep-sources` (which computes and prints the hash). | +| Filename | `filename` | string | **Yes** | Plain basename of the file in the sources directory. | +| Hash | `hash` | string | Conditional | Expected hash. Optional for `go-vendor`; otherwise required unless `--allow-no-hashes` is passed to `prep-sources`. | | Hash type | `hash-type` | string | Conditional | Hash algorithm (`"SHA256"`, `"SHA512"`). Required with `hash`; defaults to `"SHA512"` when auto-computed. | | Origin | `origin` | [Origin](#origin) | **Yes** | How to obtain the file | | Replace upstream | `replace-upstream` | bool | No | Replace the same-named entry in the upstream `sources` file. The upstream entry must exist. Requires `replace-reason`. | @@ -388,7 +388,37 @@ The `[[components..source-files]]` array defines additional source files t ### Origin -Three origin types are supported. +Four origin types are supported. + +#### `"go-vendor"` — generate a Go dependency archive + +```toml +[[components.containerd.source-files]] +filename = "containerd-2.3.5-vendor.tar.bz2" +replace-upstream = true +replace-reason = "Regenerate the existing vendor source" +origin.type = "go-vendor" +hash-type = "SHA512" +hash = "" +``` + +This origin generates only a tarball; it never converts the published spec. +See [Generate a Go vendor source archive](../../how-to/vendor-go-application.md). + +| Key | Default | Meaning | +|-----|---------|---------| +| `filename` | Required | Plain output basename; not inferred from the spec. | +| `hash` | Compute on initial preparation | Required for render. Preparation/build verify the generated archive if pinned; a mismatch fails before publication. | +| `hash-type` | `SHA512` | Output digest algorithm (`SHA256` or `SHA512`). | +| `origin.config-file` | Reuse upstream sidecar/tool defaults | Native TOML relative to the declaring file; replaces settings rather than merging, and is fingerprinted by content. | +| `origin.module-dir` | Final `%prep` directory | Relative module directory; native `general.go_mod_dir` must not conflict. | +| `origin.prep-packages` | `[]` | Additional generation-chroot RPM prerequisites. | + +One Go vendor source is supported per component. Existing upstream manifest +entries require `replace-upstream` and `replace-reason`. Generation runs +after overlays during prepare, build, and diff. Render writes the configured +`hash-type` and `hash` to `sources` without downloading or generating the archive. +Maintainers own extraction, offline build settings, and licensing in the spec. #### `"download"` — fetch from a URI diff --git a/internal/app/azldev/agentskill/agentskill_test.go b/internal/app/azldev/agentskill/agentskill_test.go index e53c985a8..1211b0025 100644 --- a/internal/app/azldev/agentskill/agentskill_test.go +++ b/internal/app/azldev/agentskill/agentskill_test.go @@ -185,6 +185,16 @@ func TestComponentTomlSkillDocumentsRPMDevBumpspecPreview(t *testing.T) { assert.Contains(t, doc, "no bumpspec runtime discovery occurs") } +func TestComponentSkillDocumentsVendorSource(t *testing.T) { + for _, mode := range []bool{false, true} { + doc, err := agentskill.NewCatalog(mode).SkillDocument("azldev-comp-toml", testParams()) + require.NoError(t, err) + assert.Contains(t, doc, `origin.type = "go-vendor"`) + assert.Contains(t, doc, "never converts the spec") + assert.Contains(t, doc, "render writes the pin without generation") + } +} + func TestImageSkillDocumentsSKUGroupGuidance(t *testing.T) { doc, err := agentskill.SkillDocument("azldev-image", testParams()) require.NoError(t, err) diff --git a/internal/app/azldev/agentskill/content/comp-toml.md.tmpl b/internal/app/azldev/agentskill/content/comp-toml.md.tmpl index 0def4bf59..3315a0adf 100644 --- a/internal/app/azldev/agentskill/content/comp-toml.md.tmpl +++ b/internal/app/azldev/agentskill/content/comp-toml.md.tmpl @@ -35,6 +35,15 @@ Add sub-tables only for what you change. The fields you will reach for most: ## Spec source +For generated Go dependencies, add a `source-files` entry with +`origin.type = "go-vendor"`. This generates only a tarball, never converts the spec. +Set `filename` explicitly and reference that basename in the effective spec for +packaging. Bootstrap with `prepare-sources`, then pin `hash` and `hash-type` for render. +Native settings belong in `origin.config-file`, relative to the declaring TOML. +Use `origin.module-dir` and `origin.prep-packages` only when needed. Generation +runs after overlays for prepare/build/diff; render writes the pin without generation. +Maintain extraction, offline Go settings, and licensing in specs or overlays. + The `spec` field selects where the spec is fetched from. When omitted, the component inherits the distro default (normally an upstream import). diff --git a/internal/app/azldev/agentskill/content/withoutlockfile/comp-toml.md.tmpl b/internal/app/azldev/agentskill/content/withoutlockfile/comp-toml.md.tmpl index 0e33a9e6d..ba9e91ac6 100644 --- a/internal/app/azldev/agentskill/content/withoutlockfile/comp-toml.md.tmpl +++ b/internal/app/azldev/agentskill/content/withoutlockfile/comp-toml.md.tmpl @@ -35,6 +35,15 @@ Add sub-tables only for what you change. The fields you will reach for most: ## Spec source +For generated Go dependencies, add a `source-files` entry with +`origin.type = "go-vendor"`. This generates only a tarball, never converts the spec. +Set `filename` explicitly and reference that basename in the effective spec for +packaging. Bootstrap with `prepare-sources`, then pin `hash` and `hash-type` for render. +Native settings belong in `origin.config-file`, relative to the declaring TOML. +Use `origin.module-dir` and `origin.prep-packages` only when needed. Generation +runs after overlays for prepare/build/diff; render writes the pin without generation. +Maintain extraction, offline Go settings, and licensing in specs or overlays. + The `spec` field selects where the spec is fetched from. When omitted, the component inherits the distro default (normally an upstream import). diff --git a/internal/app/azldev/cmds/component/build.go b/internal/app/azldev/cmds/component/build.go index 26a3b308e..baa94c26c 100644 --- a/internal/app/azldev/cmds/component/build.go +++ b/internal/app/azldev/cmds/component/build.go @@ -363,6 +363,7 @@ func buildComponent( }, &err) var preparerOpts []sources.PreparerOption + if !options.WithoutGitRepo { preparerOpts = append(preparerOpts, gitRepoPreparerOptions(env, distro)...) } @@ -377,7 +378,7 @@ func buildComponent( preparerOpts = append(preparerOpts, sources.WithMockProcessor(mockProcessor)) - sourcePreparer, err := newSourcePreparer(sourceManager, env.FS(), env, env, append( + sourcePreparer, err := newComponentSourcePreparer(env, component, sourceManager, options.MockConfigOpts, append( preparerOpts, sources.WithSpecEditor(options.specEditorMode()), )...) @@ -394,16 +395,11 @@ func buildComponent( allLocalRepoPaths = append(allLocalRepoPaths, options.LocalRepoWithPublishPath) } - results, err = buildComponentUsingBuilder( + return buildComponentUsingBuilder( env, component, builder, allLocalRepoPaths, options.SourcePackageOnly, options.NoCheck, options.LocalRepoWithPublishPath, ) - if err != nil { - return results, err - } - - return results, nil } func buildComponentUsingBuilder( diff --git a/internal/app/azldev/cmds/component/changed_upstreamcommit.go b/internal/app/azldev/cmds/component/changed_upstreamcommit.go index 9d95b553f..8d1762e15 100644 --- a/internal/app/azldev/cmds/component/changed_upstreamcommit.go +++ b/internal/app/azldev/cmds/component/changed_upstreamcommit.go @@ -298,6 +298,21 @@ func buildComponentComparisonInputs( inputs.OverlaySourceHashes[strconv.Itoa(idx)] = sourceName + ":" + contentHash } + for idx, ref := range component.SourceFiles { + identity, err := ref.Origin.VendorIdentity(fs) + if err != nil { + return inputs, fmt.Errorf("hashing vendor source settings:\n%w", err) + } + + if identity != "" { + if inputs.OverlaySourceHashes == nil { + inputs.OverlaySourceHashes = map[string]string{} + } + + inputs.OverlaySourceHashes["source:"+strconv.Itoa(idx)] = identity + } + } + return inputs, nil } @@ -326,6 +341,7 @@ func normalizeComponentForComparison(component projectconfig.ComponentConfig) pr normalized.SourceFiles = slices.Clone(component.SourceFiles) for idx := range normalized.SourceFiles { + normalized.SourceFiles[idx].Origin.ConfigFile = "" normalized.SourceFiles[idx].Origin.Type = "" normalized.SourceFiles[idx].Origin.Uri = "" normalized.SourceFiles[idx].ReplaceReason = "" diff --git a/internal/app/azldev/cmds/component/diffsources.go b/internal/app/azldev/cmds/component/diffsources.go index e021e01f5..efb091fd1 100644 --- a/internal/app/azldev/cmds/component/diffsources.go +++ b/internal/app/azldev/cmds/component/diffsources.go @@ -101,7 +101,7 @@ func DiffComponentSources(env *azldev.Env, options *DiffSourcesOptions) (interfa return nil, fmt.Errorf("failed to create source manager:\n%w", err) } - preparer, err := newSourcePreparer(sourceManager, env.FS(), env, env, + preparer, err := newComponentSourcePreparer(env, component, sourceManager, nil, sources.WithUpstreamProvenance(sources.FedoraDistTag(distro.Ref.Name, distro.Version.ReleaseVer)), sources.WithSpecEditor(options.specEditorMode())) if err != nil { diff --git a/internal/app/azldev/cmds/component/history_customizations.go b/internal/app/azldev/cmds/component/history_customizations.go index 2e90e7eb3..29f56c7c8 100644 --- a/internal/app/azldev/cmds/component/history_customizations.go +++ b/internal/app/azldev/cmds/component/history_customizations.go @@ -222,6 +222,17 @@ func appendSourceFileItems( ) []CustomizationItem { for _, sourceFile := range sourceFiles { items = append(items, CustomizationItem{Kind: "source-files", Value: sourceFile.Filename}) + if sourceFile.Origin.Type == projectconfig.OriginTypeGoVendor { + items = append(items, CustomizationItem{Kind: "source-files.go-vendor", Value: "enabled"}) + } + + if sourceFile.Origin.ModuleDir != "" { + items = append(items, CustomizationItem{Kind: "source-files.module-dir", Value: sourceFile.Origin.ModuleDir}) + } + + for _, pkg := range sourceFile.Origin.PrepPackages { + items = append(items, CustomizationItem{Kind: "source-files.prep-packages", Value: pkg}) + } if sourceFile.ReplaceUpstream { items = append(items, CustomizationItem{ diff --git a/internal/app/azldev/cmds/component/history_internal_test.go b/internal/app/azldev/cmds/component/history_internal_test.go index 242094194..78cb0d4a4 100644 --- a/internal/app/azldev/cmds/component/history_internal_test.go +++ b/internal/app/azldev/cmds/component/history_internal_test.go @@ -149,6 +149,8 @@ func TestCustomizationCollectorsCoverEveryFingerprintableField(t *testing.T) { "Origin.Script": "source-files.script", "Origin.MockPackages": "source-files.mock-packages", "Origin.Inputs": "source-files.inputs", + "Origin.ModuleDir": "source-files.module-dir", + "Origin.PrepPackages": "source-files.prep-packages", } actualFields := make(map[string]bool) diff --git a/internal/app/azldev/cmds/component/preparerctx.go b/internal/app/azldev/cmds/component/preparerctx.go index f98f7b671..a3c80b5ea 100644 --- a/internal/app/azldev/cmds/component/preparerctx.go +++ b/internal/app/azldev/cmds/component/preparerctx.go @@ -4,11 +4,39 @@ package component import ( + "errors" + "fmt" + "path/filepath" + "github.com/microsoft/azure-linux-dev-tools/internal/app/azldev" + "github.com/microsoft/azure-linux-dev-tools/internal/app/azldev/core/components" "github.com/microsoft/azure-linux-dev-tools/internal/app/azldev/core/sources" "github.com/microsoft/azure-linux-dev-tools/internal/providers/sourceproviders" + "github.com/microsoft/azure-linux-dev-tools/internal/rpm/mock" ) +func vendorPreparerOptions( + env *azldev.Env, comp components.Component, opts map[string]string, +) ([]sources.PreparerOption, error) { + if !comp.GetConfig().HasGoVendorSources() || env.DryRun() { + return nil, nil + } + + _, distro, err := env.Distro() + if err != nil { + return nil, fmt.Errorf("resolving vendor generation distro:\n%w", err) + } + + if distro.MockConfigPath == "" { + return nil, errors.New("'go-vendor' sources require project distro 'mock-config'") + } + + return []sources.PreparerOption{ + sources.WithGoVendorRunner(mock.NewRunner(env, distro.MockConfigPath). + WithConfigOpts(opts).WithBaseDir(filepath.Join(env.WorkDir(), "go-vendor"))), + }, nil +} + // gitRepoPreparerOptions returns the [sources.PreparerOption] values that enable // synthetic dist-git history for the current mode. // diff --git a/internal/app/azldev/cmds/component/preparesources.go b/internal/app/azldev/cmds/component/preparesources.go index 4be62ae43..f7a05041b 100644 --- a/internal/app/azldev/cmds/component/preparesources.go +++ b/internal/app/azldev/cmds/component/preparesources.go @@ -143,7 +143,7 @@ func PrepareComponentSources(env *azldev.Env, options *PrepareSourcesOptions) er preparerOpts := buildPreparerOptions(env, distro, options) - preparer, err := newSourcePreparer(sourceManager, env.FS(), env, env, append( + preparer, err := newComponentSourcePreparer(env, component, sourceManager, nil, append( preparerOpts, sources.WithSpecEditor(options.specEditorMode()), )...) diff --git a/internal/app/azldev/cmds/component/render.go b/internal/app/azldev/cmds/component/render.go index afe1e95cc..b4b95dd2e 100644 --- a/internal/app/azldev/cmds/component/render.go +++ b/internal/app/azldev/cmds/component/render.go @@ -64,9 +64,9 @@ Within the output directory, components are organized into letter-prefixed subdirectories based on the first character of their name (e.g., specs/c/curl, specs/v/vim). -Unlike prepare-sources, render skips downloading source tarballs from the -lookaside cache — only spec files, patches, scripts, and other git-tracked -sidecar files are included. Multiple components can be rendered at once. +Render normally skips lookaside archives, retaining specs and git-tracked sidecars. +Go vendor sources are rendered from their configured digests without generating +the archive. Multiple components can be rendered at once. When rendering all components (-a), the --clean-stale flag prunes orphan rendered-spec directories (per-component dirs that no longer correspond to @@ -536,10 +536,11 @@ func prepareComponentSources( // WithSkipLookaside avoids expensive tarball downloads — only spec + // sidecar files are needed for rendering. preparerOpts := append(gitRepoPreparerOptions(env, distro), - sources.WithSkipLookaside(), + sources.WithRenderManifest(), sources.WithUpstreamProvenance(sources.FedoraDistTag(distro.Ref.Name, distro.Version.ReleaseVer)), sources.WithMockProcessor(mockProcessor), ) + if rpmDevBumpspec { preparerOpts = append(preparerOpts, sources.WithRPMDevBumpspec(env, env.WorkDir(), "")) } diff --git a/internal/app/azldev/cmds/component/sourcepreparer.go b/internal/app/azldev/cmds/component/sourcepreparer.go index a16e0a00c..a57a12717 100644 --- a/internal/app/azldev/cmds/component/sourcepreparer.go +++ b/internal/app/azldev/cmds/component/sourcepreparer.go @@ -3,7 +3,31 @@ package component -import "github.com/microsoft/azure-linux-dev-tools/internal/app/azldev/core/sources" +import ( + "fmt" + + "github.com/microsoft/azure-linux-dev-tools/internal/app/azldev" + "github.com/microsoft/azure-linux-dev-tools/internal/app/azldev/core/components" + "github.com/microsoft/azure-linux-dev-tools/internal/app/azldev/core/sources" + "github.com/microsoft/azure-linux-dev-tools/internal/providers/sourceproviders" +) //nolint:gochecknoglobals // Replaced by isolated command tests to observe constructed source preparers. var newSourcePreparer = sources.NewPreparer + +func newComponentSourcePreparer( + env *azldev.Env, comp components.Component, manager sourceproviders.SourceManager, + mockOpts map[string]string, options ...sources.PreparerOption, +) (sources.SourcePreparer, error) { + vendor, err := vendorPreparerOptions(env, comp, mockOpts) + if err != nil { + return nil, err + } + + preparer, err := newSourcePreparer(manager, env.FS(), env, env, append(options, vendor...)...) + if err != nil { + return nil, fmt.Errorf("creating component source preparer:\n%w", err) + } + + return preparer, nil +} diff --git a/internal/app/azldev/core/sources/govendor.go b/internal/app/azldev/core/sources/govendor.go new file mode 100644 index 000000000..83f8ff93f --- /dev/null +++ b/internal/app/azldev/core/sources/govendor.go @@ -0,0 +1,291 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package sources + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "slices" + "strings" + + "github.com/microsoft/azure-linux-dev-tools/internal/app/azldev/core/components" + "github.com/microsoft/azure-linux-dev-tools/internal/govendor" + "github.com/microsoft/azure-linux-dev-tools/internal/projectconfig" + "github.com/microsoft/azure-linux-dev-tools/internal/providers/sourceproviders/fedorasource" + "github.com/microsoft/azure-linux-dev-tools/internal/rpm/mock" + "github.com/microsoft/azure-linux-dev-tools/internal/rpm/spec" + "github.com/microsoft/azure-linux-dev-tools/internal/utils/fileperms" + "github.com/microsoft/azure-linux-dev-tools/internal/utils/fileutils" +) + +// WithGoVendorRunner supplies the distro's isolated archive-generation environment. +func WithGoVendorRunner(runner *mock.Runner) PreparerOption { + return func(p *sourcePreparerImpl) { p.goVendorRunner = runner } +} + +// WithRenderManifest renders declared vendor pins without downloading sources or generating payloads. +func WithRenderManifest() PreparerOption { + return func(p *sourcePreparerImpl) { p.skipLookaside, p.renderManifest = true, true } +} + +func (p *sourcePreparerImpl) needsVendorInputs(config *projectconfig.ComponentConfig) bool { + return !p.renderManifest && config.HasGoVendorSources() +} + +type vendorComponent struct { + components.Component + config projectconfig.ComponentConfig +} + +func (c vendorComponent) GetConfig() *projectconfig.ComponentConfig { return &c.config } + +func vendorFingerprintConfig( + effective, declared *projectconfig.ComponentConfig, +) *projectconfig.ComponentConfig { + if !declared.HasGoVendorSources() { + return effective + } + + result := *effective + result.SourceFiles = slices.Clone(effective.SourceFiles) + // Generated hashes are outputs, not declared build inputs. + for index, ref := range declared.SourceFiles { + if ref.Origin.Type == projectconfig.OriginTypeGoVendor && index < len(result.SourceFiles) { + result.SourceFiles[index] = ref + } + } + + return &result +} + +func (p *sourcePreparerImpl) prepareVendorSources( + ctx context.Context, component components.Component, directory string, +) (components.Component, error) { + config := *component.GetConfig() + if !config.HasGoVendorSources() { + return component, nil + } + + config.SourceFiles = slices.Clone(config.SourceFiles) + if p.dryRunnable.DryRun() { + config.SourceFiles = slices.DeleteFunc(config.SourceFiles, func(ref projectconfig.SourceFileReference) bool { + return ref.Origin.Type == projectconfig.OriginTypeGoVendor + }) + + return vendorComponent{Component: component, config: config}, nil + } + + if p.goVendorRunner == nil { + return nil, errors.New("'go-vendor' sources require a project distro with 'mock-config'") + } + + for index, ref := range config.SourceFiles { + if ref.Origin.Type != projectconfig.OriginTypeGoVendor { + continue + } + + resolved, err := p.generateVendorSource(ctx, component, directory, ref) + if err != nil { + return nil, err + } + + config.SourceFiles[index] = resolved + } + + return vendorComponent{Component: component, config: config}, nil +} + +func (p *sourcePreparerImpl) generateVendorSource( + ctx context.Context, component components.Component, directory string, ref projectconfig.SourceFileReference, +) (resolved projectconfig.SourceFileReference, err error) { + specPath, err := p.resolveSpecPath(component, directory) + if err != nil { + return ref, err + } + + data, err := fileutils.ReadFile(p.fs, specPath) + if err != nil { + return ref, fmt.Errorf("reading vendor prep spec:\n%w", err) + } + + plan, err := spec.PrepareVendorSource(data, ref.Filename) + if err != nil { + return ref, fmt.Errorf("planning private vendor prep:\n%w", err) + } + + settings, err := p.vendorSettings(directory, plan.ConfigName, ref.Origin) + if err != nil { + return ref, err + } + + scratch, err := p.vendorScratchDir() + if err != nil { + return ref, fmt.Errorf("creating vendor scratch:\n%w", err) + } + defer fileutils.RemoveAllAndUpdateErrorIfNil(p.fs, scratch, &err) + + artifact, err := govendor.Generate(ctx, p.fs, p.goVendorRunner, govendor.Request{ + SourceDir: directory, WorkDir: scratch, Filename: ref.Filename, SpecName: filepath.Base(specPath), + PrepSpec: plan.Spec, Config: settings, ModuleDir: ref.Origin.ModuleDir, Packages: ref.Origin.PrepPackages, + }) + if err != nil { + return ref, fmt.Errorf("running vendor generation:\n%w", err) + } + + return p.publishVendorSource(component, directory, ref, artifact) +} + +func (p *sourcePreparerImpl) publishVendorSource( + component components.Component, directory string, ref projectconfig.SourceFileReference, + artifact govendor.Artifact, +) (projectconfig.SourceFileReference, error) { + if ref.HashType == "" { + ref.HashType = fileutils.HashTypeSHA512 + } + + digest, err := fileutils.ComputeFileHash(p.fs, ref.HashType, artifact.Path) + if err != nil { + return ref, fmt.Errorf("hashing generated vendor archive:\n%w", err) + } + + if ref.Hash != "" && !strings.EqualFold(ref.Hash, digest) { + return ref, fmt.Errorf("generated Go vendor hash mismatch for %#q: expected %s, got %s", + ref.Filename, ref.Hash, digest) + } + + ref.Hash = digest + if err := p.resolveVendorTarget(component, directory, ref); err != nil { + return ref, err + } + + return ref, p.copyVendorArchive(directory, ref.Filename, artifact.Path) +} + +func (p *sourcePreparerImpl) copyVendorArchive(directory, name, source string) error { + destination := filepath.Join(directory, name) + // Remove the old leaf first so copying cannot follow an upstream symlink. + if err := p.fs.Remove(destination); err != nil && !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("removing previous vendor output:\n%w", err) + } + + if err := fileutils.CopyFile(p.dryRunnable, p.fs, source, destination, fileutils.CopyFileOptions{}); err != nil { + return fmt.Errorf("publishing vendor archive:\n%w", err) + } + + ignorePath := filepath.Join(directory, ".gitignore") + + ignore, err := p.readSourcesFileIfExists(ignorePath) + if err != nil { + return err + } + + if !slices.Contains(strings.Split(ignore, "\n"), "/"+name) { + if err := fileutils.WriteFile(p.fs, ignorePath, + []byte(strings.TrimRight(ignore, "\n")+"\n/"+name+"\n"), fileperms.PublicFile); err != nil { + return fmt.Errorf("ignoring generated vendor archive:\n%w", err) + } + } + + return nil +} + +func (p *sourcePreparerImpl) vendorScratchDir() (string, error) { + base := p.goVendorRunner.BaseDir() + if base == "" { + path, err := fileutils.MkdirTempInTempDir(p.fs, "azldev-vendor-") + if err != nil { + return "", fmt.Errorf("creating temporary vendor directory:\n%w", err) + } + + return path, nil + } + + if err := fileutils.MkdirAll(p.fs, base); err != nil { + return "", fmt.Errorf("creating vendor work directory:\n%w", err) + } + + path, err := fileutils.MkdirTemp(p.fs, base, "azldev-vendor-") + if err != nil { + return "", fmt.Errorf("creating private vendor directory:\n%w", err) + } + + return path, nil +} + +func (p *sourcePreparerImpl) vendorSettings( + directory, upstreamName string, origin projectconfig.Origin, +) (string, error) { + if origin.ConfigFile != "" { + data, err := origin.VendorConfig(p.fs) + if err != nil { + return "", fmt.Errorf("loading vendor settings:\n%w", err) + } + + return data, nil + } + + if upstreamName == "" { + upstreamName = "go-vendor-tools.toml" + + exists, err := fileutils.Exists(p.fs, filepath.Join(directory, upstreamName)) + if err != nil { + return "", fmt.Errorf("checking native vendor settings:\n%w", err) + } + + if !exists { + return "", nil + } + } + + data, err := fileutils.ReadFile(p.fs, filepath.Join(directory, upstreamName)) + if err != nil { + return "", fmt.Errorf("reading upstream vendor settings:\n%w", err) + } + + return string(data), nil +} + +func (p *sourcePreparerImpl) resolveVendorTarget( + component components.Component, directory string, ref projectconfig.SourceFileReference, +) error { + for _, other := range component.GetConfig().SourceFiles { + if other.Origin.Type != projectconfig.OriginTypeGoVendor && other.Filename == ref.Filename { + return fmt.Errorf("go vendor output %#q conflicts with another 'source-files' entry", ref.Filename) + } + } + + manifest, err := p.readSourcesFileIfExists(filepath.Join(directory, fedorasource.SourcesFileName)) + if err != nil { + return err + } + + lines, err := fedorasource.ReadSourcesFile(manifest) + if err != nil { + return fmt.Errorf("parsing vendor target manifest:\n%w", err) + } + + for _, overlay := range component.GetConfig().Overlays { + if overlay.Archive == ref.Filename { + return errors.New("archive overlays cannot target regenerated vendor output; use native generation hooks") + } + } + + if !ref.ReplaceUpstream { + exists, err := fileutils.Exists(p.fs, filepath.Join(directory, ref.Filename)) + if err != nil { + return fmt.Errorf("checking vendor destination:\n%w", err) + } + + if exists { + return fmt.Errorf("vendor output %#q conflicts with an existing source", ref.Filename) + } + } + + _, err = p.buildSourceEntries([]projectconfig.SourceFileReference{ref}, lines, component.GetName(), directory) + + return err +} diff --git a/internal/app/azldev/core/sources/govendor_internal_test.go b/internal/app/azldev/core/sources/govendor_internal_test.go new file mode 100644 index 000000000..1b99324e6 --- /dev/null +++ b/internal/app/azldev/core/sources/govendor_internal_test.go @@ -0,0 +1,283 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package sources + +import ( + "context" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/microsoft/azure-linux-dev-tools/internal/app/azldev/core/components/components_testutils" + "github.com/microsoft/azure-linux-dev-tools/internal/projectconfig" + "github.com/microsoft/azure-linux-dev-tools/internal/providers/sourceproviders" + "github.com/microsoft/azure-linux-dev-tools/internal/providers/sourceproviders/fedorasource" + "github.com/microsoft/azure-linux-dev-tools/internal/providers/sourceproviders/sourceproviders_test" + "github.com/microsoft/azure-linux-dev-tools/internal/rpm/mock" + "github.com/microsoft/azure-linux-dev-tools/internal/utils/fileperms" + "github.com/microsoft/azure-linux-dev-tools/internal/utils/fileutils" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/mock/gomock" +) + +func TestGoVendorSourcePreparation(t *testing.T) { + const newSource = "new" + for _, mode := range []string{ + "replace", newSource, "expected hash", "mismatch", "collision", "diff", "skip overlays", + } { + t.Run(mode, func(t *testing.T) { + ctx := newMockProcessorTestCtx() + ctrl := gomock.NewController(t) + comp := components_testutils.NewMockComponent(ctrl) + manager := sourceproviders_test.NewMockSourceManager(ctrl) + + ref := projectconfig.SourceFileReference{Origin: projectconfig.Origin{ + Type: projectconfig.OriginTypeGoVendor, ConfigFile: "/project/vendor.toml", + }} + + ref.Filename = "vendor.tar.bz2" + if mode != newSource && mode != "collision" { + ref.ReplaceUpstream, ref.ReplaceReason = true, "regenerate dependencies" + } + + if mode == "mismatch" { + ref.Hash, ref.HashType = strings.Repeat("a", 128), fileutils.HashTypeSHA512 + } + + const payload = "regenerated vendor" + if mode == "expected hash" { + require.NoError(t, fileutils.WriteFile(ctx.FS(), "/expected", []byte(payload), fileperms.PublicFile)) + ref.Hash, _ = fileutils.ComputeFileHash(ctx.FS(), fileutils.HashTypeSHA256, "/expected") + ref.HashType = fileutils.HashTypeSHA256 + } + + config := &projectconfig.ComponentConfig{SourceFiles: []projectconfig.SourceFileReference{ref}} + + comp.EXPECT().GetName().AnyTimes().Return("app") + comp.EXPECT().GetConfig().AnyTimes().Return(config) + require.NoError(t, fileutils.WriteFile(ctx.FS(), "/project/vendor.toml", []byte(""), fileperms.PublicFile)) + + input := strings.Join([]string{ + "Name: app", "Version: 1", "Release: 1", "License: MIT", + "Source0: app.tar.gz", "Source5: vendor.tar.bz2", "%description", "App", "%prep", + "%setup -q", "tar -xf %{S:5}", "%build", "make build", "%install", "make install", + "%files", "/usr/bin/app", "", + }, "\n") + if mode == newSource { + input = strings.ReplaceAll(input, "Source5: vendor.tar.bz2\n", "") + input = strings.ReplaceAll(input, "tar -xf %{S:5}\n", "") + } + + manager.EXPECT().FetchComponent(gomock.Any(), comp, gomock.Any(), gomock.Any()).DoAndReturn( + func(_ context.Context, _ any, directory string, options ...sourceproviders.FetchComponentOption) error { + var fetch sourceproviders.FetchComponentOptions + for _, option := range options { + option(&fetch) + } + + assert.True(t, fetch.PreserveGitDir) + assert.False(t, fetch.SkipLookaside) + + files := map[string]string{"app.spec": input, "app.tar.gz": "source", ".git/HEAD": "history"} + if mode != newSource { + files["vendor.tar.bz2"] = "old vendor" + files["sources"] = fedorasource.FormatSourcesEntry("vendor.tar.bz2", fileutils.HashTypeSHA512, + strings.Repeat("a", 128)) + "\n" + } + + for name, content := range files { + require.NoError(t, fileutils.MkdirAll(ctx.FS(), filepath.Dir(filepath.Join(directory, name)))) + require.NoError(t, fileutils.WriteFile(ctx.FS(), filepath.Join(directory, name), + []byte(content), fileperms.PublicFile)) + } + + return nil + }) + manager.EXPECT().FetchFiles(gomock.Any(), comp, gomock.Any()).Return(nil) + + ctx.CmdFactory.RunAndGetOutputHandler = func(cmd *exec.Cmd) (string, error) { + assert.Contains(t, strings.Join(cmd.Args, " "), "go_vendor_archive create") + + matches, err := fileutils.Glob(ctx.FS(), "/project/build/vendor/azldev-vendor-*/output/config.toml") + require.NoError(t, err) + require.Len(t, matches, 1) + assert.NotContains(t, matches[0], "*") + directory := filepath.Dir(matches[0]) + prep, err := fileutils.ReadFile(ctx.FS(), filepath.Join(filepath.Dir(directory), "sources", "app.spec")) + require.NoError(t, err) + assert.NotContains(t, string(prep), "tar -xf %{S:5}") + assert.NotContains(t, string(prep), "Source5:") + + history, err := fileutils.ReadFile(ctx.FS(), filepath.Join(filepath.Dir(directory), "sources", ".git", "HEAD")) + require.NoError(t, err) + assert.Equal(t, "history", string(history)) + + require.NoError(t, fileutils.WriteFile(ctx.FS(), filepath.Join(directory, ref.Filename), + []byte(payload), fileperms.PublicFile)) + + return "", nil + } + preparer, err := NewPreparer(manager, ctx.FS(), ctx, ctx, + WithGoVendorRunner(mock.NewRunner(ctx, "/mock.cfg").WithBaseDir("/project/build/vendor")), WithSkipLookaside()) + require.NoError(t, err) + + if mode == "diff" { + require.NoError(t, fileutils.MkdirAll(ctx.FS(), "/output")) + diff, err := preparer.DiffSources(ctx, comp, "/output") + require.NoError(t, err) + assert.Contains(t, diff.String(), "vendor.tar.bz2") + assert.NotContains(t, diff.String(), ".git/HEAD") + + return + } + + err = preparer.PrepareSources(ctx, comp, "/output", mode != "skip overlays") + if mode == "mismatch" || mode == "collision" { + require.Error(t, err) + + data, readErr := fileutils.ReadFile(ctx.FS(), "/output/vendor.tar.bz2") + require.NoError(t, readErr) + assert.Equal(t, "old vendor", string(data)) + + return + } + + require.NoError(t, err) + spec, err := fileutils.ReadFile(ctx.FS(), "/output/app.spec") + require.NoError(t, err) + assert.Contains(t, string(spec), input, "published spec is not converted or rewritten by generation") + assert.NotContains(t, string(spec), "GOFLAGS") + + data, err := fileutils.ReadFile(ctx.FS(), "/output/vendor.tar.bz2") + require.NoError(t, err) + assert.Equal(t, payload, string(data)) + + manifest, err := fileutils.ReadFile(ctx.FS(), "/output/sources") + require.NoError(t, err) + + algorithm := ref.HashType + if algorithm == "" { + algorithm = fileutils.HashTypeSHA512 + } + + hash, err := fileutils.ComputeFileHash(ctx.FS(), algorithm, "/output/vendor.tar.bz2") + require.NoError(t, err) + assert.Contains(t, string(manifest), fedorasource.FormatSourcesEntry("vendor.tar.bz2", algorithm, hash)) + + exists, err := fileutils.Exists(ctx.FS(), "/output/.git") + require.NoError(t, err) + assert.False(t, exists) + assert.Equal(t, ref, config.SourceFiles[0], "runtime output must not mutate declarative inputs") + }) + } +} + +func TestRenderVendorPin(t *testing.T) { + ctx := newMockProcessorTestCtx() + comp := components_testutils.NewMockComponent(gomock.NewController(t)) + comp.EXPECT().GetName().AnyTimes().Return("app") + + ref := projectconfig.SourceFileReference{ + Filename: "app-2-vendor.tar.gz", Origin: projectconfig.Origin{Type: projectconfig.OriginTypeGoVendor}, + } + config := &projectconfig.ComponentConfig{SourceFiles: []projectconfig.SourceFileReference{ref}} + comp.EXPECT().GetConfig().AnyTimes().Return(config) + + preparer := sourcePreparerImpl{fs: ctx.FS()} + WithRenderManifest()(&preparer) + require.False(t, preparer.needsVendorInputs(config)) + require.True(t, preparer.skipLookaside) + + _, err := preparer.updateSourcesFile(comp, "/staged", nil) + require.ErrorContains(t, err, "run 'component prepare-sources'") + + pin := strings.Repeat("b", 128) + config.SourceFiles[0].HashType, config.SourceFiles[0].Hash = fileutils.HashTypeSHA512, pin + require.NoError(t, fileutils.WriteFile(ctx.FS(), "/staged/app.spec", + []byte("Name: app\nSource7: %{name}-%{version}-vendor.tar.gz\n%prep\ntar -xf %{S:7}\n"), fileperms.PublicFile)) + entry := fedorasource.FormatSourcesEntry("app-2-vendor.tar.gz", fileutils.HashTypeSHA512, strings.Repeat("a", 128)) + require.NoError(t, fileutils.WriteFile(ctx.FS(), "/staged/sources", []byte(entry+"\n"), fileperms.PublicFile)) + + _, err = preparer.updateSourcesFile(comp, "/staged", nil) + require.ErrorContains(t, err, "conflicts") + + config.SourceFiles[0].ReplaceUpstream, config.SourceFiles[0].ReplaceReason = true, "regenerate dependencies" + _, err = preparer.updateSourcesFile(comp, "/staged", nil) + require.NoError(t, err) + manifest, err := fileutils.ReadFile(ctx.FS(), "/staged/sources") + require.NoError(t, err) + + want := fedorasource.FormatSourcesEntry("app-2-vendor.tar.gz", fileutils.HashTypeSHA512, pin) + assert.Equal(t, want+"\n", string(manifest)) +} + +func TestVendorSettings(t *testing.T) { + const ( + invalid = "invalid" + missing = "missing" + ) + for _, mode := range []string{"explicit", "empty", "upstream", "default", missing, "no settings", invalid} { + t.Run(mode, func(t *testing.T) { + ctx := newMockProcessorTestCtx() + preparer := &sourcePreparerImpl{fs: ctx.FS()} + origin := projectconfig.Origin{} + name := "native.toml" + expected := "[archive]\ntidy = false\n" + + switch mode { + case "explicit", "empty", invalid, missing: + origin.ConfigFile = "/project/vendor.toml" + + content := expected + if mode == "empty" { + content, expected = "", "" + } + + if mode == invalid { + content = "invalid toml" + } + + if mode != missing { + require.NoError(t, fileutils.WriteFile(ctx.FS(), origin.ConfigFile, + []byte(content), fileperms.PublicFile)) + } + case "upstream": + require.NoError(t, fileutils.WriteFile(ctx.FS(), "/sources/"+name, []byte(expected), fileperms.PublicFile)) + case "default": + name = "" + + require.NoError(t, fileutils.WriteFile(ctx.FS(), "/sources/go-vendor-tools.toml", + []byte(expected), fileperms.PublicFile)) + case "no settings": + name, expected = "", "" + } + + actual, err := preparer.vendorSettings("/sources", name, origin) + if mode == missing || mode == invalid { + require.Error(t, err) + + return + } + + require.NoError(t, err) + assert.Equal(t, expected, actual) + }) + } +} + +func TestVendorFingerprintUsesDeclaredInputs(t *testing.T) { + declared := &projectconfig.ComponentConfig{SourceFiles: []projectconfig.SourceFileReference{ + {Filename: "other.tar.gz", Hash: "other"}, + {Origin: projectconfig.Origin{Type: projectconfig.OriginTypeGoVendor}}, + }} + effective := *declared + effective.SourceFiles = append([]projectconfig.SourceFileReference(nil), declared.SourceFiles...) + effective.SourceFiles[1].Filename = "vendor.tar.bz2" + effective.SourceFiles[1].Hash = "generated" + restored := vendorFingerprintConfig(&effective, declared) + assert.Equal(t, declared.SourceFiles, restored.SourceFiles) + assert.Equal(t, "generated", effective.SourceFiles[1].Hash, "must not mutate runtime manifest inputs") +} diff --git a/internal/app/azldev/core/sources/sourceprep.go b/internal/app/azldev/core/sources/sourceprep.go index 4edeb30b6..74ec16cde 100644 --- a/internal/app/azldev/core/sources/sourceprep.go +++ b/internal/app/azldev/core/sources/sourceprep.go @@ -24,6 +24,7 @@ import ( "github.com/microsoft/azure-linux-dev-tools/internal/projectconfig" "github.com/microsoft/azure-linux-dev-tools/internal/providers/sourceproviders" "github.com/microsoft/azure-linux-dev-tools/internal/providers/sourceproviders/fedorasource" + "github.com/microsoft/azure-linux-dev-tools/internal/rpm/mock" "github.com/microsoft/azure-linux-dev-tools/internal/rpm/spec" "github.com/microsoft/azure-linux-dev-tools/internal/utils/dirdiff" "github.com/microsoft/azure-linux-dev-tools/internal/utils/fileperms" @@ -198,6 +199,10 @@ type sourcePreparerImpl struct { // source preparation. Git-tracked files are still fetched. skipLookaside bool + goVendorRunner *mock.Runner + vendorFetchOnly bool + renderManifest bool + // cmdFactory is used to shell out to git for fingerprint change detection // in the project repository. Set via [WithGitRepo]. cmdFactory opctx.CmdFactory @@ -303,20 +308,12 @@ func (p *sourcePreparerImpl) PrepareSources( } } - // Preserve the upstream .git directory only when dist-git creation is - // requested via --with-git. This is required so that overlay commits can be - // appended on top of the upstream commit log during synthetic history generation. - var fetchOpts []sourceproviders.FetchComponentOption - if applyOverlays && p.withGitRepo { - fetchOpts = append(fetchOpts, sourceproviders.WithPreserveGitDir()) - } - - if p.skipLookaside { - fetchOpts = append(fetchOpts, sourceproviders.WithSkipLookaside()) - } + declaredConfig := component.GetConfig() + vendor := p.needsVendorInputs(declaredConfig) + p = p.withVendorDownloads(vendor) // Fetch the component first (spec, sidecar files, and upstream source tarballs). - err := p.sourceManager.FetchComponent(ctx, component, outputDir, fetchOpts...) + err := p.sourceManager.FetchComponent(ctx, component, outputDir, p.componentFetchOptions(vendor, applyOverlays)...) if err != nil { return fmt.Errorf("failed to fetch sources for component %#q:\n%w", component.GetName(), err) @@ -332,12 +329,23 @@ func (p *sourcePreparerImpl) PrepareSources( fingerprintConfig := component.GetConfig() + var repackedArchives []string + if applyOverlays { - repackedArchives, err := p.applyOverlaysToSources(ctx, component, outputDir) + repackedArchives, err = p.applyOverlaysToSources(ctx, component, outputDir) if err != nil { return err } + } + + if p.generatesVendor(vendor) { + component, err = p.prepareVendorSources(ctx, component, outputDir) + if err != nil { + return fmt.Errorf("preparing Go vendor source:\n%w", err) + } + } + if applyOverlays || p.generatesVendor(vendor) { fingerprintConfig, err = p.updateSourcesFile(component, outputDir, repackedArchives) if err != nil { return fmt.Errorf("failed to update 'sources' file for component %#q:\n%w", @@ -350,6 +358,8 @@ func (p *sourcePreparerImpl) PrepareSources( } // Record the changes as synthetic git history when dist-git creation is enabled. + fingerprintConfig = vendorFingerprintConfig(fingerprintConfig, declaredConfig) + if p.withGitRepo { if err := p.trySyntheticHistory(ctx, component, fingerprintConfig, outputDir); err != nil { return fmt.Errorf("failed to generate synthetic history for component %#q:\n%w", @@ -357,6 +367,46 @@ func (p *sourcePreparerImpl) PrepareSources( } } + return p.removePrivateVendorHistory(outputDir, vendor) +} + +func (p *sourcePreparerImpl) withVendorDownloads(vendor bool) *sourcePreparerImpl { + if !vendor { + return p + } + + effective := *p + effective.skipLookaside = false + + return &effective +} + +func (p *sourcePreparerImpl) generatesVendor(vendor bool) bool { + return vendor && !p.vendorFetchOnly +} + +func (p *sourcePreparerImpl) componentFetchOptions(vendor, applyOverlays bool) []sourceproviders.FetchComponentOption { + var options []sourceproviders.FetchComponentOption + if (applyOverlays && p.withGitRepo) || vendor { + options = append(options, sourceproviders.WithPreserveGitDir()) + } + + if p.skipLookaside { + options = append(options, sourceproviders.WithSkipLookaside()) + } + + return options +} + +func (p *sourcePreparerImpl) removePrivateVendorHistory(directory string, vendor bool) error { + if !vendor || p.withGitRepo || p.vendorFetchOnly || p.dryRunnable.DryRun() { + return nil + } + + if err := p.fs.RemoveAll(filepath.Join(directory, ".git")); err != nil { + return fmt.Errorf("removing private vendor history:\n%w", err) + } + return nil } @@ -752,7 +802,10 @@ func (p *sourcePreparerImpl) DiffSources( defer fileutils.RemoveAllAndUpdateErrorIfNil(p.fs, originalDir, &err) // Prepare sources without applying overlays, to get the original tree. - if err := p.PrepareSources(ctx, component, originalDir, false /* applyOverlays */); err != nil { + fetcher := *p + + fetcher.vendorFetchOnly = true + if err := fetcher.PrepareSources(ctx, component, originalDir, false /* applyOverlays */); err != nil { return nil, err } @@ -779,6 +832,10 @@ func (p *sourcePreparerImpl) DiffSources( return nil, fmt.Errorf("failed to apply overlays for component %#q:\n%w", component.GetName(), err) } + if _, err := p.prepareVendorSources(ctx, component, overlaidDir); err != nil { + return nil, err + } + // Diff the original tree against the overlaid tree. result, err = dirdiff.DiffDirs(p.fs, originalDir, overlaidDir) if err != nil { @@ -1064,6 +1121,13 @@ func (p *sourcePreparerImpl) buildSourceEntries( appendLines := make([]string, 0, len(sourceFiles)) for index := range sourceFiles { + if p.renderManifest && sourceFiles[index].Origin.Type == projectconfig.OriginTypeGoVendor { + if sourceFiles[index].Hash == "" || sourceFiles[index].HashType == "" { + return nil, errors.New("render requires 'hash' and 'hash-type' for 'go-vendor'; " + + "run 'component prepare-sources' and pin the digest from its 'sources' file") + } + } + formatted, isReplacement, resolvedRef, err := p.processSourceRef( sourceFiles[index], existingByName, componentName, outputDir) if err != nil { diff --git a/internal/fingerprint/fingerprint.go b/internal/fingerprint/fingerprint.go index 391559d66..60153a4b4 100644 --- a/internal/fingerprint/fingerprint.go +++ b/internal/fingerprint/fingerprint.go @@ -99,7 +99,7 @@ func ComputeIdentity( // 2. Verify all source files have a hash. Without a hash the fingerprint // cannot detect content changes, so we refuse to compute one. for i := range component.SourceFiles { - if component.SourceFiles[i].Hash == "" { + if component.SourceFiles[i].Hash == "" && component.SourceFiles[i].Origin.Type != projectconfig.OriginTypeGoVendor { return nil, fmt.Errorf( "source file %#q has no hash; cannot compute a deterministic fingerprint", component.SourceFiles[i].Filename, @@ -141,6 +141,17 @@ func ComputeIdentity( inputs.OverlayFileHashes = overlayHashes + for idx, ref := range component.SourceFiles { + identity, err := ref.Origin.VendorIdentity(fs) + if err != nil { + return nil, fmt.Errorf("hashing source %d vendor settings:\n%w", idx, err) + } + + if identity != "" { + overlayHashes["source:"+strconv.Itoa(idx)] = identity + } + } + // 5. Combine all inputs into the overall fingerprint. return &ComponentIdentity{ Fingerprint: combineInputs(inputs), diff --git a/internal/govendor/generate.go b/internal/govendor/generate.go new file mode 100644 index 000000000..3899e5d92 --- /dev/null +++ b/internal/govendor/generate.go @@ -0,0 +1,272 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +// Package govendor generates source archives without changing published RPM packaging. +package govendor + +import ( + "context" + "errors" + "fmt" + "io" + "log/slog" + "os" + "path/filepath" + "strings" + "time" + + "github.com/kballard/go-shellquote" + "github.com/microsoft/azure-linux-dev-tools/internal/global/opctx" + "github.com/microsoft/azure-linux-dev-tools/internal/rpm/mock" + "github.com/microsoft/azure-linux-dev-tools/internal/utils/fileperms" + "github.com/microsoft/azure-linux-dev-tools/internal/utils/fileutils" + "github.com/pelletier/go-toml/v2" + "golang.org/x/sys/unix" +) + +// Request contains an isolated private spec and the effective native tool settings. +type Request struct { + SourceDir, WorkDir, SpecName, Filename string + PrepSpec []byte + Config string + ModuleDir string + Packages []string +} + +// Artifact is a host-owned copy of the generated tarball. +type Artifact struct { + Name, Path string +} + +const cleanupTimeout = 5 * time.Minute + +// Generate runs prep and native go-vendor-tools in a fresh mock root. +func Generate(ctx context.Context, fs opctx.FS, base *mock.Runner, req Request) (Artifact, error) { + output, err := stage(fs, req) + if err != nil { + return Artifact{}, err + } + + if err := execute(ctx, base, req, output); err != nil { + return Artifact{}, err + } + + return readArtifact(fs, req.WorkDir, output, req.Filename) +} + +func stage(fs opctx.FS, req Request) (string, error) { + relative, err := filepath.Rel(req.SourceDir, req.WorkDir) + if err != nil || (relative != ".." && !strings.HasPrefix(relative, ".."+string(filepath.Separator))) { + return "", errors.New("vendor work directory must be outside the prepared sources") + } + + if err := fileutils.ValidateFilename(req.SpecName); err != nil { + return "", fmt.Errorf("validating vendor spec basename:\n%w", err) + } + + staged := filepath.Join(req.WorkDir, "sources") + + output := filepath.Join(req.WorkDir, "output") + if err := fileutils.CopyDirRecursiveCrossFS(fs, req.SourceDir, fs, staged, + fileutils.CopyDirOptions{CopyFileOptions: fileutils.CopyFileOptions{PreserveFileMode: true}}); err != nil { + return "", fmt.Errorf("staging Go vendor inputs:\n%w", err) + } + + if err := fileutils.MkdirAll(fs, output); err != nil { + return "", fmt.Errorf("creating vendor output directory:\n%w", err) + } + + for path, content := range map[string][]byte{ + filepath.Join(staged, req.SpecName): req.PrepSpec, + filepath.Join(output, "config.toml"): []byte(req.Config), + } { + if err := fileutils.WriteFile(fs, path, content, fileperms.PublicFile); err != nil { + return "", fmt.Errorf("writing private vendor input:\n%w", err) + } + } + + return output, nil +} + +func execute(ctx context.Context, base *mock.Runner, req Request, output string) (err error) { + command, err := generationCommand(req, base.ConfigOpts()["target_arch"]) + if err != nil { + return err + } + + runner := base.Clone().WithRootDir("").WithBaseDir(filepath.Join(req.WorkDir, "mock")). + EnableNetwork().WithUnprivileged() + // Initialization and cleanup must use the same private root, regardless of the build's location overrides. + for _, key := range []string{"root", "rootdir", "basedir"} { + delete(runner.ConfigOpts(), key) + } + + runner.AddBindMount(filepath.Join(req.WorkDir, "sources"), "/azldev-vendor-sources"). + AddBindMount(output, "/azldev-vendor-output") + + defer func() { + cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), cleanupTimeout) + defer cancel() + + if cleanupErr := runner.ScrubRoot(cleanup); cleanupErr != nil { + slog.Error("Failed to scrub Go vendor generation root", "error", cleanupErr) + + if err == nil { + err = cleanupErr + } + } + }() + + if err := runner.InitRoot(ctx); err != nil { + return fmt.Errorf("initializing Go vendor root:\n%w", err) + } + + packages := append([]string{ + "go-vendor-tools", "golang", "go-rpm-macros", "rpm-build", + "rpmdevtools", "rpmautospec", "git", "python3-click", + }, req.Packages...) + if err := runner.InstallPackages(ctx, packages); err != nil { + return fmt.Errorf("installing Go vendor tools:\n%w", err) + } + + cmd, err := runner.CmdInChroot(ctx, command, false) + if err != nil { + return fmt.Errorf("constructing vendor generation command:\n%w", err) + } + + log, err := cmd.RunAndGetOutput(ctx) + if err != nil { + return fmt.Errorf("generating Go vendor archive:\n%s\n%w", log, err) + } + + return nil +} + +func readArtifact(fs opctx.FS, workDir, output, name string) (Artifact, error) { + artifact := Artifact{Name: name} + if err := fileutils.ValidateFilename(name); err != nil { + return artifact, fmt.Errorf("invalid vendor filename:\n%w", err) + } + + if strings.ContainsAny(name, "%\r\n") || !archiveFilename(name) { + return artifact, fmt.Errorf("unsupported vendor filename %#q", name) + } + + artifact.Path = filepath.Join(workDir, artifact.Name) + if err := collect(fs, filepath.Join(output, artifact.Name), artifact.Path); err != nil { + return artifact, err + } + + return artifact, nil +} + +func generationCommand(req Request, arch string) ([]string, error) { + var config struct { + General struct { + ModuleDir string `toml:"go_mod_dir"` + } `toml:"general"` + } + if err := toml.Unmarshal([]byte(req.Config), &config); err != nil { + return nil, fmt.Errorf("parsing native vendor config:\n%w", err) + } + + for _, directory := range []string{req.ModuleDir, config.General.ModuleDir} { + if directory != "" { + if err := fileutils.ValidateRelPath(directory); err != nil { + return nil, fmt.Errorf("validating module directory:\n%w", err) + } + + if strings.ContainsAny(directory, "%\r\n") { + return nil, errors.New("invalid Go vendor module directory") + } + } + } + + module := req.ModuleDir + if config.General.ModuleDir != "" { + if module != "" && module != config.General.ModuleDir { + return nil, errors.New("'module-dir' conflicts with native 'general.go_mod_dir'") + } + + module = "" + } + + if module == "" { + module = "." + } + + quote := shellquote.Join + + prep := []string{ + "rpmbuild", "-bp", "--nodeps", "--define", "_topdir /tmp/azldev-vendor", + "--define", "_sourcedir /azldev-vendor-sources", + } + if arch != "" { + prep = append(prep, "--target", arch) + } + + prep = append(prep, req.SpecName) + lines := []string{ + "export GOTOOLCHAIN=local", + "cd /azldev-vendor-sources", + "mkdir -p /tmp/azldev-vendor/BUILD", + "git config --global --add safe.directory /azldev-vendor-sources", + quote("rpmautospec", "process-distgit", req.SpecName, req.SpecName), + quote(prep...), + "IFS= read -r root < /tmp/azldev-vendor/azldev-vendor-root", + `cd "$root"`, + "cd " + quote(module), + quote("test", "-f", filepath.Join(config.General.ModuleDir, "go.mod")), + `root=$(pwd -P)`, + "cd /azldev-vendor-sources", + quote("go_vendor_archive", "create", "--config", "/azldev-vendor-output/config.toml", + "--output", filepath.Join("/azldev-vendor-output", req.Filename)) + ` "$root"`, + } + + return []string{"bash", "-euo", "pipefail", "-c", strings.Join(lines, "\n")}, nil +} + +func archiveFilename(name string) bool { + for _, suffix := range []string{".tar", ".tar.gz", ".tar.bz2", ".tar.xz", ".tar.zst", ".tar.zstd"} { + if strings.HasSuffix(name, suffix) { + return true + } + } + + return false +} + +func collect(fs opctx.FS, source, destination string) (err error) { + file, err := fs.OpenFile(source, os.O_RDONLY|unix.O_NOFOLLOW|unix.O_NONBLOCK, 0) + if err != nil { + return fmt.Errorf("opening generated vendor output %#q:\n%w", source, err) + } + defer file.Close() + + info, err := file.Stat() + if err != nil { + return fmt.Errorf("checking generated vendor output:\n%w", err) + } + + if !info.Mode().IsRegular() || info.Size() == 0 { + return fmt.Errorf("generated output %#q must be a nonempty regular file", source) + } + + dest, err := fs.OpenFile(destination, os.O_WRONLY|os.O_CREATE|os.O_EXCL, fileperms.PublicFile) + if err != nil { + return fmt.Errorf("creating private vendor artifact:\n%w", err) + } + + defer func() { + if closeErr := dest.Close(); err == nil { + err = closeErr + } + }() + + _, err = io.Copy(dest, file) + if err != nil { + return fmt.Errorf("copying generated vendor output:\n%w", err) + } + + return nil +} diff --git a/internal/govendor/generate_internal_test.go b/internal/govendor/generate_internal_test.go new file mode 100644 index 000000000..85ff8885d --- /dev/null +++ b/internal/govendor/generate_internal_test.go @@ -0,0 +1,109 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package govendor + +import ( + "errors" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/microsoft/azure-linux-dev-tools/internal/global/testctx" + "github.com/microsoft/azure-linux-dev-tools/internal/rpm/mock" + "github.com/microsoft/azure-linux-dev-tools/internal/utils/fileperms" + "github.com/microsoft/azure-linux-dev-tools/internal/utils/fileutils" + "github.com/spf13/afero" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestGenerationFailureScrubsRoot(t *testing.T) { + ctx := testctx.NewCtx() + ctx.CmdFactory.RegisterCommandInSearchPath(mock.MockBinary) + + var commands []string + + ctx.CmdFactory.RunHandler = func(cmd *exec.Cmd) error { + commands = append(commands, strings.Join(cmd.Args, " ")) + + return nil + } + failure := errors.New("generation failed") + ctx.CmdFactory.RunAndGetOutputHandler = func(*exec.Cmd) (string, error) { + return "native tool failed", failure + } + base := mock.NewRunner(ctx, "/mock.cfg").WithRootDir("/shared/root").WithConfigOpts(map[string]string{ + "root": "/shared/name", "basedir": "/shared/base", "rootdir": "/shared/build", "target_arch": "aarch64", + }) + err := execute(ctx, base, Request{WorkDir: "/work", SpecName: "app.spec"}, "/output") + require.ErrorIs(t, err, failure) + assert.Contains(t, strings.Join(commands, "\n"), "--scrub all") + + for _, command := range commands { + assert.NotContains(t, command, "/shared/") + assert.Contains(t, command, "basedir=/work/mock") + assert.Contains(t, command, "target_arch=aarch64") + } + + assert.Equal(t, "/shared/base", base.ConfigOpts()["basedir"]) +} + +func TestReadArtifactRejectsInvalidOutputs(t *testing.T) { + for _, testCase := range []struct{ name, wantErr string }{ + {"", "invalid vendor filename"}, + {"../host", "invalid vendor filename"}, + {"vendor.tar.bz2", "nonempty regular file"}, + } { + t.Run(testCase.wantErr, func(t *testing.T) { + fs := testctx.NewCtx().FS() + require.NoError(t, fileutils.WriteFile(fs, "/work/output/vendor.tar.bz2", nil, fileperms.PublicFile)) + + _, err := readArtifact(fs, "/work", "/work/output", testCase.name) + require.ErrorContains(t, err, testCase.wantErr) + }) + } +} + +func TestGenerationModuleLayout(t *testing.T) { + for _, req := range []Request{ + {ModuleDir: "cmd/app"}, + {Config: "[general]\ngo_mod_dir = 'cmd/app'\n"}, + {ModuleDir: "cmd/app", Config: "[general]\ngo_mod_dir = 'cmd/app'\n"}, + } { + command, err := generationCommand(req, "aarch64") + require.NoError(t, err) + assert.Contains(t, command[len(command)-1], "--target aarch64") + + if req.Config == "" { + assert.Contains(t, command[len(command)-1], "cd cmd/app\ntest -f go.mod") + } else { + assert.Contains(t, command[len(command)-1], "cd .\ntest -f cmd/app/go.mod") + } + } + + for _, req := range []Request{ + {ModuleDir: "../bad"}, + {Config: "[general]\ngo_mod_dir = '../bad'\n"}, + {ModuleDir: "other", Config: "[general]\ngo_mod_dir = 'cmd/app'\n"}, + {Config: "not valid toml"}, + } { + _, err := generationCommand(req, "") + require.Error(t, err) + } +} + +func TestCollectRejectsSymlinks(t *testing.T) { + // Real FS is necessary to exercise the kernel's O_NOFOLLOW semantics. + directory := t.TempDir() + target := filepath.Join(directory, "target") + link := filepath.Join(directory, "link") + + require.NoError(t, os.WriteFile(target, []byte("host data"), fileperms.PublicFile)) + require.NoError(t, os.Symlink(target, link)) + err := collect(afero.NewOsFs(), link, filepath.Join(directory, "copy")) + require.Error(t, err) + require.NoFileExists(t, filepath.Join(directory, "copy")) +} diff --git a/internal/projectconfig/component.go b/internal/projectconfig/component.go index 6b56f9d8e..d97a2d8fb 100644 --- a/internal/projectconfig/component.go +++ b/internal/projectconfig/component.go @@ -55,20 +55,22 @@ const ( // fields record the expected post-overlay hash, or can be omitted temporarily with // '--allow-no-hashes' while source preparation computes the initial value. OriginTypeOverlay OriginType = "overlay" + + // OriginTypeGoVendor generates a Go vendor archive after source overlays. + OriginTypeGoVendor OriginType = "go-vendor" ) // IsFetched reports whether [SourceManager.FetchFiles] downloads this origin type to disk. -// Returns false for [OriginTypeOverlay], which obtains its file via the upstream lookaside -// extractor in [SourceManager.FetchComponent]. All other types return true. +// Overlay inputs come from upstream; Go vendor outputs are generated after overlays. func (t OriginType) IsFetched() bool { - return t != OriginTypeOverlay + return t != OriginTypeOverlay && t != OriginTypeGoVendor } // Origin describes where a source file comes from and how to retrieve it. // An origin is required for every 'source-files' entry. type Origin struct { // Type indicates how the source file should be acquired. - Type OriginType `toml:"type" json:"type" jsonschema:"required,enum=download,enum=custom,enum=overlay,title=Origin type,description=Type of origin for this source file" fingerprint:"-"` + Type OriginType `toml:"type" json:"type" jsonschema:"required,enum=download,enum=custom,enum=overlay,enum=go-vendor,title=Origin type,description=Type of origin for this source file" fingerprint:"-"` // Uri to download the source file from if origin type is 'download'. Ignored for other origin types. Uri string `toml:"uri,omitempty" json:"uri,omitempty" jsonschema:"title=URI,description=URI to download the source file from if origin type is 'download',example=https://example.com/source.tar.gz" fingerprint:"-"` @@ -87,6 +89,13 @@ type Origin struct { // before it runs. Each entry must be a plain filename. Only valid when // [Origin.Type] is 'custom'. Inputs []string `toml:"inputs,omitempty" json:"inputs,omitempty" jsonschema:"title=Inputs,description=Source-output filenames to make available next to the generation script before it runs. Only valid when origin type is 'custom'."` + + // ConfigFile selects native Go vendor settings relative to the declaring TOML. + ConfigFile string `toml:"config-file,omitempty" json:"configFile,omitempty" jsonschema:"title=Vendor configuration file,description=Native go-vendor-tools TOML relative to the declaring config. Only valid for go-vendor." fingerprint:"-"` + // ModuleDir selects a module relative to the final prep directory. + ModuleDir string `toml:"module-dir,omitempty" json:"moduleDir,omitempty" jsonschema:"title=Module directory,description=Module directory relative to the prepared source root. Only valid for go-vendor."` + // PrepPackages supplies tools needed by the spec's prep commands. + PrepPackages []string `toml:"prep-packages,omitempty" json:"prepPackages,omitempty" jsonschema:"title=Prep packages,description=Additional RPM packages for private prep. Only valid for go-vendor."` } // EffectiveScriptName returns the checkout-independent filename of [Origin.Script]. @@ -109,6 +118,10 @@ func (o Origin) HashInclude(field string, _ any) (bool, error) { return len(o.MockPackages) > 0, nil case "Inputs": return len(o.Inputs) > 0, nil + case "ModuleDir": + return o.ModuleDir != "", nil + case "PrepPackages": + return len(o.PrepPackages) > 0, nil } return true, nil @@ -120,7 +133,7 @@ type SourceFileReference struct { Component ComponentReference `toml:"-" json:"-" fingerprint:"-"` // Name of the source file; must be non-empty. - Filename string `toml:"filename" json:"filename"` + Filename string `toml:"filename" json:"filename" jsonschema:"required,description=Source file basename."` // Hash of the source file, expressed as a hex string. Hash string `toml:"hash,omitempty" json:"hash,omitempty"` @@ -613,6 +626,10 @@ func ResolveComponentConfig( return ComponentConfig{}, fmt.Errorf("failed to apply component config:\n%w", err) } + if err := validateVendorSourceCount(merged.SourceFiles); err != nil { + return ComponentConfig{}, fmt.Errorf("invalid resolved sources for %#q:\n%w", comp.Name, err) + } + merged.resolveLocalCustomScriptPaths() return merged, nil @@ -649,6 +666,10 @@ func (c *ComponentConfig) WithAbsolutePaths(referenceDir string) *ComponentConfi for i := range result.SourceFiles { origin := &result.SourceFiles[i].Origin + if origin.Type == OriginTypeGoVendor { + origin.ConfigFile = makeAbsolute(referenceDir, origin.ConfigFile) + } + if origin.Type == OriginTypeCustom { origin.Script = makeAbsolute(referenceDir, origin.Script) } diff --git a/internal/projectconfig/configfile.go b/internal/projectconfig/configfile.go index ee6f07c73..75b38baaa 100644 --- a/internal/projectconfig/configfile.go +++ b/internal/projectconfig/configfile.go @@ -530,8 +530,12 @@ func validateSourceFiles( ) error { seen := make(map[string]bool, len(sourceFiles)) + if err := validateVendorSourceCount(sourceFiles); err != nil { + return err + } + for _, ref := range sourceFiles { - if err := fileutils.ValidateFilename(ref.Filename); err != nil { + if err := validateSourceFilename(ref); err != nil { return fmt.Errorf("invalid filename %#q for source file in component %#q:\n%w", ref.Filename, componentName, err) } @@ -718,6 +722,10 @@ func validateCustomSourceInputs( // For [OriginTypeURI] ('download'), the [Origin.Uri] field must be a valid URI with a scheme. // For [OriginTypeOverlay] ('overlay'), no URI is used; the archive is already on disk. func validateOrigin(origin Origin, filename string, componentName string) error { + if err := validateGoVendorOrigin(origin); err != nil { + return fmt.Errorf("invalid source origin for component %#q:\n%w", componentName, err) + } + if origin.Type == "" { return fmt.Errorf( "missing 'origin' for source file %#q, component %#q; "+ @@ -758,7 +766,7 @@ func validateOrigin(origin Origin, filename string, componentName string) error filename, componentName) } - case OriginTypeOverlay: + case OriginTypeOverlay, OriginTypeGoVendor: if origin.Uri != "" { return fmt.Errorf( "unexpected 'uri' for source file %#q, component %#q; "+ diff --git a/internal/projectconfig/fingerprint_test.go b/internal/projectconfig/fingerprint_test.go index 836eee6f3..b41b88aa0 100644 --- a/internal/projectconfig/fingerprint_test.go +++ b/internal/projectconfig/fingerprint_test.go @@ -96,6 +96,8 @@ func TestAllFingerprintedFieldsHaveDecision(t *testing.T) { // what the generated artifact contains. "Origin.Type": true, "Origin.Uri": true, + // Native settings are hashed by content, not their checkout-specific path. + "Origin.ConfigFile": true, // SourceFileReference.ReplaceReason — human documentation for why an upstream entry is // being replaced. ReplaceUpstream itself remains in the fingerprint because flipping it diff --git a/internal/projectconfig/govendor.go b/internal/projectconfig/govendor.go new file mode 100644 index 000000000..05053c126 --- /dev/null +++ b/internal/projectconfig/govendor.go @@ -0,0 +1,123 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package projectconfig + +import ( + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "strings" + + "github.com/microsoft/azure-linux-dev-tools/internal/global/opctx" + "github.com/microsoft/azure-linux-dev-tools/internal/utils/fileutils" + "github.com/pelletier/go-toml/v2" +) + +// HasGoVendorSources reports whether source preparation must generate a vendor archive. +func (c *ComponentConfig) HasGoVendorSources() bool { + for _, ref := range c.SourceFiles { + if ref.Origin.Type == OriginTypeGoVendor { + return true + } + } + + return false +} + +// VendorConfig reads explicit native settings without modifying their contents. +// An omitted file reuses upstream settings; an explicit empty file replaces them. +func (o Origin) VendorConfig(fs opctx.FS) (string, error) { + data, err := fileutils.ReadFile(fs, o.ConfigFile) + if err != nil { + return "", fmt.Errorf("reading Go vendor configuration %#q:\n%w", o.ConfigFile, err) + } + + var config map[string]any + if err := toml.Unmarshal(data, &config); err != nil { + return "", fmt.Errorf("parsing Go vendor configuration %#q:\n%w", o.ConfigFile, err) + } + + return string(data), nil +} + +// VendorIdentity fingerprints native settings and the generated-origin policy. +func (o Origin) VendorIdentity(fs opctx.FS) (string, error) { + if o.Type != OriginTypeGoVendor { + return "", nil + } + + if o.ConfigFile == "" { + return "go-vendor:upstream", nil + } + + content, err := o.VendorConfig(fs) + if err != nil { + return "", err + } + + hash := sha256.Sum256([]byte(content)) + + return "go-vendor:" + hex.EncodeToString(hash[:]), nil +} + +func validateGoVendorOrigin(origin Origin) error { + if origin.Type != OriginTypeGoVendor { + if origin.ConfigFile != "" || origin.ModuleDir != "" || len(origin.PrepPackages) != 0 { + return errors.New("'config-file', 'module-dir' and 'prep-packages' require 'origin.type = go-vendor'") + } + + return nil + } + + if strings.ContainsAny(origin.ConfigFile, "\x00\r\n") { + return errors.New("invalid Go vendor 'config-file' path") + } + + if origin.ModuleDir != "" { + if err := fileutils.ValidateRelPath(origin.ModuleDir); err != nil { + return fmt.Errorf("invalid Go vendor 'module-dir':\n%w", err) + } + + if strings.ContainsAny(origin.ModuleDir, "%\r\n") { + return errors.New("go vendor 'module-dir' must not contain macros or newlines") + } + } + + for _, pkg := range origin.PrepPackages { + if pkg == "" || strings.HasPrefix(pkg, "-") || strings.ContainsAny(pkg, "\r\n") { + return fmt.Errorf("invalid Go vendor prep package %#q", pkg) + } + } + + return nil +} + +func validateVendorSourceCount(refs []SourceFileReference) error { + count := 0 + + for _, ref := range refs { + if ref.Origin.Type == OriginTypeGoVendor { + count++ + } + } + + if count > 1 { + return errors.New("only one 'go-vendor' source per component is supported") + } + + return nil +} + +func validateSourceFilename(ref SourceFileReference) error { + if ref.Origin.Type == OriginTypeGoVendor && strings.Contains(ref.Filename, "%") { + return errors.New("vendor filename must not contain RPM macros") + } + + if err := fileutils.ValidateFilename(ref.Filename); err != nil { + return fmt.Errorf("validating source basename:\n%w", err) + } + + return nil +} diff --git a/internal/projectconfig/govendor_test.go b/internal/projectconfig/govendor_test.go new file mode 100644 index 000000000..9174cec58 --- /dev/null +++ b/internal/projectconfig/govendor_test.go @@ -0,0 +1,94 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package projectconfig_test + +import ( + "testing" + + "github.com/microsoft/azure-linux-dev-tools/internal/fingerprint" + "github.com/microsoft/azure-linux-dev-tools/internal/global/testctx" + "github.com/microsoft/azure-linux-dev-tools/internal/projectconfig" + "github.com/microsoft/azure-linux-dev-tools/internal/utils/fileperms" + "github.com/microsoft/azure-linux-dev-tools/internal/utils/fileutils" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestGoVendorOriginValidation(t *testing.T) { + for name, ref := range map[string]projectconfig.SourceFileReference{ + "explicit": {Filename: "vendor.tar.bz2", Origin: projectconfig.Origin{ + Type: projectconfig.OriginTypeGoVendor, + ConfigFile: "vendor.toml", ModuleDir: "cmd/app", PrepPackages: []string{"patch"}, + }}, + } { + t.Run(name, func(t *testing.T) { + file := projectconfig.ConfigFile{Components: map[string]projectconfig.ComponentConfig{ + "app": {SourceFiles: []projectconfig.SourceFileReference{ref}}, + }} + require.NoError(t, file.Validate()) + }) + } + + missing := projectconfig.ConfigFile{Components: map[string]projectconfig.ComponentConfig{ + "app": {SourceFiles: []projectconfig.SourceFileReference{ + {Origin: projectconfig.Origin{Type: projectconfig.OriginTypeGoVendor}}, + }}, + }} + require.ErrorContains(t, missing.Validate(), "filename") + + for name, origin := range map[string]projectconfig.Origin{ + "traversal": {Type: projectconfig.OriginTypeGoVendor, ModuleDir: "../bad"}, + "package": {Type: projectconfig.OriginTypeGoVendor, PrepPackages: []string{"--bad"}}, + "uri": {Type: projectconfig.OriginTypeGoVendor, Uri: "https://example.com"}, + "wrong origin": {Type: projectconfig.OriginTypeURI, Uri: "https://example.com", ConfigFile: "vendor.toml"}, + } { + t.Run(name, func(t *testing.T) { + file := projectconfig.ConfigFile{Components: map[string]projectconfig.ComponentConfig{ + "app": {SourceFiles: []projectconfig.SourceFileReference{{Filename: "vendor.tar.gz", Origin: origin}}}, + }} + require.Error(t, file.Validate()) + }) + } +} + +func TestGoVendorSourceCountAfterInheritance(t *testing.T) { + ref := projectconfig.SourceFileReference{Origin: projectconfig.Origin{Type: projectconfig.OriginTypeGoVendor}} + group := projectconfig.ComponentConfig{SourceFiles: []projectconfig.SourceFileReference{ref}} + groups := map[string]projectconfig.ComponentGroupConfig{"group": {DefaultComponentConfig: group}} + comp := projectconfig.ComponentConfig{Name: "app"} + empty := projectconfig.ComponentConfig{} + _, err := projectconfig.ResolveComponentConfig(comp, empty, empty, groups, []string{"group"}) + require.NoError(t, err) + + ref.Filename = "second.tar.gz" + comp.SourceFiles = []projectconfig.SourceFileReference{ref} + _, err = projectconfig.ResolveComponentConfig(comp, empty, empty, groups, []string{"group"}) + require.ErrorContains(t, err, "only one 'go-vendor' source") +} + +func TestGoVendorSettingsFingerprint(t *testing.T) { + ctx := testctx.NewCtx() + config := projectconfig.ComponentConfig{SourceFiles: []projectconfig.SourceFileReference{{ + Origin: projectconfig.Origin{Type: projectconfig.OriginTypeGoVendor, ConfigFile: "vendor.toml"}, + }}} + resolved := config.WithAbsolutePaths("/project") + assert.Equal(t, "/project/vendor.toml", resolved.SourceFiles[0].Origin.ConfigFile) + assert.Equal(t, "vendor.toml", config.SourceFiles[0].Origin.ConfigFile) + + for _, path := range []string{"/project/vendor.toml", "/elsewhere/vendor.toml"} { + require.NoError(t, fileutils.WriteFile(ctx.FS(), path, []byte("[archive]\ntidy = false\n"), fileperms.PublicFile)) + } + + first, err := fingerprint.ComputeIdentity(ctx.FS(), *resolved, "", fingerprint.IdentityOptions{}) + require.NoError(t, err) + + relocated := config.WithAbsolutePaths("/elsewhere") + second, err := fingerprint.ComputeIdentity(ctx.FS(), *relocated, "", fingerprint.IdentityOptions{}) + require.NoError(t, err) + assert.Equal(t, first.Fingerprint, second.Fingerprint) + require.NoError(t, fileutils.WriteFile(ctx.FS(), "/project/vendor.toml", []byte(""), fileperms.PublicFile)) + third, err := fingerprint.ComputeIdentity(ctx.FS(), *resolved, "", fingerprint.IdentityOptions{}) + require.NoError(t, err) + assert.NotEqual(t, first.Fingerprint, third.Fingerprint) +} diff --git a/internal/providers/sourceproviders/sourcemanager.go b/internal/providers/sourceproviders/sourcemanager.go index 4bf07d45a..11aff1d43 100644 --- a/internal/providers/sourceproviders/sourcemanager.go +++ b/internal/providers/sourceproviders/sourcemanager.go @@ -343,6 +343,9 @@ func (m *sourceManager) FetchFiles( for i := range sourceFiles { fileRef := &sourceFiles[i] + if fileRef.Origin.Type == projectconfig.OriginTypeGoVendor { + continue // Generation requires the patched prep tree, not the fetched tree. + } // Fail fast when a 'custom' origin source file has no registered provider. // This means the distro has no 'mock-config' set (or the file was inaccessible), @@ -557,7 +560,7 @@ func (m *sourceManager) fetchFromDownloadOrigin( "ensure the distro has a 'mock-config' configured", fileRef.Filename) - case projectconfig.OriginTypeOverlay: + case projectconfig.OriginTypeOverlay, projectconfig.OriginTypeGoVendor: // Overlay-origin files are skipped before reaching this point in fetchSourceFile. // This case should never be reached. return fmt.Errorf("internal error: download attempted for 'overlay'-origin source file %#q", diff --git a/internal/rpm/spec/vendorprep.go b/internal/rpm/spec/vendorprep.go new file mode 100644 index 000000000..50361ee45 --- /dev/null +++ b/internal/rpm/spec/vendorprep.go @@ -0,0 +1,209 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package spec + +import ( + "errors" + "fmt" + "regexp" + "slices" + "strings" + + "github.com/microsoft/azure-linux-dev-tools/internal/utils/fileutils" +) + +// VendorPrep describes a private prep spec, never a replacement published spec. +type VendorPrep struct { + Spec []byte + ConfigName string +} + +var ( + vendorExtraction = regexp.MustCompile(`^tar\s+-xf\s+%\{(?:S:|SOURCE)([0-9]+)\}\s*$`) + vendorConfigRef = regexp.MustCompile(`^%go_vendor_license_\w+\s+-c\s+%\{(?:S:|SOURCE)([0-9]+)\}\s*$`) + secondarySetup = regexp.MustCompile(`%(?:\{[!?]*)?(?:(?:auto)?setup|goprep)\b.*\s-[a-zA-Z]*[ab]`) + knownPrepMacro = regexp.MustCompile(`^%(?:setup|autosetup|goprep|autopatch|patch[0-9]*)(?:\s|$)`) +) + +// PrepareVendorSource removes only the selected vendor input from private prep. +// The caller remains responsible for the original spec's archive consumption. +func PrepareVendorSource(data []byte, filename string) (*VendorPrep, error) { + if err := fileutils.ValidateFilename(filename); err != nil { + return nil, fmt.Errorf("validating vendor filename:\n%w", err) + } + + if strings.ContainsAny(filename, "%\r\n") { + return nil, errors.New("vendor 'filename' must be a basename without RPM macros or newlines") + } + + root, err := parseTree(strings.Split(strings.TrimSuffix(string(data), "\n"), "\n")) + if err != nil { + return nil, err + } + + tree := &specTree{root: root} + + prep := tree.Section("%prep", "") + if prep == nil || !slices.Contains(root.Children, prep.block) { + return nil, errors.New("go vendor generation requires an unconditional '%prep' section") + } + + sources, configNumber, err := vendorSourceTags(tree) + if err != nil { + return nil, err + } + + candidates, err := vendorExtractions(prep, sources) + if err != nil { + return nil, err + } + + number, err := selectVendorSource(sources, candidates, filename) + if err != nil { + return nil, err + } + + if err := removeVendorInput(tree, number); err != nil { + return nil, err + } + + configName := sources[configNumber] + if configName != "" { + if err := fileutils.ValidateFilename(configName); err != nil || strings.Contains(configName, "%") { + return nil, errors.New("vendor config Source must name a plain sidecar file") + } + } + + if number != "" { + prep.AppendLines([]string{"test %{shescape:" + sources[number] + "} = %{shescape:" + filename + "}"}) + } + + prep.AppendLines([]string{`pwd -P > "%{_topdir}/azldev-vendor-root"`}) + + return &VendorPrep{ + Spec: []byte(strings.Join(serializeTree(root), "\n") + "\n"), + ConfigName: configName, + }, nil +} + +func vendorSourceTags(tree *specTree) (sources map[string]string, configNumber string, err error) { + sources = map[string]string{} + err = tree.VisitAllLines(func(section, pkg string, line *lineHandle) error { + tag, value, ok := parseTagLine(line.Text) + if ok && section == "" && pkg == "" && strings.HasPrefix(strings.ToLower(tag), "source") { + number := strings.TrimPrefix(strings.ToLower(tag), "source") + if number == "" { + number = "0" + } + + if _, duplicate := sources[number]; duplicate || !slices.Contains(tree.Section("", "").block.Children, line.block) { + return fmt.Errorf("ambiguous vendor source declaration %#q", tag) + } + + sources[number] = value + } + + matches := vendorConfigRef.FindStringSubmatch(strings.TrimSpace(line.Text)) + if len(matches) != 0 { + if configNumber != "" && configNumber != matches[1] { + return errors.New("vendor license macros reference different configuration files") + } + + configNumber = matches[1] + } + + return nil + }) + + return sources, configNumber, err +} + +func vendorExtractions(prep *sectionHandle, sources map[string]string) ([]string, error) { + var candidates []string + + err := prep.VisitLines(func(line *lineHandle) error { + text := strings.TrimSpace(line.Text) + if strings.HasPrefix(text, "#") { + return nil + } + + if secondarySetup.MatchString(text) { + return errors.New("secondary setup extraction requires an explicit prep overlay for vendor generation") + } + + if strings.HasPrefix(text, "%") && !knownPrepMacro.MatchString(text) { + return fmt.Errorf("opaque vendor prep macro %#q; make extraction explicit", text) + } + + match := vendorExtraction.FindStringSubmatch(text) + if len(match) != 0 && match[1] != "0" { + if !slices.Contains(prep.block.Children, line.block) { + return errors.New("conditional vendor extraction is unsupported") + } + + if sources[match[1]] == "" { + return errors.New("vendor extraction references a missing Source") + } + + candidates = append(candidates, match[1]) + } else if strings.HasPrefix(text, "tar ") && strings.Contains(text, "%{S") { + return fmt.Errorf("unsupported source extraction %#q; use a simple 'tar -xf' prep overlay", text) + } + + return nil + }) + + return candidates, err +} + +func selectVendorSource( + sources map[string]string, candidates []string, filename string, +) (string, error) { + if len(candidates) > 1 { + return "", errors.New("ambiguous vendor extraction; simplify prep with an overlay") + } + + if len(candidates) == 0 { + return vendorSourceWithFilename(sources, filename) + } + + number := candidates[0] + if !strings.Contains(sources[number], "%") && sources[number] != filename { + return "", errors.New("configured vendor filename does not match the extracted Source") + } + + return number, nil +} + +func vendorSourceWithFilename(sources map[string]string, filename string) (string, error) { + number := "" + + for key, value := range sources { + if value == filename { + if key == "0" || number != "" { + return "", errors.New("vendor output must select a unique Source other than Source0") + } + + number = key + } + } + + return number, nil +} + +func removeVendorInput(tree *specTree, number string) error { + return tree.VisitAllLines(func(section, pkg string, line *lineHandle) error { + tag, _, ok := parseTagLine(line.Text) + if number != "" && ok && section == "" && pkg == "" && strings.EqualFold(tag, "Source"+number) { + line.Remove() + } + + match := vendorExtraction.FindStringSubmatch(strings.TrimSpace(line.Text)) + if section == "%prep" && len(match) != 0 && match[1] == number { + line.Remove() + } + + return nil + }) +} diff --git a/internal/rpm/spec/vendorprep_test.go b/internal/rpm/spec/vendorprep_test.go new file mode 100644 index 000000000..e8006a66c --- /dev/null +++ b/internal/rpm/spec/vendorprep_test.go @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package spec_test + +import ( + "strings" + "testing" + + "github.com/microsoft/azure-linux-dev-tools/internal/rpm/spec" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func vendorSpec() string { + return strings.Join([]string{ + "Name: app", "Version: 1", "Release: 1", "License: MIT", + "Source0: app.tar.gz", "Source5: app-%{version}-vendor.tar.bz2", "Source8: go-vendor-tools.toml", + "%description", "App", "%prep", "%autosetup -p1", + "tar -xf %{S:5}", "sed -i s/old/new/ go.mod", + "%build", "make build", "%install", "%go_vendor_license_install -c %{S:8}", + "%files", "/usr/bin/app", "", + }, "\n") +} + +func TestPrepareVendorSource(t *testing.T) { + input := vendorSpec() + plan, err := spec.PrepareVendorSource([]byte(input), "app-1-vendor.tar.bz2") + require.NoError(t, err) + assert.Equal(t, "go-vendor-tools.toml", plan.ConfigName) + assert.NotContains(t, string(plan.Spec), "Source5:") + assert.NotContains(t, string(plan.Spec), "tar -xf %{S:5}") + assert.Contains(t, string(plan.Spec), "Source0: app.tar.gz") + assert.Contains(t, string(plan.Spec), "sed -i s/old/new/ go.mod") + assert.Contains(t, string(plan.Spec), "%{shescape:app-%{version}-vendor.tar.bz2}") +} + +func TestPrepareVendorSourceRejectsAmbiguity(t *testing.T) { + for name, input := range map[string]string{ + "missing prep": strings.ReplaceAll(vendorSpec(), "%prep", "%check"), + "multiple": strings.ReplaceAll(vendorSpec(), "tar -xf %{S:5}", "tar -xf %{S:5}\ntar -xf %{S:8}"), + "secondary": strings.ReplaceAll(vendorSpec(), "%autosetup -p1", "%autosetup -a 5"), + "conditional": strings.ReplaceAll(vendorSpec(), "tar -xf %{S:5}", "%if 1\ntar -xf %{S:5}\n%endif"), + "flags": strings.ReplaceAll(vendorSpec(), "tar -xf", "tar -xjf"), + "opaque prep macro": strings.ReplaceAll(vendorSpec(), "%autosetup -p1", "%unpack_secondary"), + "braced prep macro": strings.ReplaceAll(vendorSpec(), "%autosetup -p1", "%{unpack_secondary}"), + "missing source": strings.ReplaceAll(vendorSpec(), "%{S:5}", "%{S:6}"), + "conditional source": strings.ReplaceAll(vendorSpec(), "Source5: app-%{version}-vendor.tar.bz2", + "%if 1\nSource5: app-%{version}-vendor.tar.bz2\n%endif"), + "duplicate source": strings.ReplaceAll(vendorSpec(), "Source5:", "Source0:"), + "config macro": strings.ReplaceAll(vendorSpec(), "go-vendor-tools.toml", "%{name}.toml"), + "conflicting config": strings.ReplaceAll(vendorSpec(), "%files", + "%go_vendor_license_check -c %{S:1}\n%files"), + } { + t.Run(name, func(t *testing.T) { + _, err := spec.PrepareVendorSource([]byte(input), "vendor.tar.bz2") + require.Error(t, err) + }) + } + + for _, name := range []string{"", "../outside.tar.gz", "%{name}.tar.gz", "bad\nname"} { + _, err := spec.PrepareVendorSource([]byte(vendorSpec()), name) + require.Error(t, err) + } + + plan, err := spec.PrepareVendorSource([]byte(vendorSpec()), "different.tar.bz2") + require.NoError(t, err) + assert.Contains(t, string(plan.Spec), "test %{shescape:app-%{version}-vendor.tar.bz2} = %{shescape:different.tar.bz2}") +} diff --git a/scenario/__snapshots__/TestSnapshotsContainer_config_generate-schema_stdout_1.snap b/scenario/__snapshots__/TestSnapshotsContainer_config_generate-schema_stdout_1.snap index 9cf47bd35..300f70605 100755 --- a/scenario/__snapshots__/TestSnapshotsContainer_config_generate-schema_stdout_1.snap +++ b/scenario/__snapshots__/TestSnapshotsContainer_config_generate-schema_stdout_1.snap @@ -846,7 +846,8 @@ "enum": [ "download", "custom", - "overlay" + "overlay", + "go-vendor" ], "title": "Origin type", "description": "Type of origin for this source file" @@ -879,6 +880,24 @@ "type": "array", "title": "Inputs", "description": "Source-output filenames to make available next to the generation script before it runs. Only valid when origin type is 'custom'." + }, + "config-file": { + "type": "string", + "title": "Vendor configuration file", + "description": "Native go-vendor-tools TOML relative to the declaring config. Only valid for go-vendor." + }, + "module-dir": { + "type": "string", + "title": "Module directory", + "description": "Module directory relative to the prepared source root. Only valid for go-vendor." + }, + "prep-packages": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Prep packages", + "description": "Additional RPM packages for private prep. Only valid for go-vendor." } }, "additionalProperties": false, @@ -1332,7 +1351,8 @@ "SourceFileReference": { "properties": { "filename": { - "type": "string" + "type": "string", + "description": "Source file basename." }, "hash": { "type": "string" diff --git a/scenario/__snapshots__/TestSnapshots_config_generate-schema_stdout_1.snap b/scenario/__snapshots__/TestSnapshots_config_generate-schema_stdout_1.snap index 9cf47bd35..300f70605 100755 --- a/scenario/__snapshots__/TestSnapshots_config_generate-schema_stdout_1.snap +++ b/scenario/__snapshots__/TestSnapshots_config_generate-schema_stdout_1.snap @@ -846,7 +846,8 @@ "enum": [ "download", "custom", - "overlay" + "overlay", + "go-vendor" ], "title": "Origin type", "description": "Type of origin for this source file" @@ -879,6 +880,24 @@ "type": "array", "title": "Inputs", "description": "Source-output filenames to make available next to the generation script before it runs. Only valid when origin type is 'custom'." + }, + "config-file": { + "type": "string", + "title": "Vendor configuration file", + "description": "Native go-vendor-tools TOML relative to the declaring config. Only valid for go-vendor." + }, + "module-dir": { + "type": "string", + "title": "Module directory", + "description": "Module directory relative to the prepared source root. Only valid for go-vendor." + }, + "prep-packages": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Prep packages", + "description": "Additional RPM packages for private prep. Only valid for go-vendor." } }, "additionalProperties": false, @@ -1332,7 +1351,8 @@ "SourceFileReference": { "properties": { "filename": { - "type": "string" + "type": "string", + "description": "Source file basename." }, "hash": { "type": "string" diff --git a/schemas/azldev.schema.json b/schemas/azldev.schema.json index 9cf47bd35..300f70605 100644 --- a/schemas/azldev.schema.json +++ b/schemas/azldev.schema.json @@ -846,7 +846,8 @@ "enum": [ "download", "custom", - "overlay" + "overlay", + "go-vendor" ], "title": "Origin type", "description": "Type of origin for this source file" @@ -879,6 +880,24 @@ "type": "array", "title": "Inputs", "description": "Source-output filenames to make available next to the generation script before it runs. Only valid when origin type is 'custom'." + }, + "config-file": { + "type": "string", + "title": "Vendor configuration file", + "description": "Native go-vendor-tools TOML relative to the declaring config. Only valid for go-vendor." + }, + "module-dir": { + "type": "string", + "title": "Module directory", + "description": "Module directory relative to the prepared source root. Only valid for go-vendor." + }, + "prep-packages": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Prep packages", + "description": "Additional RPM packages for private prep. Only valid for go-vendor." } }, "additionalProperties": false, @@ -1332,7 +1351,8 @@ "SourceFileReference": { "properties": { "filename": { - "type": "string" + "type": "string", + "description": "Source file basename." }, "hash": { "type": "string"