From 5605e954d8f4c8720bc451c59f9a40395c7af530 Mon Sep 17 00:00:00 2001 From: Antonio Salinas <173939267+Tonisal-byte@users.noreply.github.com> Date: Sat, 31 Oct 2026 13:32:00 -0700 Subject: [PATCH 01/16] feat: add declarative Go vendor source preparation Preserve upstream packaging while converting supported Go application specs and generating vendor archives from prepared sources. Wire configuration, history, documentation, and regression coverage across preparation, builds, rendering, and source diffs. Validation: ./magefile.go check all passed, including Python lint and type checks. Build and unit phases passed. Full ./magefile.go all was attempted via Podman, but Docker-oriented scenario file-mount and network-isolation expectations fail in this environment; Docker WSL integration is unavailable. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/user/how-to/vendor-go-application.md | 92 +++++ .../cli/azldev_component_prepare-sources.md | 4 +- docs/user/reference/config/components.md | 46 +++ .../app/azldev/agentskill/agentskill_test.go | 11 + .../agentskill/content/comp-toml.md.tmpl | 17 + .../content/withoutlockfile/comp-toml.md.tmpl | 17 + internal/app/azldev/cmds/component/build.go | 2 +- .../app/azldev/cmds/component/diffsources.go | 2 +- .../cmds/component/history_customizations.go | 25 ++ .../cmds/component/history_internal_test.go | 6 + .../app/azldev/cmds/component/preparerctx.go | 26 ++ .../component/preparerctx_internal_test.go | 64 +++ .../azldev/cmds/component/preparesources.go | 14 +- internal/app/azldev/cmds/component/render.go | 6 +- .../azldev/cmds/component/sourcepreparer.go | 19 +- internal/app/azldev/core/sources/govendor.go | 373 ++++++++++++++++++ .../core/sources/govendor_internal_test.go | 244 ++++++++++++ .../app/azldev/core/sources/sourceprep.go | 38 +- internal/projectconfig/component.go | 23 ++ internal/projectconfig/configfile.go | 4 + internal/projectconfig/fingerprint_test.go | 1 + internal/projectconfig/govendor.go | 66 ++++ internal/projectconfig/govendor_test.go | 80 ++++ internal/rpm/spec/govendor.go | 322 +++++++++++++++ internal/rpm/spec/govendor_test.go | 197 +++++++++ ...shots_config_generate-schema_stdout_1.snap | 34 ++ schemas/azldev.schema.json | 34 ++ 27 files changed, 1750 insertions(+), 17 deletions(-) create mode 100644 docs/user/how-to/vendor-go-application.md create mode 100644 internal/app/azldev/cmds/component/preparerctx_internal_test.go create mode 100644 internal/app/azldev/core/sources/govendor.go create mode 100644 internal/app/azldev/core/sources/govendor_internal_test.go create mode 100644 internal/projectconfig/govendor.go create mode 100644 internal/projectconfig/govendor_test.go create mode 100644 internal/rpm/spec/govendor.go create mode 100644 internal/rpm/spec/govendor_test.go 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..c0b430642 --- /dev/null +++ b/docs/user/how-to/vendor-go-application.md @@ -0,0 +1,92 @@ +# Vendor a Go application + +Use `go-vendor` to bundle a Go application's module dependencies instead of +building against separately packaged `golang(...)` libraries. This is a targeted +conversion of the selected upstream spec, not a `go2rpm` wrapper or a newly +generated replacement spec. + +## Enable and prepare + +Add this to the component definition: + +```toml +[components.example.go-vendor] +enabled = true +``` + +Then prepare the complete build inputs: + +```sh +azldev component prepare-sources -p example -o prepared-example --without-git +``` + +The project/build distro must have a working mock configuration and provide +`go-vendor-tools`, `askalono-cli`, `golang`, `go-rpm-macros`, `rpm-build`, and +`rpmdevtools`, `rpmautospec`, `git`, and `python3-click`. These are installed in a +fresh, network-enabled generation chroot; +neither `go2rpm` nor the Go vendor tools are required on the host. Configure +`prep-packages` for additional tools required by upstream prep scripts. + +The pipeline fetches the selected upstream sources, applies overlays, and copies +them into isolated staging. It processes automatic release/changelog metadata +there and runs the existing `%prep` section with `rpmbuild -bp --nodeps`. +This retains upstream patches and edits to module files. It then calls +`go_vendor_archive create` on the prepared module tree, extracts the result for +license detection, and runs `go_vendor_license` without interactive prompts. +Unrecognized licenses fail preparation; add reviewed, hash-qualified exceptions +to `tool-config` rather than suppressing detection. + +The output includes the converted spec, all its original sources and patches, +`-vendor.tar.bz2`, and `azldev-go-vendor.toml`. The archive is recorded +with SHA-512 in `sources` and excluded from synthetic git commits with `.gitignore`. +The upstream release/changelog is retained; ordinary azldev release handling +still applies afterwards. + +## What is converted + +The converter removes standalone `BuildRequires: golang(import/path)` tags, +including version constraints, and bare `%go_generate_buildrequires` invocations. +It changes a bare `%gocheck` to `%gotest ./...`, adds vendor extraction at the end +of `%prep`, and enables module/vendor mode for subsequent build scripts. +It adds the Go compiler/macros and vendor tooling build requirements, dynamic +license backend requirements, license installation/file-list handling, and a +license check in `%build` so disabling `%check` does not bypass license validation. +The main `License:` tag is updated to the detected cumulative SPDX expression. + +Unrelated runtime dependencies, C-library build dependencies, custom commands, +patches, metadata, and ordinary subpackages are retained. Go vendoring does not +eliminate dependencies on shared libraries used by cgo. + +The initial supported scope is application specs with one unconditional +main-package `%prep`, `%build`, `%install`, and `%files` section. The prep section +must finish in the module root, or use `module-dir` for a relative subdirectory. +Custom build/install commands must already address that same module. Conditional +commands within those sections are retained. + +Automatic Go development subpackages (`%gopkg`, `%goinstall`, Go file-list macros), +flagged `%gocheck` commands, compound/rich Go BuildRequires, existing vendor +macros, explicit conflicting module-mode settings, and ambiguous/conditional +target sections are rejected. Use narrowly scoped overlays to adapt these cases; +azldev does not silently drop subpackages or rewrite arbitrary shell scripts. + +## Review and upgrade + +Run `azldev component diff-sources -p example` to inspect the conversion, or +`azldev component render -p example` to refresh checked-in rendered output. +Rendering and source diffs also generate the archive: they need network access and +can be substantially slower for enabled components. + +Review the cumulative license expression and the retained build/install/check +commands before building. Automatic detection is not approval of a dependency's +license. The converter sets `GO111MODULE=on`, `-mod=vendor`, `GOPROXY=off`, +`GOSUMDB=off`, and `GOTOOLCHAIN=local` for build scripts; custom commands must not +override these settings to download dependencies. + +The same TOML applies after an upstream version update: no archive version, +import path, Source number, or spec line number is embedded in the declaration. +Generation reruns against the newly selected and patched inputs. Review changed +vendor hashes and licenses; an upstream packaging change may require updating +an overlay or resolving a newly unsupported construct. + +See [Go vendoring configuration](../reference/config/components.md#go-vendoring) +for module layout, dependency overrides, and license exceptions. diff --git a/docs/user/reference/cli/azldev_component_prepare-sources.md b/docs/user/reference/cli/azldev_component_prepare-sources.md index 45f9f8cb7..b133f34c5 100644 --- a/docs/user/reference/cli/azldev_component_prepare-sources.md +++ b/docs/user/reference/cli/azldev_component_prepare-sources.md @@ -41,8 +41,8 @@ azldev component prepare-sources [flags] -o, --output-dir string output directory --rpmdev-bumpspec Use rpmdev-bumpspec instead of the legacy static release calculation --skip-lock-validation skip lock file consistency checks - --skip-overlays skip applying overlays to prepared sources - --skip-sources skip downloading fetched sources when preparing the package (useful to extract dist-git metadata when source files are not needed) + --skip-overlays skip overlays and Go vendor conversion, preserving upstream packaging + --skip-sources skip downloading sources unless Go vendor conversion requires them -s, --spec-path stringArray Spec path --without-git Disable dist-git repository creation (enabled by default) ``` diff --git a/docs/user/reference/config/components.md b/docs/user/reference/config/components.md index ce06e6f60..33b7cbf8d 100644 --- a/docs/user/reference/config/components.md +++ b/docs/user/reference/config/components.md @@ -15,6 +15,7 @@ A component definition tells azldev where to find the spec file, how to customiz | Build config | `build` | [BuildConfig](#build-configuration) | No | Build-time options (macros, conditionals, check config) | | Render config | `render` | [RenderConfig](#render-configuration) | No | Options controlling spec rendering behavior | | Source files | `source-files` | array of [SourceFileReference](#source-file-references) | No | Additional source files to download for this component | +| Go vendoring | `go-vendor` | [GoVendorConfig](#go-vendoring) | No | Convert a supported Go application spec in place and generate bundled dependencies | | Package overrides | `packages` | map of string → [PackageConfig](package-groups.md#package-config) | No | Exact per-package configuration overrides; highest priority in the resolution order | | Tests | `tests` | [ComponentTests](#component-tests) | No | Test references that apply to this component (see [Tests and Test Groups](tests.md)) | @@ -165,6 +166,51 @@ skip-file-filter = true > **Note:** This should only be used for specs with macros that `spectool` cannot resolve. For most components, the default filtering behavior is correct and keeps the rendered output clean. +## Go Vendoring + +Go vendoring is opt-in and preserves the upstream spec rather than replacing it +with a generated spec. See [Vendor a Go application](../../how-to/vendor-go-application.md) +for the workflow and supported spec patterns. + +```toml +[components.example.go-vendor] +enabled = true +``` + +| TOML Key | Type | Default | Description | +|----------|------|---------|-------------| +| `enabled` | boolean | `false` | Enable conversion and vendor archive generation. An explicit `false` overrides inherited enablement. | +| `module-dir` | string | `""` | Relative directory containing `go.mod`, resolved from the working directory at the end of the upstream `%prep` section. Empty uses that directory itself. No absolute paths, traversal, or RPM macros. | +| `prep-packages` | array of string | `[]` | Additional RPM packages needed by upstream `%prep` commands or the selected license detector. Installed only in the isolated generation chroot. | +| `tool-config` | string | `""` | Inline [go-vendor-tools TOML](https://fedora.gitlab.io/sigs/go/go-vendor-tools/config/), for dependency overrides, archive options, and reviewed license exceptions. Use `module-dir`, not `general.go_mod_dir`. | + +The tool configuration is inline so its contents participate in component +fingerprinting without checkout-dependent paths. Configured command hooks execute +in the generation chroot; treat this configuration as trusted build code. + +```toml +[components.example.go-vendor] +enabled = true +prep-packages = ["git"] +tool-config = ''' +[archive.dependency_overrides] +"example.com/dependency" = "v1.2.3" +''' +``` + +Preparation emits `-vendor.tar.bz2` and `azldev-go-vendor.toml`, +allocating unused `Source` numbers automatically. These names are reserved for +generated output; do not also declare them in `source-files` or supply them through +overlays. The archive's SHA-512 digest is recorded in the prepared `sources` file. +Generation runs afresh on every preparation; there is no filename-based cache. +The recorded digest identifies that output, not a separately pinned vendor lock. + +All archive/spec/loose-file overlays run before conversion. Source preparation, +builds, rendering (including `--check-only`), and source diffs use the same +conversion. Enabled components require downloads even with `--skip-sources`, +because preparation and license detection need the effective upstream sources. +`--skip-overlays` also skips conversion, leaving the upstream packaging unchanged. + ## Build Configuration The `[components..build]` section controls build-time options for a component. diff --git a/internal/app/azldev/agentskill/agentskill_test.go b/internal/app/azldev/agentskill/agentskill_test.go index a263a100f..7ebe18bdf 100644 --- a/internal/app/azldev/agentskill/agentskill_test.go +++ b/internal/app/azldev/agentskill/agentskill_test.go @@ -160,6 +160,17 @@ func TestComponentTomlSkillDocumentsRPMDevBumpspecPreview(t *testing.T) { assert.Contains(t, doc, "no bumpspec runtime discovery occurs") } +func TestComponentTomlSkillDocumentsGoVendoring(t *testing.T) { + for _, withoutLockfile := range []bool{false, true} { + doc, err := agentskill.NewCatalog(withoutLockfile).SkillDocument("azldev-comp-toml", testParams()) + require.NoError(t, err) + assert.Contains(t, doc, "go-vendor.enabled") + assert.Contains(t, doc, "does\nnot run `go2rpm`") + assert.Contains(t, doc, "Rendering and source diffs also generate") + assert.Contains(t, doc, "reviewed license exceptions") + } +} + 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..1462c24c3 100644 --- a/internal/app/azldev/agentskill/content/comp-toml.md.tmpl +++ b/internal/app/azldev/agentskill/content/comp-toml.md.tmpl @@ -32,6 +32,23 @@ Add sub-tables only for what you change. The fields you will reach for most: | `build.defines` / `build.with` / `build.without` | RPM macro and bcond build tweaks | | `release.calculation` | how the `Release` tag is managed | | `render.skip-file-filter` | rendering edge-case escape hatch | +| `go-vendor.enabled` | opt-in Go application spec conversion and vendor archive generation | + +## Go application vendoring + +Set `[components..go-vendor]` with `enabled = true` to preserve the upstream +spec while converting supported application packaging to bundled modules. +Preparation runs the patched upstream `%prep` before `go_vendor_archive`; it does +not run `go2rpm`. Rendering and source diffs also generate the vendor archive and +require downloads. Review the generated cumulative `License:` expression. + +Use `module-dir` for a module below the final prep working directory, +`prep-packages` for additional chroot tools, and inline `tool-config` for +go-vendor-tools dependency overrides or reviewed license exceptions. +Generated `-vendor.tar.bz2` and `azldev-go-vendor.toml` must not also be +declared as `source-files`. Unsupported constructs (notably automatic Go devel +subpackages, flagged `%gocheck`, or ambiguous sections) require explicit overlays; +never replace the upstream spec wholesale to bypass a conversion error. ## Spec source 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..c1f972f5d 100644 --- a/internal/app/azldev/agentskill/content/withoutlockfile/comp-toml.md.tmpl +++ b/internal/app/azldev/agentskill/content/withoutlockfile/comp-toml.md.tmpl @@ -32,6 +32,23 @@ Add sub-tables only for what you change. The fields you will reach for most: | `build.defines` / `build.with` / `build.without` | RPM macro and bcond build tweaks | | `release.calculation` | how the `Release` tag is managed | | `render.skip-file-filter` | rendering edge-case escape hatch | +| `go-vendor.enabled` | opt-in Go application spec conversion and vendor archive generation | + +## Go application vendoring + +Set `[components..go-vendor]` with `enabled = true` to preserve the upstream +spec while converting supported application packaging to bundled modules. +Preparation runs the patched upstream `%prep` before `go_vendor_archive`; it does +not run `go2rpm`. Rendering and source diffs also generate the vendor archive and +require downloads. Review the generated cumulative `License:` expression. + +Use `module-dir` for a module below the final prep working directory, +`prep-packages` for additional chroot tools, and inline `tool-config` for +go-vendor-tools dependency overrides or reviewed license exceptions. +Generated `-vendor.tar.bz2` and `azldev-go-vendor.toml` must not also be +declared as `source-files`. Unsupported constructs (notably automatic Go devel +subpackages, flagged `%gocheck`, or ambiguous sections) require explicit overlays; +never replace the upstream spec wholesale to bypass a conversion error. ## Spec source diff --git a/internal/app/azldev/cmds/component/build.go b/internal/app/azldev/cmds/component/build.go index 2c9f99171..f2d955277 100644 --- a/internal/app/azldev/cmds/component/build.go +++ b/internal/app/azldev/cmds/component/build.go @@ -288,7 +288,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()), )...) diff --git a/internal/app/azldev/cmds/component/diffsources.go b/internal/app/azldev/cmds/component/diffsources.go index 7fd728050..24a2dd370 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..d1950fc34 100644 --- a/internal/app/azldev/cmds/component/history_customizations.go +++ b/internal/app/azldev/cmds/component/history_customizations.go @@ -29,6 +29,31 @@ func collectCustomizations(name string, config *projectconfig.ComponentConfig) [ items = appendRenderItems(items, config.Render) items = appendPackageItems(items, config.Packages) items = appendSourceFileItems(items, config.SourceFiles) + items = appendGoVendorItems(items, config.GoVendor) + + return items +} + +func appendGoVendorItems(items []CustomizationItem, config *projectconfig.GoVendorConfig) []CustomizationItem { + if config == nil { + return items + } + + if config.Enabled != nil { + items = append(items, CustomizationItem{Kind: "go-vendor.enabled", Value: strconv.FormatBool(*config.Enabled)}) + } + + if config.ModuleDir != "" { + items = append(items, CustomizationItem{Kind: "go-vendor.module-dir", Value: config.ModuleDir}) + } + + if config.ToolConfig != "" { + items = append(items, CustomizationItem{Kind: "go-vendor.tool-config", Value: config.ToolConfig}) + } + + for _, name := range config.PrepPackages { + items = append(items, CustomizationItem{Kind: "go-vendor.prep-packages", Value: name}) + } return items } diff --git a/internal/app/azldev/cmds/component/history_internal_test.go b/internal/app/azldev/cmds/component/history_internal_test.go index 242094194..eb9ef98fd 100644 --- a/internal/app/azldev/cmds/component/history_internal_test.go +++ b/internal/app/azldev/cmds/component/history_internal_test.go @@ -88,6 +88,7 @@ func TestCustomizationCollectorsCoverEveryFingerprintableField(t *testing.T) { reflect.TypeFor[projectconfig.ComponentRenderConfig](), reflect.TypeFor[projectconfig.SourceFileReference](), reflect.TypeFor[projectconfig.Origin](), + reflect.TypeFor[projectconfig.GoVendorConfig](), } // Maps "StructName.FieldName" -> short note describing how the field @@ -103,6 +104,11 @@ func TestCustomizationCollectorsCoverEveryFingerprintableField(t *testing.T) { "ComponentConfig.Render": "appendRenderItems (per-field via ComponentRenderConfig walk)", "ComponentConfig.SourceFiles": "appendSourceFileItems (opaque unit per source file)", "ComponentConfig.Packages": "appendPackageItems (opaque unit per package override)", + "ComponentConfig.GoVendor": "appendGoVendorItems", + "GoVendorConfig.Enabled": "go-vendor.enabled", + "GoVendorConfig.ModuleDir": "go-vendor.module-dir", + "GoVendorConfig.ToolConfig": "go-vendor.tool-config", + "GoVendorConfig.PrepPackages": "go-vendor.prep-packages", // ComponentBuildConfig. "ComponentBuildConfig.With": "build.with", diff --git a/internal/app/azldev/cmds/component/preparerctx.go b/internal/app/azldev/cmds/component/preparerctx.go index f98f7b671..777ff4c73 100644 --- a/internal/app/azldev/cmds/component/preparerctx.go +++ b/internal/app/azldev/cmds/component/preparerctx.go @@ -4,11 +4,37 @@ package component import ( + "errors" + "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" + "github.com/microsoft/azure-linux-dev-tools/internal/rpm/mock" ) +func goVendorPreparerOptions( + env *azldev.Env, component components.Component, mockConfigOpts map[string]string, +) ([]sources.PreparerOption, error) { + if !component.GetConfig().GoVendor.IsEnabled() || env.DryRun() { + return nil, nil + } + + _, distro, err := env.Distro() + if err != nil { + return nil, fmt.Errorf("resolving Go vendor build distro:\n%w", err) + } + + if distro.MockConfigPath == "" { + return nil, errors.New("go vendoring requires a project distro with a mock configuration") + } + + runner := mock.NewRunner(env, distro.MockConfigPath).WithConfigOpts(mockConfigOpts) + + return []sources.PreparerOption{sources.WithGoVendorRunner(runner)}, 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/preparerctx_internal_test.go b/internal/app/azldev/cmds/component/preparerctx_internal_test.go new file mode 100644 index 000000000..7118b0017 --- /dev/null +++ b/internal/app/azldev/cmds/component/preparerctx_internal_test.go @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package component + +import ( + "testing" + + "github.com/microsoft/azure-linux-dev-tools/internal/app/azldev/core/components/components_testutils" + "github.com/microsoft/azure-linux-dev-tools/internal/app/azldev/core/testutils" + "github.com/microsoft/azure-linux-dev-tools/internal/projectconfig" + "github.com/samber/lo" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/mock/gomock" +) + +func TestGoVendorPreparerOptions(t *testing.T) { + const disabled = "disabled" + for _, mode := range []string{"enabled", disabled, "missing-mock", "missing-distro"} { + t.Run(mode, func(t *testing.T) { + env := testutils.NewTestEnv(t) + component := components_testutils.NewMockComponent(gomock.NewController(t)) + component.EXPECT().GetConfig().AnyTimes().Return(&projectconfig.ComponentConfig{ + GoVendor: &projectconfig.GoVendorConfig{Enabled: lo.ToPtr(mode != disabled)}, + }) + + switch mode { + case "missing-mock", disabled: + clearProjectMockConfig(env.Env.Config()) + case "missing-distro": + env.Env.Config().Project.DefaultDistro.Name = "absent" + } + + options, err := goVendorPreparerOptions(env.Env, component, nil) + + switch mode { + case "enabled": + require.NoError(t, err) + require.Len(t, options, 1) + case disabled: + require.NoError(t, err) + assert.Empty(t, options) + default: + require.Error(t, err) + assert.Empty(t, options) + } + }) + } +} + +func TestGoVendorHistoryCustomizations(t *testing.T) { + config := &projectconfig.GoVendorConfig{ + Enabled: lo.ToPtr(true), ModuleDir: "cmd/app", + ToolConfig: "[archive]\ntidy = false", PrepPackages: []string{"git"}, + } + assert.Equal(t, []CustomizationItem{ + {Kind: "go-vendor.enabled", Value: "true"}, + {Kind: "go-vendor.module-dir", Value: "cmd/app"}, + {Kind: "go-vendor.tool-config", Value: config.ToolConfig}, + {Kind: "go-vendor.prep-packages", Value: "git"}, + }, collectCustomizations("app", &projectconfig.ComponentConfig{GoVendor: config})) + assert.Empty(t, appendGoVendorItems(nil, &projectconfig.GoVendorConfig{})) +} diff --git a/internal/app/azldev/cmds/component/preparesources.go b/internal/app/azldev/cmds/component/preparesources.go index 317b7fb38..37b9668c8 100644 --- a/internal/app/azldev/cmds/component/preparesources.go +++ b/internal/app/azldev/cmds/component/preparesources.go @@ -73,7 +73,8 @@ Only one component may be selected at a time.`, _ = cmd.MarkFlagRequired("output-dir") _ = cmd.MarkFlagDirname("output-dir") - cmd.Flags().BoolVar(&options.SkipOverlays, "skip-overlays", false, "skip applying overlays to prepared sources") + cmd.Flags().BoolVar(&options.SkipOverlays, "skip-overlays", false, + "skip overlays and Go vendor conversion, preserving upstream packaging") cmd.Flags().BoolVar(&options.WithoutGitRepo, "without-git", false, "Disable dist-git repository creation (enabled by default)") addRPMDevBumpspecFlag(cmd, &options.RPMDevBumpspec) @@ -82,8 +83,7 @@ Only one component may be selected at a time.`, cmd.Flags().BoolVar(&options.AllowNoHashes, "allow-no-hashes", false, "compute missing hashes by downloading source files from their origin") cmd.Flags().BoolVar(&options.SkipSources, "skip-sources", false, - "skip downloading fetched sources when preparing the package (useful to extract "+ - "dist-git metadata when source files are not needed)") + "skip downloading sources unless Go vendor conversion requires them") return cmd } @@ -142,6 +142,14 @@ func PrepareComponentSources(env *azldev.Env, options *PrepareSourcesOptions) er } preparerOpts := buildPreparerOptions(env, distro, options) + if !options.SkipOverlays { + vendorOpts, err := goVendorPreparerOptions(env, component, nil) + if err != nil { + return err + } + + preparerOpts = append(preparerOpts, vendorOpts...) + } preparer, err := newSourcePreparer(sourceManager, env.FS(), env, env, append( preparerOpts, diff --git a/internal/app/azldev/cmds/component/render.go b/internal/app/azldev/cmds/component/render.go index ff99942bd..6f4277743 100644 --- a/internal/app/azldev/cmds/component/render.go +++ b/internal/app/azldev/cmds/component/render.go @@ -531,8 +531,8 @@ func prepareComponentSources( // Prepare sources with overlays, skipping lookaside downloads. // WithGitRepo preserves upstream .git and creates synthetic history so // rpmautospec can expand %autorelease and %autochangelog correctly. - // WithSkipLookaside avoids expensive tarball downloads — only spec + - // sidecar files are needed for rendering. + // WithSkipLookaside avoids tarball downloads unless Go vendoring requires + // the prepared sources to generate the archive and cumulative license. preparerOpts := append(gitRepoPreparerOptions(env, distro), sources.WithSkipLookaside(), sources.WithUpstreamProvenance(sources.FedoraDistTag(distro.Ref.Name, distro.Version.ReleaseVer)), @@ -542,7 +542,7 @@ func prepareComponentSources( preparerOpts = append(preparerOpts, sources.WithRPMDevBumpspec(env, env.WorkDir(), "")) } - preparer, err := newSourcePreparer(sourceManager, env.FS(), env, env, append( + preparer, err := newComponentSourcePreparer(env, comp, sourceManager, nil, append( preparerOpts, sources.WithSpecEditor(specEditor), )...) diff --git a/internal/app/azldev/cmds/component/sourcepreparer.go b/internal/app/azldev/cmds/component/sourcepreparer.go index a16e0a00c..a13890267 100644 --- a/internal/app/azldev/cmds/component/sourcepreparer.go +++ b/internal/app/azldev/cmds/component/sourcepreparer.go @@ -3,7 +3,24 @@ package component -import "github.com/microsoft/azure-linux-dev-tools/internal/app/azldev/core/sources" +import ( + "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, component components.Component, manager sourceproviders.SourceManager, + mockConfigOpts map[string]string, options ...sources.PreparerOption, +) (sources.SourcePreparer, error) { + vendorOpts, err := goVendorPreparerOptions(env, component, mockConfigOpts) + if err != nil { + return nil, err + } + + return newSourcePreparer(manager, env.FS(), env, env, append(options, vendorOpts...)...) +} diff --git a/internal/app/azldev/core/sources/govendor.go b/internal/app/azldev/core/sources/govendor.go new file mode 100644 index 000000000..c6314e3a8 --- /dev/null +++ b/internal/app/azldev/core/sources/govendor.go @@ -0,0 +1,373 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package sources + +import ( + "bytes" + "context" + "errors" + "fmt" + "log/slog" + "path/filepath" + "strings" + "time" + + "github.com/kballard/go-shellquote" + "github.com/microsoft/azure-linux-dev-tools/internal/app/azldev/core/components" + "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/rpm/spectool" + "github.com/microsoft/azure-linux-dev-tools/internal/utils/fileperms" + "github.com/microsoft/azure-linux-dev-tools/internal/utils/fileutils" +) + +const ( + goVendorMount = "/azldev-go-vendor" + goVendorTopDir = "/tmp/azldev-go-rpm" + goVendorBuild = goVendorTopDir + "/BUILD" + goVendorConfig = "azldev-go-vendor.toml" + goVendorScratch = "/azldev-go-scratch" + goVendorCleanupTimeout = 5 * time.Minute +) + +// WithGoVendorRunner provides a template runner. Every conversion uses a fresh, +// isolated root; only the component staging directory is exposed to it. +func WithGoVendorRunner(runner *mock.Runner) PreparerOption { + return func(p *sourcePreparerImpl) { p.goVendorRunner = runner } +} + +func (p *sourcePreparerImpl) prepareGoVendor( + ctx context.Context, component components.Component, outputDir string, +) (err error) { + config := component.GetConfig().GoVendor + if !config.IsEnabled() { + return nil + } + + if err := config.Validate(); err != nil { + return fmt.Errorf("invalid Go vendor configuration:\n%w", err) + } + + if p.dryRunnable.DryRun() { + slog.Info("Dry run; skipping Go vendor conversion and archive generation", "component", component.GetName()) + + return nil + } + + if p.goVendorRunner == nil { + return errors.New("go vendoring requires a mock runner with the project's build distro configuration") + } + + archiveName := component.GetName() + "-vendor.tar.bz2" + + specPath, err := p.resolveSpecPath(component, outputDir) + if err != nil { + return err + } + + data, err := fileutils.ReadFile(p.fs, specPath) + if err != nil { + return fmt.Errorf("reading Go spec:\n%w", err) + } + + converted, err := spec.ConvertGoVendor(data, spec.GoVendorOptions{ + ArchiveName: archiveName, ConfigName: goVendorConfig, ModuleDir: config.ModuleDir, + }) + if err != nil { + return fmt.Errorf("converting Go spec for %#q:\n%w", component.GetName(), err) + } + + if err := p.checkGoVendorSourceCollision(outputDir, archiveName); err != nil { + return err + } + + scratch, err := fileutils.MkdirTempInTempDir(p.fs, "azldev-go-vendor-*") + if err != nil { + return fmt.Errorf("creating Go vendor scratch directory:\n%w", err) + } + defer fileutils.RemoveAllAndUpdateErrorIfNil(p.fs, scratch, &err) + + staging := filepath.Join(scratch, "work") + if err := fileutils.MkdirAll(p.fs, staging); err != nil { + return fmt.Errorf("creating Go vendor staging directory:\n%w", err) + } + + sourceCopy := filepath.Join(scratch, "sources") + if err := p.stageGoVendorInputs(outputDir, sourceCopy, staging, filepath.Base(specPath), + converted.PrepSpec, config.ToolConfig); err != nil { + return err + } + + runner := p.goVendorRunner.Clone().WithBaseDir(filepath.Join(scratch, "mock")). + EnableNetwork().WithUnprivileged() + runner.AddBindMount(sourceCopy, goVendorMount) + runner.AddBindMount(staging, goVendorScratch) + + if err := p.runGoVendor(ctx, runner, archiveName, filepath.Base(specPath), config); err != nil { + return err + } + + if err := p.validateGoVendorInputs(staging, outputDir); err != nil { + return err + } + + return p.publishGoVendor(staging, outputDir, specPath, archiveName, converted.Spec, config.ToolConfig) +} + +func (p *sourcePreparerImpl) stageGoVendorInputs( + outputDir, sourceCopy, staging, specFilename string, prepSpec []byte, toolConfig string, +) error { + if err := fileutils.CopyDirRecursive(p.dryRunnable, p.fs, outputDir, sourceCopy, + fileutils.CopyDirOptions{CopyFileOptions: fileutils.CopyFileOptions{PreserveFileMode: true}}); err != nil { + return fmt.Errorf("copying Go sources for isolated prep:\n%w", err) + } + + if err := fileutils.WriteFile(p.fs, + filepath.Join(sourceCopy, specFilename), prepSpec, fileperms.PublicFile); err != nil { + return fmt.Errorf("staging Go prep spec:\n%w", err) + } + + if err := fileutils.WriteFile(p.fs, filepath.Join(staging, goVendorConfig), + []byte(toolConfig), fileperms.PublicFile); err != nil { + return fmt.Errorf("staging Go vendor tool configuration:\n%w", err) + } + + return nil +} + +func (p *sourcePreparerImpl) publishGoVendor( + staging, outputDir, specPath, archiveName string, data []byte, toolConfig string, +) error { + archiveInfo, err := p.fs.Stat(filepath.Join(staging, archiveName)) + if err != nil { + return fmt.Errorf("missing generated Go vendor archive:\n%w", err) + } + + if !archiveInfo.Mode().IsRegular() || archiveInfo.Size() == 0 { + return errors.New("generated Go vendor archive must be a nonempty regular file") + } + + license, err := fileutils.ReadFile(p.fs, filepath.Join(staging, "license")) + if err != nil { + return fmt.Errorf("reading Go vendor license report:\n%w", err) + } + + expression := strings.TrimSpace(string(license)) + if expression == "" || strings.ContainsAny(expression, "\r\n%") { + return fmt.Errorf("invalid license expression returned by 'go_vendor_license': %#q", expression) + } + + editor, err := spec.OpenSpec(bytes.NewReader(data), spec.WithEditor(spec.EditorStructural)) + if err != nil { + return fmt.Errorf("reading converted Go spec:\n%w", err) + } + + if err := editor.UpdateExistingTag("", "License", expression); err != nil { + return fmt.Errorf("updating bundled Go licenses:\n%w", err) + } + + var finalSpec bytes.Buffer + if err := editor.Serialize(&finalSpec); err != nil { + return fmt.Errorf("serializing converted Go spec:\n%w", err) + } + // Publish only after generation and license detection succeed. + if err := fileutils.CopyFile(p.dryRunnable, p.fs, + filepath.Join(staging, archiveName), filepath.Join(outputDir, archiveName), fileutils.CopyFileOptions{}); err != nil { + return fmt.Errorf("publishing Go vendor archive:\n%w", err) + } + + for name, contents := range map[string][]byte{ + filepath.Base(specPath): finalSpec.Bytes(), + goVendorConfig: []byte(toolConfig), + } { + if err := fileutils.WriteFile(p.fs, filepath.Join(outputDir, name), contents, fileperms.PublicFile); err != nil { + return fmt.Errorf("publishing Go vendor file %#q:\n%w", name, err) + } + } + + return p.recordGoVendorArchive(outputDir, archiveName) +} + +func (p *sourcePreparerImpl) runGoVendor( + ctx context.Context, runner *mock.Runner, archiveName, specFilename string, config *projectconfig.GoVendorConfig, +) (err error) { + defer func() { + cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), goVendorCleanupTimeout) + defer cancel() + + if scrubErr := runner.ScrubRoot(cleanupCtx); scrubErr != nil { + slog.Error("Failed to clean Go vendor mock root", "error", scrubErr) + + if err == nil { + err = scrubErr + } + } + }() + + if err := runner.InitRoot(ctx); err != nil { + return fmt.Errorf("initializing Go vendor mock root:\n%w", err) + } + + packages := append([]string{ + "go-vendor-tools", "askalono-cli", "golang", "go-rpm-macros", "rpm-build", "rpmdevtools", + "rpmautospec", "git", "python3-click", + }, config.PrepPackages...) + if err := runner.InstallPackages(ctx, packages); err != nil { + return fmt.Errorf("installing Go vendor prerequisites:\n%w", err) + } + + cmd, err := runner.CmdInChroot(ctx, []string{ + "bash", "-euo", "pipefail", "-c", + goVendorScript(archiveName, config.ModuleDir, runner.ConfigOpts()["target_arch"], specFilename), + }, false) + if err != nil { + return fmt.Errorf("constructing Go vendor command:\n%w", err) + } + + output, err := cmd.RunAndGetOutput(ctx) + if err != nil { + return fmt.Errorf("go vendor generation or license detection failed; use 'prep-packages' for missing prep tools "+ + "and 'tool-config' for reviewed license exceptions:\n%s\n%w", output, err) + } + + return nil +} + +func goVendorScript(archiveName, moduleDir, targetArch, specFilename string) string { + if moduleDir == "" { + moduleDir = "." + } + + quote := shellquote.Join + + prepArgs := []string{ + "rpmbuild", "-bp", "--nodeps", "--define", "_topdir /tmp/azldev-go-rpm", + "--define", "_builddir " + goVendorBuild, "--define", "_sourcedir " + goVendorMount, + } + if targetArch != "" { + prepArgs = append(prepArgs, "--target", targetArch) + } + + prepArgs = append(prepArgs, goVendorMount+"/"+specFilename) + + return strings.Join([]string{ + "cd " + goVendorMount, + "mkdir -p " + goVendorBuild, + quote("git", "config", "--global", "--add", "safe.directory", goVendorMount), + quote("rpmautospec", "process-distgit", specFilename, specFilename), + quote(prepArgs...), + `IFS= read -r module_root < ` + goVendorTopDir + "/azldev-go-module-root", + `cd "$module_root"`, + "cd " + quote(moduleDir), + "test -f go.mod", + "export GOTOOLCHAIN=local", + quote("go_vendor_archive", "create", "--config", goVendorScratch+"/"+goVendorConfig, + "--output", goVendorScratch+"/"+archiveName, "."), + quote("tar", "-xf", goVendorScratch+"/"+archiveName), + quote("go_vendor_license", "--config", goVendorScratch+"/"+goVendorConfig, "--path", ".", + "report", "--no-prompt", "--autofill", "off", "expression") + " > " + goVendorScratch + "/license", + "cd " + goVendorMount, + quote("spectool", "--define", "_sourcedir "+goVendorMount, "-l", "-a", + specFilename) + " > " + goVendorScratch + "/sources-list", + }, "\n") +} + +func (p *sourcePreparerImpl) checkGoVendorSourceCollision(outputDir, name string) error { + for _, filename := range []string{name, goVendorConfig} { + exists, err := fileutils.Exists(p.fs, filepath.Join(outputDir, filename)) + if err != nil { + return fmt.Errorf("checking generated Go source path:\n%w", err) + } + + if exists { + return fmt.Errorf("generated Go vendor file %#q conflicts with an existing source", filename) + } + } + + content, err := p.readSourcesFileIfExists(filepath.Join(outputDir, fedorasource.SourcesFileName)) + if err != nil { + return err + } + + lines, err := fedorasource.ReadSourcesFile(content) + if err != nil { + return fmt.Errorf("reading Go vendor 'sources' entries:\n%w", err) + } + + for _, line := range lines { + if line.Entry != nil && line.Entry.Filename == name { + return fmt.Errorf("generated Go vendor archive %#q conflicts with an upstream 'sources' entry", name) + } + } + + return nil +} + +func (p *sourcePreparerImpl) recordGoVendorArchive(outputDir, name string) error { + hash, err := fileutils.ComputeFileHash(p.fs, fileutils.HashTypeSHA512, filepath.Join(outputDir, name)) + if err != nil { + return fmt.Errorf("hashing generated Go vendor archive:\n%w", err) + } + + content, err := p.readSourcesFileIfExists(filepath.Join(outputDir, fedorasource.SourcesFileName)) + if err != nil { + return err + } + + content = strings.TrimRight(content, "\n") + if content != "" { + content += "\n" + } + + content += fedorasource.FormatSourcesEntry(name, fileutils.HashTypeSHA512, hash) + "\n" + if err := fileutils.WriteFile(p.fs, filepath.Join(outputDir, fedorasource.SourcesFileName), + []byte(content), fileperms.PublicFile); err != nil { + return fmt.Errorf("recording Go vendor digest:\n%w", err) + } + // Generated payloads belong in lookaside storage, not synthetic git commits. + ignorePath := filepath.Join(outputDir, ".gitignore") + + ignore, err := p.readSourcesFileIfExists(ignorePath) + if err != nil { + return err + } + + if err := fileutils.WriteFile(p.fs, ignorePath, + []byte(strings.TrimRight(ignore, "\n")+"\n/"+name+"\n"), fileperms.PublicFile); err != nil { + return fmt.Errorf("ignoring generated Go archive in git:\n%w", err) + } + + return nil +} + +func (p *sourcePreparerImpl) validateGoVendorInputs(scratch, outputDir string) error { + data, err := fileutils.ReadFile(p.fs, filepath.Join(scratch, "sources-list")) + if err != nil { + return fmt.Errorf("reading prepared Go source list:\n%w", err) + } + + for _, line := range strings.Split(strings.TrimSpace(string(data)), "\n") { + if line == "" { + continue + } + + files := spectool.ParseSpectoolOutput(line) + if len(files) != 1 || strings.Contains(files[0], "%") { + return fmt.Errorf("cannot resolve Go source/patch reference %#q", line) + } + + info, err := p.fs.Stat(filepath.Join(outputDir, files[0])) + if err != nil { + return fmt.Errorf("missing prepared Go source/patch %#q:\n%w", files[0], err) + } + + if !info.Mode().IsRegular() { + return fmt.Errorf("go source/patch %#q is not a regular file", files[0]) + } + } + + return nil +} 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..d79bbf4a5 --- /dev/null +++ b/internal/app/azldev/core/sources/govendor_internal_test.go @@ -0,0 +1,244 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package sources + +import ( + "context" + "errors" + "os/exec" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/microsoft/azure-linux-dev-tools/internal/app/azldev/core/components/components_testutils" + "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/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/samber/lo" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/mock/gomock" +) + +func goVendorTestSpec() string { + return strings.Join([]string{ + "Name: app", "Version: 1", "Release: 1", "Summary: app", "License: MIT", + "Source0: app.tar.gz", "Patch0: fix.patch", "BuildRequires: golang(example.com/dep)", + "%description", "app", "%prep", "%goprep -p1", "%build", "%gobuild -o app .", + "%install", "install -D app %{buildroot}%{_bindir}/app", "%files", "%{_bindir}/app", "", + }, "\n") +} + +func TestPrepareSourcesGoVendor(t *testing.T) { + for _, skipLookaside := range []bool{false, true} { + t.Run(map[bool]string{false: "prepare", true: "render"}[skipLookaside], func(t *testing.T) { + ctx := newMockProcessorTestCtx() + ctrl := gomock.NewController(t) + component := components_testutils.NewMockComponent(ctrl) + manager := sourceproviders_test.NewMockSourceManager(ctrl) + config := &projectconfig.ComponentConfig{ + GoVendor: &projectconfig.GoVendorConfig{Enabled: lo.ToPtr(true), PrepPackages: []string{"git"}}, + Overlays: []projectconfig.ComponentOverlay{{ + Type: "spec-set-tag", Tag: "Summary", Value: "overlaid", + }}, + } + + component.EXPECT().GetName().AnyTimes().Return("app") + component.EXPECT().GetConfig().AnyTimes().Return(config) + manager.EXPECT().FetchComponent(gomock.Any(), component, "/output", gomock.Any()).DoAndReturn( + func(_ context.Context, _ any, _ string, _ ...sourceproviders.FetchComponentOption) error { + for name, content := range map[string]string{ + "app.spec": goVendorTestSpec(), "app.tar.gz": "upstream", "fix.patch": "patch", + "sources": "# upstream\n", ".gitignore": "/app.tar.gz\n", + } { + require.NoError(t, fileutils.WriteFile(ctx.FS(), "/output/"+name, []byte(content), fileperms.PublicFile)) + } + + return nil + }) + manager.EXPECT().FetchFiles(gomock.Any(), component, "/output").Return(nil) + + var calls []string + + ctx.CmdFactory.RunHandler = func(cmd *exec.Cmd) error { + calls = append(calls, strings.Join(cmd.Args, " ")) + + return nil + } + ctx.CmdFactory.RunAndGetOutputHandler = func(cmd *exec.Cmd) (string, error) { + assert.Contains(t, cmd.Args, "--unpriv") + assert.Contains(t, cmd.Args, "--enable-network") + assert.Contains(t, strings.Join(cmd.Args, " "), "go_vendor_archive") + staging := goVendorTestStaging(t, ctx) + prep, err := fileutils.ReadFile(ctx.FS(), filepath.Join(filepath.Dir(staging), "sources", "app.spec")) + require.NoError(t, err) + assert.Contains(t, string(prep), "Summary: overlaid", "overlays must run before generation") + + for name, content := range map[string]string{ + "app-vendor.tar.bz2": "generated archive", + "license": "Apache-2.0 AND MIT\n", + "sources-list": "Source0: app.tar.gz\nPatch0: fix.patch\n", + } { + require.NoError(t, fileutils.WriteFile(ctx.FS(), + filepath.Join(staging, name), []byte(content), fileperms.PublicFile)) + } + + return "", nil + } + + options := []PreparerOption{WithGoVendorRunner(mock.NewRunner(ctx, "/mock.cfg"))} + if skipLookaside { + options = append(options, WithSkipLookaside()) + } + + preparer, err := NewPreparer(manager, ctx.FS(), ctx, ctx, options...) + require.NoError(t, err) + require.NoError(t, preparer.PrepareSources(ctx, component, "/output", true)) + output, err := fileutils.ReadFile(ctx.FS(), "/output/app.spec") + require.NoError(t, err) + assert.Contains(t, string(output), "License: Apache-2.0 AND MIT") + assert.Contains(t, string(output), "tar -xf %{SOURCE1}") + assert.NotContains(t, string(output), "BuildRequires: golang(") + + digest, err := fileutils.ComputeFileHash(ctx.FS(), fileutils.HashTypeSHA512, "/output/app-vendor.tar.bz2") + require.NoError(t, err) + sources, err := fileutils.ReadFile(ctx.FS(), "/output/sources") + require.NoError(t, err) + assert.Contains(t, string(sources), "# upstream\n") + assert.Contains(t, string(sources), + fedorasource.FormatSourcesEntry("app-vendor.tar.bz2", fileutils.HashTypeSHA512, digest)) + ignored, err := fileutils.ReadFile(ctx.FS(), "/output/.gitignore") + require.NoError(t, err) + assert.Equal(t, "/app.tar.gz\n/app-vendor.tar.bz2\n", string(ignored)) + assert.Contains(t, strings.Join(calls, "\n"), "--install go-vendor-tools askalono-cli") + assert.Contains(t, strings.Join(calls, "\n"), " git") + assert.Contains(t, strings.Join(calls, "\n"), "--scrub all") + assert.NotContains(t, strings.Join(calls, "\n"), "go2rpm") + + matches, err := fileutils.Glob(ctx.FS(), "/tmp/azldev-go-vendor-*") + require.NoError(t, err) + assert.Empty(t, matches) + }) + } +} + +func goVendorTestStaging(t *testing.T, ctx *testctx.TestCtx) string { + t.Helper() + + matches, err := fileutils.Glob(ctx.FS(), "/tmp/azldev-go-vendor-*/work/azldev-go-vendor.toml") + require.NoError(t, err) + require.Len(t, matches, 1) + + return filepath.Dir(matches[0]) +} + +func TestGoVendorFailuresDoNotPublishSpec(t *testing.T) { + failure := errors.New("tool failed") + + for _, stage := range []string{ + "init", "install", "generate", "missing-archive", "empty-archive", + "license", "missing-source", "source-list", "scrub", + } { + t.Run(stage, func(t *testing.T) { + ctx := newMockProcessorTestCtx() + ctrl := gomock.NewController(t) + component := components_testutils.NewMockComponent(ctrl) + component.EXPECT().GetName().AnyTimes().Return("app") + component.EXPECT().GetConfig().AnyTimes().Return(&projectconfig.ComponentConfig{ + GoVendor: &projectconfig.GoVendorConfig{Enabled: lo.ToPtr(true)}, + }) + require.NoError(t, fileutils.WriteFile(ctx.FS(), + "/output/app.spec", []byte(goVendorTestSpec()), fileperms.PublicFile)) + require.NoError(t, fileutils.WriteFile(ctx.FS(), "/output/app.tar.gz", []byte("source"), fileperms.PublicFile)) + ctx.CmdFactory.RunHandler = func(cmd *exec.Cmd) error { + if slices.Contains(cmd.Args, "--"+stage) { + return failure + } + + return nil + } + ctx.CmdFactory.RunAndGetOutputHandler = func(_ *exec.Cmd) (string, error) { + if stage == "generate" { + return "license failure details", failure + } + + staging := goVendorTestStaging(t, ctx) + files := map[string]string{ + "app-vendor.tar.bz2": "archive", "license": "MIT\n", "sources-list": "Source0: app.tar.gz\n", + } + + switch stage { + case "missing-archive": + delete(files, "app-vendor.tar.bz2") + case "empty-archive": + files["app-vendor.tar.bz2"] = "" + case "license": + files["license"] = "bad\nLicense" + case "missing-source": + files["sources-list"] += "Patch0: absent.patch\n" + case "source-list": + files["sources-list"] = "Source0: /etc/passwd\n" + } + + for name, data := range files { + require.NoError(t, fileutils.WriteFile(ctx.FS(), filepath.Join(staging, name), []byte(data), fileperms.PublicFile)) + } + + return "", nil + } + p := &sourcePreparerImpl{fs: ctx.FS(), dryRunnable: ctx, goVendorRunner: mock.NewRunner(ctx, "/mock.cfg")} + err := p.prepareGoVendor(ctx, component, "/output") + require.Error(t, err) + + unchanged, readErr := fileutils.ReadFile(ctx.FS(), "/output/app.spec") + require.NoError(t, readErr) + assert.Equal(t, goVendorTestSpec(), string(unchanged)) + + exists, readErr := fileutils.Exists(ctx.FS(), "/output/app-vendor.tar.bz2") + require.NoError(t, readErr) + assert.False(t, exists) + }) + } +} + +func TestGoVendorScriptOrdering(t *testing.T) { + script := goVendorScript("app-vendor.tar.bz2", "cmd/app", "aarch64", "app.spec") + assert.Less(t, strings.Index(script, "rpmautospec"), strings.Index(script, "rpmbuild")) + assert.Less(t, strings.Index(script, "rpmbuild"), strings.Index(script, "go_vendor_archive")) + assert.Less(t, strings.Index(script, "go_vendor_archive"), strings.Index(script, "go_vendor_license")) + assert.Contains(t, script, "cd cmd/app") + assert.Contains(t, script, "--target aarch64") + assert.Contains(t, script, "--no-prompt") + assert.Contains(t, script, "--autofill off") + assert.NotContains(t, script, "--idempotent") +} + +func TestGoVendorSourceCollisions(t *testing.T) { + for _, name := range []string{"app-vendor.tar.bz2", goVendorConfig, "sources", "invalid-sources"} { + t.Run(name, func(t *testing.T) { + ctx := testctx.NewCtx() + preparer := &sourcePreparerImpl{fs: ctx.FS()} + content := "existing" + + filename := name + switch name { + case "sources": + content = fedorasource.FormatSourcesEntry( + "app-vendor.tar.bz2", fileutils.HashTypeSHA512, strings.Repeat("a", 128)) + "\n" + case "invalid-sources": + filename = "sources" + content = "SHA512 (broken" + } + + require.NoError(t, fileutils.WriteFile(ctx.FS(), "/output/"+filename, []byte(content), fileperms.PublicFile)) + require.Error(t, preparer.checkGoVendorSourceCollision("/output", "app-vendor.tar.bz2")) + }) + } +} diff --git a/internal/app/azldev/core/sources/sourceprep.go b/internal/app/azldev/core/sources/sourceprep.go index 4edeb30b6..8759787d8 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" @@ -133,7 +134,8 @@ func WithSpecEditor(mode spec.EditorMode) PreparerOption { // component fetching ([FedoraSourceDownloader.ExtractSourcesFromRepo]). // Git-tracked files (spec, patches, scripts, configs) are still fetched from // the upstream clone. This is useful for rendering, where only the spec and -// sidecar files are needed and downloading large source tarballs is unnecessary. +// sidecar files are normally needed. Enabled Go vendor conversion overrides this +// optimization because its archive and license expression require prepared sources. func WithSkipLookaside() PreparerOption { return func(p *sourcePreparerImpl) { p.skipLookaside = true @@ -184,11 +186,12 @@ func WithAllowNoHashes() PreparerOption { // Standard implementation of the [SourcePreparer] interface. type sourcePreparerImpl struct { - sourceManager sourceproviders.SourceManager - specEditor spec.EditorMode - fs opctx.FS - eventListener opctx.EventListener - dryRunnable opctx.DryRunnable + sourceManager sourceproviders.SourceManager + specEditor spec.EditorMode + fs opctx.FS + eventListener opctx.EventListener + dryRunnable opctx.DryRunnable + goVendorRunner *mock.Runner // withGitRepo, when true, enables dist-git creation by preserving the // upstream .git directory and generating synthetic commit history. @@ -297,6 +300,8 @@ func NewPreparer( func (p *sourcePreparerImpl) PrepareSources( ctx context.Context, component components.Component, outputDir string, applyOverlays bool, ) error { + p = p.withRequiredDownloads(component, applyOverlays) + if applyOverlays { if err := p.validateArchiveOverlayConfig(component); err != nil { return err @@ -360,6 +365,21 @@ func (p *sourcePreparerImpl) PrepareSources( return nil } +func (p *sourcePreparerImpl) withRequiredDownloads( + component components.Component, applyConversion bool, +) *sourcePreparerImpl { + if applyConversion && p.skipLookaside && component.GetConfig().GoVendor.IsEnabled() { + effective := *p + effective.skipLookaside = false + + slog.Info("Go vendoring requires source downloads, including during rendering", "component", component.GetName()) + + return &effective + } + + return p +} + func (p *sourcePreparerImpl) validateArchiveOverlayConfig(component components.Component) error { config := component.GetConfig() if err := config.ValidateArchiveOverlays(p.allowNoHashes); err != nil { @@ -394,6 +414,10 @@ func (p *sourcePreparerImpl) applyOverlaysToSources( component.GetName(), err) } + if err := p.prepareGoVendor(ctx, component, outputDir); err != nil { + return nil, fmt.Errorf("preparing Go vendor sources for component %#q:\n%w", component.GetName(), err) + } + return repackedArchives, nil } @@ -740,6 +764,8 @@ func removeSubmoduleEntries(fs opctx.FS, repo *gogit.Repository, repoDir string) func (p *sourcePreparerImpl) DiffSources( ctx context.Context, component components.Component, baseDir string, ) (result *dirdiff.DiffResult, err error) { + p = p.withRequiredDownloads(component, true) + event := p.eventListener.StartEvent("Computing overlay diff", "component", component.GetName()) defer event.End() diff --git a/internal/projectconfig/component.go b/internal/projectconfig/component.go index 6b56f9d8e..cf753e065 100644 --- a/internal/projectconfig/component.go +++ b/internal/projectconfig/component.go @@ -374,6 +374,8 @@ type ComponentLockData struct { } // Defines a component. +// +//nolint:recvcheck // HashInclude must also support configs passed to hashstructure by value. type ComponentConfig struct { // The component's name; not actually present in serialized files. Name string `toml:"-" json:"name" table:",sortkey" fingerprint:"-"` @@ -432,6 +434,9 @@ type ComponentConfig struct { // Source file references for this component. SourceFiles []SourceFileReference `toml:"source-files,omitempty" json:"sourceFiles,omitempty" table:"-" jsonschema:"title=Source files,description=Source files to download for this component"` + // GoVendor converts supported Go application specs and generates their vendored sources. + GoVendor *GoVendorConfig `toml:"go-vendor,omitempty" json:"goVendor,omitempty" table:"-" jsonschema:"title=Go vendoring,description=Convert a Go application spec and generate its vendor archive during source preparation"` + // Per-package configuration overrides, keyed by exact binary package name. // Takes precedence over package-group defaults. Packages map[string]PackageConfig `toml:"packages,omitempty" json:"packages,omitempty" table:"-" validate:"dive" jsonschema:"title=Package overrides,description=Per-package configuration overrides keyed by exact binary package name"` @@ -450,6 +455,11 @@ type ComponentConfig struct { Tests *ComponentTestsConfig `toml:"tests,omitempty" json:"tests,omitempty" table:"-" jsonschema:"title=Tests,description=Per-component test or test-group references" fingerprint:"-"` } +// HashInclude preserves existing fingerprints when Go vendoring is not configured. +func (c ComponentConfig) HashInclude(field string, _ any) (bool, error) { + return field != "GoVendor" || c.GoVendor != nil, nil +} + // AllowedSourceFilesHashTypes defines the set of hash types that are supported // for use in [SourceFileReference] entries in component configs. // MD5 is excluded by design. @@ -480,9 +490,20 @@ func (c *ComponentConfig) MergeUpdatesFrom(other *ComponentConfig) error { c.OverlayFiles = otherOverlayFiles } + c.overrideGoVendorEnabled(other) + return nil } +func (c *ComponentConfig) overrideGoVendorEnabled(other *ComponentConfig) { + if other.GoVendor != nil && other.GoVendor.Enabled != nil { + config := *c.GoVendor + enabled := *other.GoVendor.Enabled + config.Enabled = &enabled + c.GoVendor = &config + } +} + func (c *ComponentConfig) resolveLocalCustomScriptPaths() { if c.Spec.SourceType != SpecSourceTypeLocal || c.Spec.Path == "" { return @@ -549,6 +570,8 @@ func (c *ComponentConfig) MergeOverridesFrom(other *ComponentConfig) error { c.OverlayFiles = otherOverlayFiles } + c.overrideGoVendorEnabled(other) + return nil } diff --git a/internal/projectconfig/configfile.go b/internal/projectconfig/configfile.go index ee6f07c73..aee4be162 100644 --- a/internal/projectconfig/configfile.go +++ b/internal/projectconfig/configfile.go @@ -171,6 +171,10 @@ func validateComponentConfigs( } // Validate build configuration. + if err := component.GoVendor.Validate(); err != nil { + return fmt.Errorf("invalid 'go-vendor' config for component %#q:\n%w", componentName, err) + } + err := component.Build.Validate() if err != nil { return fmt.Errorf("invalid build config for component %#q:\n%w", componentName, err) diff --git a/internal/projectconfig/fingerprint_test.go b/internal/projectconfig/fingerprint_test.go index 836eee6f3..dcf89f830 100644 --- a/internal/projectconfig/fingerprint_test.go +++ b/internal/projectconfig/fingerprint_test.go @@ -36,6 +36,7 @@ func TestAllFingerprintedFieldsHaveDecision(t *testing.T) { reflect.TypeFor[projectconfig.Origin](), reflect.TypeFor[projectconfig.ReleaseConfig](), reflect.TypeFor[projectconfig.ComponentRenderConfig](), + reflect.TypeFor[projectconfig.GoVendorConfig](), } // Maps "StructName.FieldName" for every field that should carry a diff --git a/internal/projectconfig/govendor.go b/internal/projectconfig/govendor.go new file mode 100644 index 000000000..cf9fc4eae --- /dev/null +++ b/internal/projectconfig/govendor.go @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package projectconfig + +import ( + "errors" + "fmt" + "strings" + + "github.com/microsoft/azure-linux-dev-tools/internal/utils/fileutils" + "github.com/pelletier/go-toml/v2" +) + +// GoVendorConfig describes a repeatable conversion, not a replacement spec. +type GoVendorConfig struct { + // Enabled is a pointer so an explicit false overrides inherited settings. + Enabled *bool `toml:"enabled,omitempty" json:"enabled,omitempty" jsonschema:"title=Enabled,description=Enable Go application vendoring"` + // ModuleDir is relative to the directory left by the spec's prep section. + ModuleDir string `toml:"module-dir,omitempty" json:"moduleDir,omitempty" jsonschema:"title=Module directory,description=Relative module directory within the prepared source tree; defaults to its root"` + // ToolConfig is inline go-vendor-tools TOML, including reviewed license exceptions. + ToolConfig string `toml:"tool-config,omitempty" json:"toolConfig,omitempty" jsonschema:"title=Tool configuration,description=Inline go-vendor-tools TOML for dependency overrides and licensing settings"` + // PrepPackages supplies additional tools used by upstream prep commands. + PrepPackages []string `toml:"prep-packages,omitempty" json:"prepPackages,omitempty" jsonschema:"title=Prep packages,description=Additional RPM packages needed to execute the upstream prep section in mock"` +} + +// IsEnabled reports whether vendoring was explicitly enabled. +func (c *GoVendorConfig) IsEnabled() bool { + return c != nil && c.Enabled != nil && *c.Enabled +} + +// Validate checks paths and tool configuration before any source processing. +func (c *GoVendorConfig) Validate() error { + if c == nil { + return nil + } + + if c.ModuleDir != "" { + if err := fileutils.ValidateRelPath(c.ModuleDir); err != nil { + return fmt.Errorf("invalid 'module-dir':\n%w", err) + } + + if strings.ContainsAny(c.ModuleDir, "%\n\r") { + return errors.New("'module-dir' must not contain RPM macros or newlines") + } + } + + var toolConfig map[string]any + if err := toml.Unmarshal([]byte(c.ToolConfig), &toolConfig); err != nil { + return fmt.Errorf("invalid 'tool-config' TOML:\n%w", err) + } + + if general, ok := toolConfig["general"].(map[string]any); ok { + if _, exists := general["go_mod_dir"]; exists { + return errors.New("use 'module-dir' instead of 'general.go_mod_dir' in 'tool-config'") + } + } + + for _, name := range c.PrepPackages { + if name == "" || strings.HasPrefix(name, "-") || strings.ContainsAny(name, "\r\n") { + return fmt.Errorf("invalid 'prep-packages' entry %#q", name) + } + } + + return nil +} diff --git a/internal/projectconfig/govendor_test.go b/internal/projectconfig/govendor_test.go new file mode 100644 index 000000000..1c363001a --- /dev/null +++ b/internal/projectconfig/govendor_test.go @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package projectconfig_test + +import ( + "testing" + + "github.com/microsoft/azure-linux-dev-tools/internal/projectconfig" + "github.com/mitchellh/hashstructure/v2" + "github.com/pelletier/go-toml/v2" + "github.com/samber/lo" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestGoVendorConfig(t *testing.T) { + var config projectconfig.ComponentConfig + require.NoError(t, toml.Unmarshal([]byte(` +[go-vendor] +enabled = true +module-dir = "cmd/app" +prep-packages = ["git"] +tool-config = ''' +[archive.dependency_overrides] +"example.com/module" = "v1.2.3" +''' +`), &config)) + require.True(t, config.GoVendor.IsEnabled()) + require.NoError(t, config.GoVendor.Validate()) + require.NoError(t, config.MergeUpdatesFrom(&projectconfig.ComponentConfig{ + GoVendor: &projectconfig.GoVendorConfig{Enabled: lo.ToPtr(false)}, + })) + assert.False(t, config.GoVendor.IsEnabled(), "explicit false must override an inherited true") +} + +func TestGoVendorConfigValidation(t *testing.T) { + for _, config := range []*projectconfig.GoVendorConfig{ + {ModuleDir: "../outside"}, + {ModuleDir: "/absolute"}, + {ModuleDir: "%{macro}"}, + {ToolConfig: "["}, + {ToolConfig: "[general]\ngo_mod_dir = 'subdir'"}, + {PrepPackages: []string{"--bad"}}, + {PrepPackages: []string{""}}, + } { + require.Error(t, config.Validate()) + } + + var absent *projectconfig.GoVendorConfig + assert.False(t, absent.IsEnabled()) + require.NoError(t, absent.Validate()) +} + +func TestGoVendorFingerprint(t *testing.T) { + empty := projectconfig.ComponentConfig{} + included, err := empty.HashInclude("GoVendor", nil) + require.NoError(t, err) + assert.False(t, included, "absent vendoring must not invalidate existing component fingerprints") + included, err = empty.HashInclude("Build", nil) + require.NoError(t, err) + assert.True(t, included) + + base := projectconfig.ComponentConfig{GoVendor: &projectconfig.GoVendorConfig{Enabled: lo.ToPtr(true)}} + original, err := hashstructure.Hash(base, hashstructure.FormatV2, &hashstructure.HashOptions{TagName: "fingerprint"}) + require.NoError(t, err) + + for _, config := range []*projectconfig.GoVendorConfig{ + {Enabled: lo.ToPtr(false)}, + {Enabled: lo.ToPtr(true), ModuleDir: "sub"}, + {Enabled: lo.ToPtr(true), ToolConfig: "[archive]\ntidy = false"}, + {Enabled: lo.ToPtr(true), PrepPackages: []string{"git"}}, + } { + changed := base + changed.GoVendor = config + hash, err := hashstructure.Hash(changed, hashstructure.FormatV2, &hashstructure.HashOptions{TagName: "fingerprint"}) + require.NoError(t, err) + assert.NotEqual(t, original, hash) + } +} diff --git a/internal/rpm/spec/govendor.go b/internal/rpm/spec/govendor.go new file mode 100644 index 000000000..29791e3c1 --- /dev/null +++ b/internal/rpm/spec/govendor.go @@ -0,0 +1,322 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package spec + +import ( + "errors" + "fmt" + "regexp" + "slices" + "strconv" + "strings" + + "github.com/kballard/go-shellquote" + "github.com/microsoft/azure-linux-dev-tools/internal/utils/fileutils" +) + +// GoVendorOptions names generated artifacts. All paths except ModuleDir are basenames. +type GoVendorOptions struct { + ArchiveName string + ConfigName string + ModuleDir string +} + +// GoVendorSpec contains the converted spec and the otherwise identical prep-only +// spec used to obtain the patched module tree before a vendor archive exists. +type GoVendorSpec struct { + Spec []byte + PrepSpec []byte +} + +const goVendorEnvironment = `export GO111MODULE=on GOPROXY=off GOSUMDB=off GOTOOLCHAIN=local +export GOFLAGS="${GOFLAGS:+$GOFLAGS }-mod=vendor"` + +var goBuildRequirement = regexp.MustCompile(`^golang\([^)]+\)(\s*(>=|<=|=|>|<)\s*[^\s,]+)?$`) + +var ( + goVendorUnsupportedMacro = regexp.MustCompile( + `%(?:\{[!?]*)?(?:gopkg\w*|goinstall|gofiles?\w*|go_vendor_\w*|include)\b`) + goVendorRequiresMacro = regexp.MustCompile(`%(?:\{[!?]*)?go_generate_buildrequires\b`) + goVendorCheckMacro = regexp.MustCompile(`%(?:\{[!?]*)?gocheck\b`) +) + +// ConvertGoVendor changes only recognized Go application packaging constructs. +// It always uses the lossless tree, independently of the selected overlay editor. +// Unsupported Go macros and ambiguous section ownership fail before returning output. +func ConvertGoVendor(data []byte, options GoVendorOptions) (*GoVendorSpec, error) { + if err := options.validate(); err != nil { + return nil, err + } + + root, err := parseTree(strings.Split(strings.TrimSuffix(string(data), "\n"), "\n")) + if err != nil { + return nil, err + } + + tree := &specTree{root: root} + if err := validateGoVendorTree(tree); err != nil { + return nil, err + } + + if err := convertGoVendorLines(tree); err != nil { + return nil, err + } + + // Do not replace upstream prep or build scripts: capture the directory after + // their existing prep commands, including patches and module-file edits. + prep := tree.Section("%prep", "") + prep.PrependLines([]string{"export GOTOOLCHAIN=local"}) + prep.AppendLines([]string{"", `pwd -P > "%{_topdir}/azldev-go-module-root"`}) + + prepSpec := serializeGoVendorTree(tree) + + sourceNumber, err := freeGoVendorSources(tree, options) + if err != nil { + return nil, err + } + + configRef := fmt.Sprintf("%%{SOURCE%d}", sourceNumber+1) + + extract := fmt.Sprintf("tar -xf %%{SOURCE%d}", sourceNumber) + if options.ModuleDir != "" { + extract += " -C " + shellquote.Join(options.ModuleDir) + } + + prep.AppendLines([]string{"", extract}) + tree.Section("", "").AppendLines([]string{ + fmt.Sprintf("Source%d: %s", sourceNumber, options.ArchiveName), + fmt.Sprintf("Source%d: %s", sourceNumber+1, options.ConfigName), + "BuildRequires: go-vendor-tools", + "BuildRequires: go-rpm-macros", + "BuildRequires: golang", + "%global gomodulesmode GO111MODULE=on", + "%global go_vendor_license_filelist() %{_topdir}/azldev-go-vendor-licenses.list", + "", + }) + + addGoVendorBuildSections(tree, options, configRef) + + return &GoVendorSpec{Spec: serializeGoVendorTree(tree), PrepSpec: prepSpec}, nil +} + +func addGoVendorBuildSections(tree *specTree, options GoVendorOptions, configRef string) { + requires := tree.Section("%generate_buildrequires", "") + if requires == nil { + blk := &block{Kind: sectionBlock, Name: "%generate_buildrequires", Header: "%generate_buildrequires"} + buildIndex := slices.Index(tree.root.Children, tree.Section("%build", "").block) + tree.root.Children = slices.Insert(tree.root.Children, buildIndex, blk) + requires = §ionHandle{block: blk, tree: tree} + } + + requires.PrependLines([]string{"%go_vendor_license_buildrequires -c " + configRef}) + + for _, name := range []string{"%build", "%install", "%check", "%generate_buildrequires"} { + if section := tree.Section(name, ""); section != nil { + section.PrependLines([]string{goVendorEnvironment}) + } + } + + tree.Section("%install", "").AppendLines([]string{ + "", goVendorInModule(options.ModuleDir, "%go_vendor_license_install -c "+configRef), + }) + // Licensing is a build invariant, even when the component disables %check. + tree.Section("%build", "").PrependLines([]string{ + goVendorInModule(options.ModuleDir, "%go_vendor_license_check -c "+configRef), + }) + files := tree.Section("%files", "") + files.block.Header += " -f %{go_vendor_license_filelist}" +} + +func (o GoVendorOptions) validate() error { + for _, name := range []string{o.ArchiveName, o.ConfigName} { + if err := fileutils.ValidateFilename(name); err != nil { + return fmt.Errorf("invalid Go vendor artifact name:\n%w", err) + } + + if strings.ContainsAny(name, "%\r\n") { + return errors.New("go vendor artifact name must not contain macros or newlines") + } + } + + if o.ModuleDir != "" { + if err := fileutils.ValidateRelPath(o.ModuleDir); err != nil { + return fmt.Errorf("invalid Go module directory:\n%w", err) + } + + if strings.ContainsAny(o.ModuleDir, "%\r\n") { + return errors.New("go module directory must not contain macros or newlines") + } + } + + return nil +} + +func serializeGoVendorTree(tree *specTree) []byte { + return []byte(strings.Join(serializeTree(tree.root), "\n") + "\n") +} + +func goVendorInModule(moduleDir, command string) string { + lines := []string{`( cd "$(cat "%{_topdir}/azldev-go-module-root")"`} + if moduleDir != "" { + lines = append(lines, "cd "+shellquote.Join(moduleDir)) + } + + lines = append(lines, command, ")") + + return strings.Join(lines, "\n") +} + +func validateGoVendorTree(tree *specTree) error { + if tree.HasSection("%sourcelist") { + return errors.New("go vendoring requires explicit Source tags instead of '%sourcelist'") + } + + for _, name := range []string{"", "%prep", "%build", "%install", "%files"} { + if err := validateGoVendorSection(tree, name, true); err != nil { + return err + } + } + + for _, name := range []string{"%check", "%generate_buildrequires"} { + if err := validateGoVendorSection(tree, name, false); err != nil { + return err + } + } + + var invalid error + + walkBlocks(tree.root, func(blk *block) bool { + if invalid != nil { + return false + } + + invalid = validateGoVendorBlock(blk) + + return true + }) + + return invalid +} + +func validateGoVendorSection(tree *specTree, name string, required bool) error { + sections := tree.Sections(name, "") + if len(sections) == 0 && !required { + return nil + } + + if len(sections) != 1 { + return fmt.Errorf("go vendoring requires one main-package %#q section; use overlays to disambiguate", name) + } + + if !slices.Contains(tree.root.Children, sections[0].block) { + return fmt.Errorf("go vendoring does not support conditional %#q sections; use an overlay", name) + } + + return nil +} + +func validateGoVendorBlock(blk *block) error { + if blk.Kind == macroDefBlock && (blk.Name == "gomodulesmode" || strings.HasPrefix(blk.Name, "go_vendor_")) { + return fmt.Errorf("explicit %#q conflicts with Go vendoring; remove it with an overlay", blk.Name) + } + + for _, line := range append([]string{blk.Header}, blk.Lines...) { + if strings.HasPrefix(strings.TrimSpace(line), "#") { + continue + } + + if macro := goVendorUnsupportedMacro.FindString(line); macro != "" { + return fmt.Errorf("unsupported Go vendoring macro %#q in %#q; adapt it with an overlay", macro, line) + } + + if blk.Kind == macroDefBlock && + (goVendorRequiresMacro.MatchString(line) || goVendorCheckMacro.MatchString(line) || + strings.Contains(line, "golang(")) { + return fmt.Errorf("go dependency or check logic inside a macro definition requires an explicit overlay: %#q", line) + } + + for _, macro := range []string{"-mod=mod", "GO111MODULE=off"} { + if strings.Contains(line, macro) { + return fmt.Errorf("unsupported Go vendoring construct %#q in %#q; adapt it with an overlay", macro, line) + } + } + } + + return nil +} + +func convertGoVendorLines(tree *specTree) error { + return tree.VisitAllLines(func(section, _ string, line *lineHandle) error { + text := strings.TrimSpace(line.Text) + if strings.HasPrefix(text, "#") { + return nil + } + + if tag, value, ok := parseTagLine(text); ok && isTagBearingSection(section) && + strings.EqualFold(tag, "BuildRequires") && strings.Contains(value, "golang(") { + if !goBuildRequirement.MatchString(value) { + return fmt.Errorf("ambiguous Go BuildRequires %#q; split it into individual tags with an overlay", line.Text) + } + + line.Remove() + } + + switch { + case goVendorRequiresMacro.MatchString(text): + if text != "%go_generate_buildrequires" || section != "%generate_buildrequires" { + return fmt.Errorf("unsupported Go dependency generator %#q; adapt it with an overlay", text) + } + + line.Remove() + case goVendorCheckMacro.MatchString(text): + if text != "%gocheck" || section != "%check" { + return fmt.Errorf("unsupported Go check command %#q; use a module-aware check overlay", text) + } + + line.Replace("%gotest ./...") + } + + return nil + }) +} + +func freeGoVendorSources(tree *specTree, options GoVendorOptions) (int, error) { + used := make(map[int]bool) + + err := tree.VisitAllLines(func(section, _ string, line *lineHandle) error { + tag, value, ok := parseTagLine(line.Text) + if !ok || !isTagBearingSection(section) || !strings.HasPrefix(strings.ToLower(tag), "source") { + return nil + } + + suffix := tag[len("source"):] + number := 0 + + if suffix != "" { + var err error + + number, err = strconv.Atoi(suffix) + if err != nil || number < 0 { + return fmt.Errorf("cannot allocate vendor Source tags alongside %#q", tag) + } + } + + used[number] = true + + if value == options.ArchiveName || value == options.ConfigName { + return fmt.Errorf("generated Go vendor source collides with existing Source tag %#q", line.Text) + } + + return nil + }) + if err != nil { + return 0, err + } + + for number := 0; ; number++ { + if !used[number] && !used[number+1] { + return number, nil + } + } +} diff --git a/internal/rpm/spec/govendor_test.go b/internal/rpm/spec/govendor_test.go new file mode 100644 index 000000000..cfed507aa --- /dev/null +++ b/internal/rpm/spec/govendor_test.go @@ -0,0 +1,197 @@ +// 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 vendorInput() string { + return strings.Join([]string{ + "# Upstream customization", + "%global goipath example.com/app", + "Name: app", + "Version: 1.2", + "Release: %autorelease", + "Summary: App", + "License: MIT", + "Source0: app-%{version}.tar.gz", + "Source1: app.service", + "Source9999: app.macros", + "Patch0: fix.patch", + "BuildRequires: golang(example.com/dep) >= 1.0", + "BuildRequires: gcc", + "Requires: systemd", + "", + "%description", + "App description", + "%package tools", + "Summary: Tools", + "Requires: app = %{version}-%{release}", + "%description tools", + "Tool description", + "%prep", + "%goprep -p1", + "sed -i 's/old/new/' go.mod", + "%generate_buildrequires", + "%go_generate_buildrequires", + "echo custom-build-dependency", + "%build", + "%gobuild -o app %{goipath}", + "%install", + "install -D app %{buildroot}%{_bindir}/app", + "%check", + "%if %{with check}", + "%gocheck", + "./custom-test", + "%endif", + "%files", + "%{_bindir}/app", + "%files tools", + "%{_bindir}/tool", + "%changelog", + "%autochangelog", + "", + }, "\n") +} + +func TestConvertGoVendorPreservesUpstream(t *testing.T) { + for _, version := range []string{"1.2", "2.7"} { + t.Run(version, func(t *testing.T) { + input := strings.ReplaceAll(vendorInput(), "Version: 1.2", "Version: "+version) + result, err := spec.ConvertGoVendor([]byte(input), spec.GoVendorOptions{ + ArchiveName: "app-vendor.tar.bz2", ConfigName: "vendor.toml", + }) + require.NoError(t, err) + + output := string(result.Spec) + for _, line := range []string{ + "# Upstream customization", "Version: " + version, "Release: %autorelease", + "Source0: app-%{version}.tar.gz", "Source1: app.service", "Source9999: app.macros", + "Patch0: fix.patch", "BuildRequires: gcc", "Requires: systemd", + "%package tools", "Requires: app = %{version}-%{release}", + "%goprep -p1", "sed -i 's/old/new/' go.mod", "echo custom-build-dependency", + "%gobuild -o app %{goipath}", "install -D app %{buildroot}%{_bindir}/app", + "%if %{with check}\n%gotest ./...\n./custom-test\n%endif", + "%files tools\n%{_bindir}/tool", "%autochangelog", + "Source2: app-vendor.tar.bz2", "Source3: vendor.toml", "tar -xf %{SOURCE2}", + "%go_vendor_license_buildrequires -c %{SOURCE3}", + "%go_vendor_license_check -c %{SOURCE3}", + "%go_vendor_license_install -c %{SOURCE3}", + "%files -f %{go_vendor_license_filelist}", + "GOPROXY=off", "-mod=vendor", "%global gomodulesmode GO111MODULE=on", + } { + assert.Contains(t, output, line) + } + + assert.NotContains(t, output, "BuildRequires: golang(") + assert.NotContains(t, output, "%go_generate_buildrequires") + assert.Contains(t, output, `pwd -P > "%{_topdir}/azldev-go-module-root"`) + assert.Contains(t, output, `%global go_vendor_license_filelist() %{_topdir}/azldev-go-vendor-licenses.list`) + assert.Contains(t, string(result.PrepSpec), "Release: %autorelease") + assert.Contains(t, string(result.PrepSpec), `pwd -P > "%{_topdir}/azldev-go-module-root"`) + assert.Contains(t, string(result.PrepSpec), "sed -i 's/old/new/' go.mod") + assert.NotContains(t, string(result.PrepSpec), "app-vendor.tar.bz2") + assert.Contains(t, string(result.PrepSpec), "%autochangelog") + + _, err = spec.OpenSpec(strings.NewReader(output), spec.WithEditor(spec.EditorStructural)) + require.NoError(t, err) + }) + } +} + +func TestConvertGoVendorRejectsAmbiguity(t *testing.T) { + for name, input := range map[string]string{ + "development subpackages": strings.ReplaceAll(vendorInput(), "%package tools", "%gopkg\n%package tools"), + "mixed requirements": strings.ReplaceAll(vendorInput(), + "golang(example.com/dep) >= 1.0", "gcc, golang(example.com/dep)"), + "check flags": strings.ReplaceAll(vendorInput(), "%gocheck", "%gocheck -z foo"), + "generator shell": strings.ReplaceAll(vendorInput(), + "%go_generate_buildrequires", "%go_generate_buildrequires | cat"), + "conditional prep": strings.ReplaceAll(vendorInput(), + "%prep\n%goprep -p1", "%if 1\n%prep\n%goprep -p1\n%endif"), + "module mode conflict": "%global gomodulesmode GO111MODULE=off\n" + vendorInput(), + "module mode override": "%global gomodulesmode GO111MODULE=on\n" + vendorInput(), + "license check override": "%global go_vendor_license_check_disable 1\n" + vendorInput(), + "existing vendor config": strings.ReplaceAll(vendorInput(), "app.service", "vendor.toml"), + "missing install": strings.ReplaceAll(vendorInput(), "%install", "# install"), + "macro source index": strings.ReplaceAll(vendorInput(), "Source1:", "Source%{number}:"), + "already vendored": strings.ReplaceAll(vendorInput(), "%gocheck", "%go_vendor_license_check"), + "braced generator": strings.ReplaceAll(vendorInput(), + "%go_generate_buildrequires", "%{go_generate_buildrequires}"), + "braced devel macro": strings.ReplaceAll(vendorInput(), "%package tools", "%{gopkg}\n%package tools"), + "hidden generator": "%global dependencies %{go_generate_buildrequires}\n" + vendorInput(), + "go filelist": strings.ReplaceAll(vendorInput(), "%files\n", "%files -f %{gofilelist}\n"), + "unsupported after comment": "# unrelated comment\n%gopkg\n" + vendorInput(), + } { + t.Run(name, func(t *testing.T) { + result, err := spec.ConvertGoVendor([]byte(input), spec.GoVendorOptions{ + ArchiveName: "app-vendor.tar.bz2", ConfigName: "vendor.toml", + }) + require.Error(t, err) + assert.Nil(t, result) + }) + } +} + +func TestConvertGoVendorModuleDirAndStaticRequires(t *testing.T) { + input := strings.ReplaceAll(vendorInput(), + "%generate_buildrequires\n%go_generate_buildrequires\necho custom-build-dependency\n", "") + input = strings.ReplaceAll(input, "%changelog\n%autochangelog\n", "") + result, err := spec.ConvertGoVendor([]byte(input), spec.GoVendorOptions{ + ArchiveName: "app-vendor.tar.bz2", ConfigName: "vendor.toml", ModuleDir: "cmd/app", + }) + require.NoError(t, err) + assert.Contains(t, string(result.Spec), "tar -xf %{SOURCE2} -C cmd/app") + assert.Contains(t, string(result.Spec), "cd cmd/app\n%go_vendor_license_install") + assert.Contains(t, string(result.Spec), `( cd "$(cat "%{_topdir}/azldev-go-module-root")"`) + assert.Contains(t, string(result.Spec), "%generate_buildrequires\n") +} + +func TestConvertGoVendorRejectsUnsafeOptions(t *testing.T) { + for _, options := range []spec.GoVendorOptions{ + {ArchiveName: "../vendor.tar.bz2", ConfigName: "config"}, + {ArchiveName: "vendor", ConfigName: "%{name}"}, + {ArchiveName: "vendor", ConfigName: "config", ModuleDir: "../escape"}, + {ArchiveName: "vendor", ConfigName: "config", ModuleDir: "%{bad}"}, + } { + _, err := spec.ConvertGoVendor([]byte(vendorInput()), options) + require.Error(t, err) + } +} + +func TestConvertGoVendorPreservesStaticReleaseAndCustomDirectories(t *testing.T) { + input := strings.ReplaceAll(vendorInput(), "Release: %autorelease", "Release: 42%{?dist}") + input = strings.ReplaceAll(input, "%check", "cd assets\n%check") + result, err := spec.ConvertGoVendor([]byte(input), spec.GoVendorOptions{ + ArchiveName: "app-vendor.tar.bz2", ConfigName: "vendor.toml", + }) + require.NoError(t, err) + assert.Contains(t, string(result.PrepSpec), "Release: 42%{?dist}") + assert.Contains(t, string(result.Spec), "cd assets") + assert.Contains(t, string(result.Spec), + `( cd "$(cat "%{_topdir}/azldev-go-module-root")"`+"\n%go_vendor_license_install") + assert.Contains(t, string(result.Spec), + "%global go_vendor_license_filelist() %{_topdir}/azldev-go-vendor-licenses.list") +} + +func TestConvertGoVendorPreservesNonTagsAndComments(t *testing.T) { + script := "cat <<'EOF' > metadata\nBuildRequires: golang(not-a-dependency)\nSource2: not-a-source\nEOF\n" + input := strings.ReplaceAll(vendorInput(), "%gobuild", script+"%gobuild") + input = "# %gopkg is intentionally not invoked\n" + input + input = strings.ReplaceAll(input, "%files\n", "%files\n# app files\n") + result, err := spec.ConvertGoVendor([]byte(input), spec.GoVendorOptions{ + ArchiveName: "app-vendor.tar.bz2", ConfigName: "vendor.toml", + }) + require.NoError(t, err) + assert.Contains(t, string(result.Spec), script) + assert.Contains(t, string(result.Spec), "Source2: app-vendor.tar.bz2") + assert.Contains(t, string(result.Spec), "# %gopkg is intentionally not invoked") + assert.Contains(t, string(result.Spec), "%files -f %{go_vendor_license_filelist}\n# app files") +} diff --git a/scenario/__snapshots__/TestSnapshots_config_generate-schema_stdout_1.snap b/scenario/__snapshots__/TestSnapshots_config_generate-schema_stdout_1.snap index 9cf47bd35..65c59d83a 100755 --- a/scenario/__snapshots__/TestSnapshots_config_generate-schema_stdout_1.snap +++ b/scenario/__snapshots__/TestSnapshots_config_generate-schema_stdout_1.snap @@ -150,6 +150,11 @@ "title": "Source files", "description": "Source files to download for this component" }, + "go-vendor": { + "$ref": "#/$defs/GoVendorConfig", + "title": "Go vendoring", + "description": "Convert a Go application spec and generate its vendor archive during source preparation" + }, "packages": { "additionalProperties": { "$ref": "#/$defs/PackageConfig" @@ -682,6 +687,35 @@ "additionalProperties": false, "type": "object" }, + "GoVendorConfig": { + "properties": { + "enabled": { + "type": "boolean", + "title": "Enabled", + "description": "Enable Go application vendoring" + }, + "module-dir": { + "type": "string", + "title": "Module directory", + "description": "Relative module directory within the prepared source tree; defaults to its root" + }, + "tool-config": { + "type": "string", + "title": "Tool configuration", + "description": "Inline go-vendor-tools TOML for dependency overrides and licensing settings" + }, + "prep-packages": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Prep packages", + "description": "Additional RPM packages needed to execute the upstream prep section in mock" + } + }, + "additionalProperties": false, + "type": "object" + }, "ImageCapabilities": { "properties": { "machine-bootable": { diff --git a/schemas/azldev.schema.json b/schemas/azldev.schema.json index 9cf47bd35..65c59d83a 100644 --- a/schemas/azldev.schema.json +++ b/schemas/azldev.schema.json @@ -150,6 +150,11 @@ "title": "Source files", "description": "Source files to download for this component" }, + "go-vendor": { + "$ref": "#/$defs/GoVendorConfig", + "title": "Go vendoring", + "description": "Convert a Go application spec and generate its vendor archive during source preparation" + }, "packages": { "additionalProperties": { "$ref": "#/$defs/PackageConfig" @@ -682,6 +687,35 @@ "additionalProperties": false, "type": "object" }, + "GoVendorConfig": { + "properties": { + "enabled": { + "type": "boolean", + "title": "Enabled", + "description": "Enable Go application vendoring" + }, + "module-dir": { + "type": "string", + "title": "Module directory", + "description": "Relative module directory within the prepared source tree; defaults to its root" + }, + "tool-config": { + "type": "string", + "title": "Tool configuration", + "description": "Inline go-vendor-tools TOML for dependency overrides and licensing settings" + }, + "prep-packages": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Prep packages", + "description": "Additional RPM packages needed to execute the upstream prep section in mock" + } + }, + "additionalProperties": false, + "type": "object" + }, "ImageCapabilities": { "properties": { "machine-bootable": { From c7e4bc2764db6da3a94f3ab71740b7db80fc26a9 Mon Sep 17 00:00:00 2001 From: Antonio Salinas <173939267+Tonisal-byte@users.noreply.github.com> Date: Sun, 1 Nov 2026 11:47:14 -0800 Subject: [PATCH 02/16] feat: regenerate existing Go vendor sources Preserve upstream Source entries, tool configuration, and reviewed licenses when regenerating already-vendored packages. Use a common spec plan and reusable Go-only generation backend. Keep command construction in Go, automatically clone component configuration while retaining shared back-references, and exclude payloads from rendered specs. Add regression coverage and document both workflows. Validation: unit tests, build, and all quality checks passed. All ten prepared containerd files are byte-for-byte identical to the pre-refactor baseline. Full Mage scenarios remain blocked by Docker provider initialization in this WSL environment. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/instructions/go.instructions.md | 3 + docs/user/how-to/vendor-go-application.md | 30 +- .../reference/cli/azldev_component_render.md | 6 +- docs/user/reference/config/components.md | 9 +- .../agentskill/content/comp-toml.md.tmpl | 5 +- .../content/withoutlockfile/comp-toml.md.tmpl | 5 +- internal/app/azldev/cmds/component/render.go | 12 +- .../azldev/cmds/component/render_govendor.go | 53 ++++ .../render_govendor_internal_test.go | 51 +++ internal/app/azldev/core/sources/govendor.go | 300 +++++------------- .../govendor_existing_internal_test.go | 97 ++++++ .../core/sources/govendor_internal_test.go | 25 +- internal/govendor/generate.go | 253 +++++++++++++++ internal/govendor/generate_internal_test.go | 88 +++++ internal/projectconfig/component.go | 37 +-- .../component_clone_internal_test.go | 36 +++ internal/projectconfig/govendor_test.go | 1 + internal/rpm/spec/govendor.go | 74 ++++- internal/rpm/spec/govendor_existing.go | 212 +++++++++++++ internal/rpm/spec/govendor_existing_test.go | 87 +++++ internal/rpm/spec/govendor_test.go | 5 +- 21 files changed, 1104 insertions(+), 285 deletions(-) create mode 100644 internal/app/azldev/cmds/component/render_govendor.go create mode 100644 internal/app/azldev/cmds/component/render_govendor_internal_test.go create mode 100644 internal/app/azldev/core/sources/govendor_existing_internal_test.go create mode 100644 internal/govendor/generate.go create mode 100644 internal/govendor/generate_internal_test.go create mode 100644 internal/projectconfig/component_clone_internal_test.go create mode 100644 internal/rpm/spec/govendor_existing.go create mode 100644 internal/rpm/spec/govendor_existing_test.go 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/user/how-to/vendor-go-application.md b/docs/user/how-to/vendor-go-application.md index c0b430642..068673213 100644 --- a/docs/user/how-to/vendor-go-application.md +++ b/docs/user/how-to/vendor-go-application.md @@ -3,7 +3,8 @@ Use `go-vendor` to bundle a Go application's module dependencies instead of building against separately packaged `golang(...)` libraries. This is a targeted conversion of the selected upstream spec, not a `go2rpm` wrapper or a newly -generated replacement spec. +generated replacement spec. The same setting regenerates sources for supported +specs that already use go-vendor-tools. ## Enable and prepare @@ -64,17 +65,40 @@ Custom build/install commands must already address that same module. Conditional commands within those sections are retained. Automatic Go development subpackages (`%gopkg`, `%goinstall`, Go file-list macros), -flagged `%gocheck` commands, compound/rich Go BuildRequires, existing vendor -macros, explicit conflicting module-mode settings, and ambiguous/conditional +flagged `%gocheck` commands, compound/rich Go BuildRequires, +explicit conflicting module-mode settings, and ambiguous/conditional target sections are rejected. Use narrowly scoped overlays to adapt these cases; azldev does not silently drop subpackages or rewrite arbitrary shell scripts. +## Regenerate an existing vendor archive + +For an already-vendored spec, azldev recognizes a single +`tar -xf %{S:N}` (or `%{SOURCEN}`) prep command and the configuration source +referenced by `%go_vendor_license_* -c %{S:M}` commands. The Source numbers need +not be 1 and 2. The configuration must name a plain sidecar file. + +The original Source declarations, extraction command, license/file-list macros, +module-mode settings, and custom packaging are retained. The temporary prep spec +omits the vendor Source declaration and its extraction command, so generating +the replacement does not consume the old vendor payload. RPM expands the +upstream archive filename; the regenerated archive replaces that file and its +`sources` checksum rather than adding a second vendor archive. + +When `tool-config` is omitted, the upstream go-vendor-tools configuration is used, +including its reviewed license exceptions. An explicit `tool-config` replaces +that configuration. The detected licenses are verified against the existing +main-package `License:` expression; mismatches fail instead of rewriting it. +The source-fetch phase currently still downloads the upstream vendor archive +alongside the other upstream sources, before regenerating its contents. + ## Review and upgrade Run `azldev component diff-sources -p example` to inspect the conversion, or `azldev component render -p example` to refresh checked-in rendered output. Rendering and source diffs also generate the archive: they need network access and can be substantially slower for enabled components. +Rendered output retains the `sources` checksums but excludes payloads listed in +that manifest; archives remain preparation/build artifacts rather than checked-in files. Review the cumulative license expression and the retained build/install/check commands before building. Automatic detection is not approval of a dependency's diff --git a/docs/user/reference/cli/azldev_component_render.md b/docs/user/reference/cli/azldev_component_render.md index 88a9d5157..239018bd4 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 source downloads. Go vendoring downloads and prepares sources for archive generation +and license checks, but excludes payloads from checked-in output. Only specs, patches, scripts, checksums, +and sidecar files are included. 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 33b7cbf8d..d16fffc7b 100644 --- a/docs/user/reference/config/components.md +++ b/docs/user/reference/config/components.md @@ -182,7 +182,7 @@ enabled = true | `enabled` | boolean | `false` | Enable conversion and vendor archive generation. An explicit `false` overrides inherited enablement. | | `module-dir` | string | `""` | Relative directory containing `go.mod`, resolved from the working directory at the end of the upstream `%prep` section. Empty uses that directory itself. No absolute paths, traversal, or RPM macros. | | `prep-packages` | array of string | `[]` | Additional RPM packages needed by upstream `%prep` commands or the selected license detector. Installed only in the isolated generation chroot. | -| `tool-config` | string | `""` | Inline [go-vendor-tools TOML](https://fedora.gitlab.io/sigs/go/go-vendor-tools/config/), for dependency overrides, archive options, and reviewed license exceptions. Use `module-dir`, not `general.go_mod_dir`. | +| `tool-config` | string | `""` | Inline [go-vendor-tools TOML](https://fedora.gitlab.io/sigs/go/go-vendor-tools/config/), for dependency overrides, archive options, and reviewed license exceptions. When omitted for an already-vendored spec, reuse its upstream tool configuration. An explicit value replaces it. Use `module-dir`, not `general.go_mod_dir`. | The tool configuration is inline so its contents participate in component fingerprinting without checkout-dependent paths. Configured command hooks execute @@ -198,13 +198,18 @@ tool-config = ''' ''' ``` -Preparation emits `-vendor.tar.bz2` and `azldev-go-vendor.toml`, +For previously unbundled specs, preparation emits `-vendor.tar.bz2` and `azldev-go-vendor.toml`, allocating unused `Source` numbers automatically. These names are reserved for generated output; do not also declare them in `source-files` or supply them through overlays. The archive's SHA-512 digest is recorded in the prepared `sources` file. Generation runs afresh on every preparation; there is no filename-based cache. The recorded digest identifies that output, not a separately pinned vendor lock. +For supported specs already using go-vendor-tools, preparation instead regenerates +the existing vendor source, retaining its Source number, RPM-expanded filename, +and configuration sidecar. It updates that archive's `sources` entry in place and +verifies the existing `License:` expression without rewriting it. + All archive/spec/loose-file overlays run before conversion. Source preparation, builds, rendering (including `--check-only`), and source diffs use the same conversion. Enabled components require downloads even with `--skip-sources`, diff --git a/internal/app/azldev/agentskill/content/comp-toml.md.tmpl b/internal/app/azldev/agentskill/content/comp-toml.md.tmpl index 1462c24c3..a6dbf477e 100644 --- a/internal/app/azldev/agentskill/content/comp-toml.md.tmpl +++ b/internal/app/azldev/agentskill/content/comp-toml.md.tmpl @@ -46,7 +46,10 @@ Use `module-dir` for a module below the final prep working directory, `prep-packages` for additional chroot tools, and inline `tool-config` for go-vendor-tools dependency overrides or reviewed license exceptions. Generated `-vendor.tar.bz2` and `azldev-go-vendor.toml` must not also be -declared as `source-files`. Unsupported constructs (notably automatic Go devel +declared as `source-files`. For supported already-vendored specs, regenerate the +existing vendor Source instead, reuse upstream tool configuration unless overridden, +and verify rather than replace the reviewed `License:` expression. +Unsupported constructs (notably automatic Go devel subpackages, flagged `%gocheck`, or ambiguous sections) require explicit overlays; never replace the upstream spec wholesale to bypass a conversion error. 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 c1f972f5d..96690b936 100644 --- a/internal/app/azldev/agentskill/content/withoutlockfile/comp-toml.md.tmpl +++ b/internal/app/azldev/agentskill/content/withoutlockfile/comp-toml.md.tmpl @@ -46,7 +46,10 @@ Use `module-dir` for a module below the final prep working directory, `prep-packages` for additional chroot tools, and inline `tool-config` for go-vendor-tools dependency overrides or reviewed license exceptions. Generated `-vendor.tar.bz2` and `azldev-go-vendor.toml` must not also be -declared as `source-files`. Unsupported constructs (notably automatic Go devel +declared as `source-files`. For supported already-vendored specs, regenerate the +existing vendor Source instead, reuse upstream tool configuration unless overridden, +and verify rather than replace the reviewed `License:` expression. +Unsupported constructs (notably automatic Go devel subpackages, flagged `%gocheck`, or ambiguous sections) require explicit overlays; never replace the upstream spec wholesale to bypass a conversion error. diff --git a/internal/app/azldev/cmds/component/render.go b/internal/app/azldev/cmds/component/render.go index 6f4277743..e9df2be13 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 source downloads. Go vendoring downloads and prepares sources for archive generation +and license checks, but excludes payloads from checked-in output. Only specs, patches, scripts, checksums, +and sidecar files are included. 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 @@ -765,6 +765,12 @@ func finishComponentRender( return false, fmt.Errorf("filtering unreferenced files for %#q:\n%w", componentName, filterErr) } + if err := removeGoVendorRenderPayloads( + env.FS(), componentDir, prep.comp.GetConfig().GoVendor.IsEnabled(), + ); err != nil { + return false, fmt.Errorf("removing generated render payloads for %#q:\n%w", componentName, err) + } + // Remove .git directory — must not appear in rendered output. // rpmautospec already read it during the batch mock phase. gitDir := filepath.Join(componentDir, ".git") diff --git a/internal/app/azldev/cmds/component/render_govendor.go b/internal/app/azldev/cmds/component/render_govendor.go new file mode 100644 index 000000000..bcfae2005 --- /dev/null +++ b/internal/app/azldev/cmds/component/render_govendor.go @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package component + +import ( + "errors" + "fmt" + "os" + "path/filepath" + + "github.com/microsoft/azure-linux-dev-tools/internal/global/opctx" + "github.com/microsoft/azure-linux-dev-tools/internal/providers/sourceproviders/fedorasource" + "github.com/microsoft/azure-linux-dev-tools/internal/utils/fileutils" +) + +// Vendoring needs real payloads during preparation, but rendered dist-git output +// must contain their manifest rather than copying source archives into the repository. +func removeGoVendorRenderPayloads(fs opctx.FS, directory string, enabled bool) error { + if !enabled { + return nil + } + + contents, err := fileutils.ReadFile(fs, filepath.Join(directory, fedorasource.SourcesFileName)) + if errors.Is(err, os.ErrNotExist) { + return nil + } + + if err != nil { + return fmt.Errorf("reading render source manifest:\n%w", err) + } + + lines, err := fedorasource.ReadSourcesFile(string(contents)) + if err != nil { + return fmt.Errorf("parsing render source manifest:\n%w", err) + } + + for _, line := range lines { + if line.Entry == nil { + continue + } + + if err := fileutils.ValidateFilename(line.Entry.Filename); err != nil { + return fmt.Errorf("invalid render source filename:\n%w", err) + } + + if err := fs.Remove(filepath.Join(directory, line.Entry.Filename)); err != nil && !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("removing render source payload %#q:\n%w", line.Entry.Filename, err) + } + } + + return nil +} diff --git a/internal/app/azldev/cmds/component/render_govendor_internal_test.go b/internal/app/azldev/cmds/component/render_govendor_internal_test.go new file mode 100644 index 000000000..e6b336335 --- /dev/null +++ b/internal/app/azldev/cmds/component/render_govendor_internal_test.go @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package component + +import ( + "strings" + "testing" + + "github.com/microsoft/azure-linux-dev-tools/internal/global/testctx" + "github.com/microsoft/azure-linux-dev-tools/internal/providers/sourceproviders/fedorasource" + "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 TestRemoveGoVendorRenderPayloads(t *testing.T) { + for _, enabled := range []bool{false, true} { + ctx := testctx.NewCtx() + + manifest := "# keep manifest\n" + + fedorasource.FormatSourcesEntry("upstream.tar.gz", fileutils.HashTypeSHA512, strings.Repeat("a", 128)) + "\n" + + fedorasource.FormatSourcesEntry("vendor.tar.bz2", fileutils.HashTypeSHA512, strings.Repeat("b", 128)) + "\n" + for name, content := range map[string]string{ + "app.spec": "spec", "config.toml": "[archive]", "sources": manifest, + "upstream.tar.gz": "source", "vendor.tar.bz2": "vendor", + } { + require.NoError(t, fileutils.WriteFile(ctx.FS(), "/render/"+name, []byte(content), fileperms.PublicFile)) + } + + require.NoError(t, removeGoVendorRenderPayloads(ctx.FS(), "/render", enabled)) + + for _, name := range []string{"upstream.tar.gz", "vendor.tar.bz2"} { + exists, err := fileutils.Exists(ctx.FS(), "/render/"+name) + require.NoError(t, err) + assert.Equal(t, !enabled, exists) + } + + for _, name := range []string{"app.spec", "config.toml", "sources"} { + exists, err := fileutils.Exists(ctx.FS(), "/render/"+name) + require.NoError(t, err) + assert.True(t, exists) + } + + data, err := fileutils.ReadFile(ctx.FS(), "/render/sources") + require.NoError(t, err) + assert.Equal(t, manifest, string(data)) + require.NoError(t, removeGoVendorRenderPayloads(ctx.FS(), "/render", enabled)) + } +} diff --git a/internal/app/azldev/core/sources/govendor.go b/internal/app/azldev/core/sources/govendor.go index c6314e3a8..4d2e42b54 100644 --- a/internal/app/azldev/core/sources/govendor.go +++ b/internal/app/azldev/core/sources/govendor.go @@ -4,37 +4,24 @@ package sources import ( - "bytes" "context" "errors" "fmt" "log/slog" "path/filepath" + "slices" "strings" - "time" - "github.com/kballard/go-shellquote" "github.com/microsoft/azure-linux-dev-tools/internal/app/azldev/core/components" - "github.com/microsoft/azure-linux-dev-tools/internal/projectconfig" + "github.com/microsoft/azure-linux-dev-tools/internal/govendor" "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/rpm/spectool" "github.com/microsoft/azure-linux-dev-tools/internal/utils/fileperms" "github.com/microsoft/azure-linux-dev-tools/internal/utils/fileutils" ) -const ( - goVendorMount = "/azldev-go-vendor" - goVendorTopDir = "/tmp/azldev-go-rpm" - goVendorBuild = goVendorTopDir + "/BUILD" - goVendorConfig = "azldev-go-vendor.toml" - goVendorScratch = "/azldev-go-scratch" - goVendorCleanupTimeout = 5 * time.Minute -) - -// WithGoVendorRunner provides a template runner. Every conversion uses a fresh, -// isolated root; only the component staging directory is exposed to it. +// WithGoVendorRunner provides a template for an isolated generation root. func WithGoVendorRunner(runner *mock.Runner) PreparerOption { return func(p *sourcePreparerImpl) { p.goVendorRunner = runner } } @@ -52,7 +39,7 @@ func (p *sourcePreparerImpl) prepareGoVendor( } if p.dryRunnable.DryRun() { - slog.Info("Dry run; skipping Go vendor conversion and archive generation", "component", component.GetName()) + slog.Info("Dry run; skipping Go vendor generation", "component", component.GetName()) return nil } @@ -61,8 +48,6 @@ func (p *sourcePreparerImpl) prepareGoVendor( return errors.New("go vendoring requires a mock runner with the project's build distro configuration") } - archiveName := component.GetName() + "-vendor.tar.bz2" - specPath, err := p.resolveSpecPath(component, outputDir) if err != nil { return err @@ -73,14 +58,16 @@ func (p *sourcePreparerImpl) prepareGoVendor( return fmt.Errorf("reading Go spec:\n%w", err) } - converted, err := spec.ConvertGoVendor(data, spec.GoVendorOptions{ - ArchiveName: archiveName, ConfigName: goVendorConfig, ModuleDir: config.ModuleDir, + plan, err := spec.ConvertGoVendor(data, spec.GoVendorOptions{ + ArchiveName: component.GetName() + "-vendor.tar.bz2", + ConfigName: govendor.ConfigFilename, ModuleDir: config.ModuleDir, }) if err != nil { - return fmt.Errorf("converting Go spec for %#q:\n%w", component.GetName(), err) + return fmt.Errorf("planning Go vendoring for %#q:\n%w", component.GetName(), err) } - if err := p.checkGoVendorSourceCollision(outputDir, archiveName); err != nil { + toolConfig, err := p.resolveGoVendorConfig(outputDir, plan, config.ToolConfig) + if err != nil { return err } @@ -90,200 +77,76 @@ func (p *sourcePreparerImpl) prepareGoVendor( } defer fileutils.RemoveAllAndUpdateErrorIfNil(p.fs, scratch, &err) - staging := filepath.Join(scratch, "work") - if err := fileutils.MkdirAll(p.fs, staging); err != nil { - return fmt.Errorf("creating Go vendor staging directory:\n%w", err) - } - - sourceCopy := filepath.Join(scratch, "sources") - if err := p.stageGoVendorInputs(outputDir, sourceCopy, staging, filepath.Base(specPath), - converted.PrepSpec, config.ToolConfig); err != nil { - return err - } + slog.Info("Generating Go vendor archive", "spec", filepath.Base(specPath), "regenerating", plan.AllowReplacement) - runner := p.goVendorRunner.Clone().WithBaseDir(filepath.Join(scratch, "mock")). - EnableNetwork().WithUnprivileged() - runner.AddBindMount(sourceCopy, goVendorMount) - runner.AddBindMount(staging, goVendorScratch) - - if err := p.runGoVendor(ctx, runner, archiveName, filepath.Base(specPath), config); err != nil { - return err - } - - if err := p.validateGoVendorInputs(staging, outputDir); err != nil { - return err + artifact, err := govendor.Generate(ctx, p.fs, p.goVendorRunner, govendor.Request{ + SourceDir: outputDir, WorkDir: scratch, SpecName: filepath.Base(specPath), PrepSpec: plan.PrepSpec, + ArchiveFile: plan.ArchiveFile, ArchiveSuffix: plan.ArchiveSuffix, ModuleDir: config.ModuleDir, + ToolConfig: toolConfig, Packages: config.PrepPackages, ExpectedLicense: plan.ExpectedLicense, + }) + if err != nil { + return fmt.Errorf("generating Go vendor sources:\n%w", err) } - return p.publishGoVendor(staging, outputDir, specPath, archiveName, converted.Spec, config.ToolConfig) + return p.publishGoVendor(outputDir, filepath.Base(specPath), toolConfig, plan, artifact) } -func (p *sourcePreparerImpl) stageGoVendorInputs( - outputDir, sourceCopy, staging, specFilename string, prepSpec []byte, toolConfig string, -) error { - if err := fileutils.CopyDirRecursive(p.dryRunnable, p.fs, outputDir, sourceCopy, - fileutils.CopyDirOptions{CopyFileOptions: fileutils.CopyFileOptions{PreserveFileMode: true}}); err != nil { - return fmt.Errorf("copying Go sources for isolated prep:\n%w", err) +func (p *sourcePreparerImpl) resolveGoVendorConfig( + outputDir string, plan *spec.GoVendorSpec, configured string, +) (string, error) { + if !plan.AllowReplacement { + if err := p.checkGoVendorSourceCollision(outputDir, plan.ArchiveFile, plan.ConfigName); err != nil { + return "", err + } } - if err := fileutils.WriteFile(p.fs, - filepath.Join(sourceCopy, specFilename), prepSpec, fileperms.PublicFile); err != nil { - return fmt.Errorf("staging Go prep spec:\n%w", err) + if configured != "" || !plan.AllowReplacement { + return configured, nil } - if err := fileutils.WriteFile(p.fs, filepath.Join(staging, goVendorConfig), - []byte(toolConfig), fileperms.PublicFile); err != nil { - return fmt.Errorf("staging Go vendor tool configuration:\n%w", err) + data, err := fileutils.ReadFile(p.fs, filepath.Join(outputDir, plan.ConfigName)) + if err != nil { + return "", fmt.Errorf("reading upstream Go vendor configuration:\n%w", err) } - return nil + return string(data), nil } func (p *sourcePreparerImpl) publishGoVendor( - staging, outputDir, specPath, archiveName string, data []byte, toolConfig string, + outputDir, specName, toolConfig string, plan *spec.GoVendorSpec, artifact govendor.Artifact, ) error { - archiveInfo, err := p.fs.Stat(filepath.Join(staging, archiveName)) - if err != nil { - return fmt.Errorf("missing generated Go vendor archive:\n%w", err) - } - - if !archiveInfo.Mode().IsRegular() || archiveInfo.Size() == 0 { - return errors.New("generated Go vendor archive must be a nonempty regular file") - } - - license, err := fileutils.ReadFile(p.fs, filepath.Join(staging, "license")) - if err != nil { - return fmt.Errorf("reading Go vendor license report:\n%w", err) - } - - expression := strings.TrimSpace(string(license)) - if expression == "" || strings.ContainsAny(expression, "\r\n%") { - return fmt.Errorf("invalid license expression returned by 'go_vendor_license': %#q", expression) + if !plan.AllowReplacement && artifact.Name != plan.ArchiveFile { + return fmt.Errorf("generated Go archive %#q does not match planned name %#q", artifact.Name, plan.ArchiveFile) } - editor, err := spec.OpenSpec(bytes.NewReader(data), spec.WithEditor(spec.EditorStructural)) + finalSpec, err := plan.FinalizeLicense(artifact.License) if err != nil { - return fmt.Errorf("reading converted Go spec:\n%w", err) - } - - if err := editor.UpdateExistingTag("", "License", expression); err != nil { - return fmt.Errorf("updating bundled Go licenses:\n%w", err) + return fmt.Errorf("finalizing Go vendor spec:\n%w", err) } - var finalSpec bytes.Buffer - if err := editor.Serialize(&finalSpec); err != nil { - return fmt.Errorf("serializing converted Go spec:\n%w", err) - } - // Publish only after generation and license detection succeed. - if err := fileutils.CopyFile(p.dryRunnable, p.fs, - filepath.Join(staging, archiveName), filepath.Join(outputDir, archiveName), fileutils.CopyFileOptions{}); err != nil { + if err := fileutils.CopyFile(p.dryRunnable, p.fs, artifact.Path, + filepath.Join(outputDir, artifact.Name), fileutils.CopyFileOptions{}); err != nil { return fmt.Errorf("publishing Go vendor archive:\n%w", err) } - for name, contents := range map[string][]byte{ - filepath.Base(specPath): finalSpec.Bytes(), - goVendorConfig: []byte(toolConfig), - } { + for name, contents := range map[string][]byte{specName: finalSpec, plan.ConfigName: []byte(toolConfig)} { if err := fileutils.WriteFile(p.fs, filepath.Join(outputDir, name), contents, fileperms.PublicFile); err != nil { return fmt.Errorf("publishing Go vendor file %#q:\n%w", name, err) } } - return p.recordGoVendorArchive(outputDir, archiveName) -} - -func (p *sourcePreparerImpl) runGoVendor( - ctx context.Context, runner *mock.Runner, archiveName, specFilename string, config *projectconfig.GoVendorConfig, -) (err error) { - defer func() { - cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), goVendorCleanupTimeout) - defer cancel() - - if scrubErr := runner.ScrubRoot(cleanupCtx); scrubErr != nil { - slog.Error("Failed to clean Go vendor mock root", "error", scrubErr) - - if err == nil { - err = scrubErr - } - } - }() - - if err := runner.InitRoot(ctx); err != nil { - return fmt.Errorf("initializing Go vendor mock root:\n%w", err) - } - - packages := append([]string{ - "go-vendor-tools", "askalono-cli", "golang", "go-rpm-macros", "rpm-build", "rpmdevtools", - "rpmautospec", "git", "python3-click", - }, config.PrepPackages...) - if err := runner.InstallPackages(ctx, packages); err != nil { - return fmt.Errorf("installing Go vendor prerequisites:\n%w", err) - } - - cmd, err := runner.CmdInChroot(ctx, []string{ - "bash", "-euo", "pipefail", "-c", - goVendorScript(archiveName, config.ModuleDir, runner.ConfigOpts()["target_arch"], specFilename), - }, false) - if err != nil { - return fmt.Errorf("constructing Go vendor command:\n%w", err) - } - - output, err := cmd.RunAndGetOutput(ctx) - if err != nil { - return fmt.Errorf("go vendor generation or license detection failed; use 'prep-packages' for missing prep tools "+ - "and 'tool-config' for reviewed license exceptions:\n%s\n%w", output, err) - } - - return nil -} - -func goVendorScript(archiveName, moduleDir, targetArch, specFilename string) string { - if moduleDir == "" { - moduleDir = "." - } - - quote := shellquote.Join - - prepArgs := []string{ - "rpmbuild", "-bp", "--nodeps", "--define", "_topdir /tmp/azldev-go-rpm", - "--define", "_builddir " + goVendorBuild, "--define", "_sourcedir " + goVendorMount, - } - if targetArch != "" { - prepArgs = append(prepArgs, "--target", targetArch) - } - - prepArgs = append(prepArgs, goVendorMount+"/"+specFilename) - - return strings.Join([]string{ - "cd " + goVendorMount, - "mkdir -p " + goVendorBuild, - quote("git", "config", "--global", "--add", "safe.directory", goVendorMount), - quote("rpmautospec", "process-distgit", specFilename, specFilename), - quote(prepArgs...), - `IFS= read -r module_root < ` + goVendorTopDir + "/azldev-go-module-root", - `cd "$module_root"`, - "cd " + quote(moduleDir), - "test -f go.mod", - "export GOTOOLCHAIN=local", - quote("go_vendor_archive", "create", "--config", goVendorScratch+"/"+goVendorConfig, - "--output", goVendorScratch+"/"+archiveName, "."), - quote("tar", "-xf", goVendorScratch+"/"+archiveName), - quote("go_vendor_license", "--config", goVendorScratch+"/"+goVendorConfig, "--path", ".", - "report", "--no-prompt", "--autofill", "off", "expression") + " > " + goVendorScratch + "/license", - "cd " + goVendorMount, - quote("spectool", "--define", "_sourcedir "+goVendorMount, "-l", "-a", - specFilename) + " > " + goVendorScratch + "/sources-list", - }, "\n") + return p.recordGoVendorArchive(outputDir, artifact, plan.AllowReplacement) } -func (p *sourcePreparerImpl) checkGoVendorSourceCollision(outputDir, name string) error { - for _, filename := range []string{name, goVendorConfig} { - exists, err := fileutils.Exists(p.fs, filepath.Join(outputDir, filename)) +func (p *sourcePreparerImpl) checkGoVendorSourceCollision(outputDir string, names ...string) error { + for _, name := range names { + exists, err := fileutils.Exists(p.fs, filepath.Join(outputDir, name)) if err != nil { return fmt.Errorf("checking generated Go source path:\n%w", err) } if exists { - return fmt.Errorf("generated Go vendor file %#q conflicts with an existing source", filename) + return fmt.Errorf("generated Go vendor file %#q conflicts with an existing source", name) } } @@ -298,36 +161,34 @@ func (p *sourcePreparerImpl) checkGoVendorSourceCollision(outputDir, name string } for _, line := range lines { - if line.Entry != nil && line.Entry.Filename == name { - return fmt.Errorf("generated Go vendor archive %#q conflicts with an upstream 'sources' entry", name) + if line.Entry != nil && slices.Contains(names, line.Entry.Filename) { + return fmt.Errorf("generated Go vendor file %#q conflicts with an upstream 'sources' entry", line.Entry.Filename) } } return nil } -func (p *sourcePreparerImpl) recordGoVendorArchive(outputDir, name string) error { - hash, err := fileutils.ComputeFileHash(p.fs, fileutils.HashTypeSHA512, filepath.Join(outputDir, name)) - if err != nil { - return fmt.Errorf("hashing generated Go vendor archive:\n%w", err) - } +func (p *sourcePreparerImpl) recordGoVendorArchive(outputDir string, artifact govendor.Artifact, replace bool) error { + path := filepath.Join(outputDir, fedorasource.SourcesFileName) - content, err := p.readSourcesFileIfExists(filepath.Join(outputDir, fedorasource.SourcesFileName)) + content, err := p.readSourcesFileIfExists(path) if err != nil { return err } - content = strings.TrimRight(content, "\n") - if content != "" { - content += "\n" + content, err = upsertGoVendorEntry(content, artifact, replace) + if err != nil { + return err } - content += fedorasource.FormatSourcesEntry(name, fileutils.HashTypeSHA512, hash) + "\n" - if err := fileutils.WriteFile(p.fs, filepath.Join(outputDir, fedorasource.SourcesFileName), - []byte(content), fileperms.PublicFile); err != nil { + if err := fileutils.WriteFile(p.fs, path, []byte(content), fileperms.PublicFile); err != nil { return fmt.Errorf("recording Go vendor digest:\n%w", err) } - // Generated payloads belong in lookaside storage, not synthetic git commits. + + slog.Info("Recorded generated Go vendor archive", "filename", artifact.Name, + "hashType", fileutils.HashTypeSHA512, "hash", artifact.Digest) + ignorePath := filepath.Join(outputDir, ".gitignore") ignore, err := p.readSourcesFileIfExists(ignorePath) @@ -335,39 +196,46 @@ func (p *sourcePreparerImpl) recordGoVendorArchive(outputDir, name string) error return err } + for _, line := range strings.Split(ignore, "\n") { + if strings.TrimPrefix(line, "/") == artifact.Name { + return nil + } + } + if err := fileutils.WriteFile(p.fs, ignorePath, - []byte(strings.TrimRight(ignore, "\n")+"\n/"+name+"\n"), fileperms.PublicFile); err != nil { + []byte(strings.TrimRight(ignore, "\n")+"\n/"+artifact.Name+"\n"), fileperms.PublicFile); err != nil { return fmt.Errorf("ignoring generated Go archive in git:\n%w", err) } return nil } -func (p *sourcePreparerImpl) validateGoVendorInputs(scratch, outputDir string) error { - data, err := fileutils.ReadFile(p.fs, filepath.Join(scratch, "sources-list")) +func upsertGoVendorEntry(content string, artifact govendor.Artifact, replace bool) (string, error) { + lines, err := fedorasource.ReadSourcesFile(strings.TrimRight(content, "\n")) if err != nil { - return fmt.Errorf("reading prepared Go source list:\n%w", err) + return "", fmt.Errorf("parsing Go vendor source manifest:\n%w", err) } - for _, line := range strings.Split(strings.TrimSpace(string(data)), "\n") { - if line == "" { - continue - } + entry := fedorasource.FormatSourcesEntry(artifact.Name, fileutils.HashTypeSHA512, artifact.Digest) + raw := make([]string, 0, len(lines)+1) + found := false - files := spectool.ParseSpectoolOutput(line) - if len(files) != 1 || strings.Contains(files[0], "%") { - return fmt.Errorf("cannot resolve Go source/patch reference %#q", line) - } + for _, line := range lines { + value := line.Raw + if line.Entry != nil && line.Entry.Filename == artifact.Name { + if !replace { + return "", fmt.Errorf("go vendor source %#q already exists", artifact.Name) + } - info, err := p.fs.Stat(filepath.Join(outputDir, files[0])) - if err != nil { - return fmt.Errorf("missing prepared Go source/patch %#q:\n%w", files[0], err) + value, found = entry, true } - if !info.Mode().IsRegular() { - return fmt.Errorf("go source/patch %#q is not a regular file", files[0]) - } + raw = append(raw, value) } - return nil + if !found { + raw = append(raw, entry) + } + + return strings.Join(raw, "\n") + "\n", nil } diff --git a/internal/app/azldev/core/sources/govendor_existing_internal_test.go b/internal/app/azldev/core/sources/govendor_existing_internal_test.go new file mode 100644 index 000000000..b9d47d92b --- /dev/null +++ b/internal/app/azldev/core/sources/govendor_existing_internal_test.go @@ -0,0 +1,97 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package sources + +import ( + "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/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/utils/fileperms" + "github.com/microsoft/azure-linux-dev-tools/internal/utils/fileutils" + "github.com/samber/lo" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/mock/gomock" +) + +func TestPrepareExistingGoVendorReplacesPayload(t *testing.T) { + ctx := newMockProcessorTestCtx() + component := components_testutils.NewMockComponent(gomock.NewController(t)) + component.EXPECT().GetName().AnyTimes().Return("app") + component.EXPECT().GetConfig().AnyTimes().Return(&projectconfig.ComponentConfig{ + GoVendor: &projectconfig.GoVendorConfig{Enabled: lo.ToPtr(true)}, + }) + + input := strings.Join([]string{ + "Name: app", "Version: 1.2", "Release: 1", "License: MIT AND Apache-2.0", + "Source0: app.tar.gz", "Source1: app-%{version}-vendor.tar.bz2", "Source2: go-vendor-tools.toml", + "%description", "app", "%prep", "%goprep", "tar -xf %{S:1}", + "%build", "%global gomodulesmode GO111MODULE=on", "%gobuild -o app .", + "%install", "%go_vendor_license_install -c %{S:2}", + "%files -f %{go_vendor_license_filelist}", "/usr/bin/app", "", + }, "\n") + + const ( + archiveName = "app-1.2-vendor.tar.bz2" + upstreamConfig = "[licensing]\ndetector = 'askalono'\n" + ) + + oldEntry := fedorasource.FormatSourcesEntry(archiveName, fileutils.HashTypeSHA512, strings.Repeat("a", 128)) + for name, data := range map[string]string{ + "app.spec": input, "app.tar.gz": "upstream source", archiveName: "old vendor", + "go-vendor-tools.toml": upstreamConfig, "sources": oldEntry + "\n", ".gitignore": "/" + archiveName + "\n", + } { + require.NoError(t, fileutils.WriteFile(ctx.FS(), "/output/"+name, []byte(data), fileperms.PublicFile)) + } + + ctx.CmdFactory.RunAndGetOutputHandler = func(command *exec.Cmd) (string, error) { + assert.Contains(t, strings.Join(command.Args, " "), "--verify") + assert.Contains(t, strings.Join(command.Args, " "), "MIT AND Apache-2.0") + staging := goVendorTestStaging(t, ctx) + data, err := fileutils.ReadFile(ctx.FS(), filepath.Join(staging, govendor.ConfigFilename)) + require.NoError(t, err) + assert.Equal(t, upstreamConfig, string(data)) + + prep, err := fileutils.ReadFile(ctx.FS(), filepath.Join(filepath.Dir(staging), "sources", "app.spec")) + require.NoError(t, err) + assert.NotContains(t, string(prep), "Source1:") + assert.NotContains(t, string(prep), "tar -xf %{S:1}") + + for name, data := range map[string]string{ + "azldev-generated-vendor.tar.bz2": "new vendor", "archive-name": archiveName + "\n", + "license": "Apache-2.0 AND MIT\n", "sources-list": "Source0: app.tar.gz\nSource2: go-vendor-tools.toml\n", + } { + require.NoError(t, fileutils.WriteFile(ctx.FS(), filepath.Join(staging, name), []byte(data), fileperms.PublicFile)) + } + + return "", nil + } + preparer := &sourcePreparerImpl{fs: ctx.FS(), dryRunnable: ctx, goVendorRunner: mock.NewRunner(ctx, "/mock.cfg")} + require.NoError(t, preparer.prepareGoVendor(ctx, component, "/output")) + payload, err := fileutils.ReadFile(ctx.FS(), "/output/"+archiveName) + require.NoError(t, err) + assert.Equal(t, "new vendor", string(payload)) + + finalSpec, err := fileutils.ReadFile(ctx.FS(), "/output/app.spec") + require.NoError(t, err) + assert.Contains(t, string(finalSpec), "Source1: app-%{version}-vendor.tar.bz2") + assert.Contains(t, string(finalSpec), "License: MIT AND Apache-2.0") + assert.NotContains(t, string(finalSpec), "azldev-go-vendor.toml") + + sources, err := fileutils.ReadFile(ctx.FS(), "/output/sources") + require.NoError(t, err) + digest, err := fileutils.ComputeFileHash(ctx.FS(), fileutils.HashTypeSHA512, "/output/"+archiveName) + require.NoError(t, err) + assert.Equal(t, fedorasource.FormatSourcesEntry(archiveName, fileutils.HashTypeSHA512, digest)+"\n", string(sources)) + ignore, err := fileutils.ReadFile(ctx.FS(), "/output/.gitignore") + require.NoError(t, err) + assert.Equal(t, "/"+archiveName+"\n", string(ignore)) +} diff --git a/internal/app/azldev/core/sources/govendor_internal_test.go b/internal/app/azldev/core/sources/govendor_internal_test.go index d79bbf4a5..6509507b2 100644 --- a/internal/app/azldev/core/sources/govendor_internal_test.go +++ b/internal/app/azldev/core/sources/govendor_internal_test.go @@ -14,6 +14,7 @@ import ( "github.com/microsoft/azure-linux-dev-tools/internal/app/azldev/core/components/components_testutils" "github.com/microsoft/azure-linux-dev-tools/internal/global/testctx" + "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" "github.com/microsoft/azure-linux-dev-tools/internal/providers/sourceproviders/fedorasource" @@ -83,6 +84,7 @@ func TestPrepareSourcesGoVendor(t *testing.T) { for name, content := range map[string]string{ "app-vendor.tar.bz2": "generated archive", + "archive-name": "app-vendor.tar.bz2\n", "license": "Apache-2.0 AND MIT\n", "sources-list": "Source0: app.tar.gz\nPatch0: fix.patch\n", } { @@ -144,7 +146,7 @@ func TestGoVendorFailuresDoNotPublishSpec(t *testing.T) { for _, stage := range []string{ "init", "install", "generate", "missing-archive", "empty-archive", - "license", "missing-source", "source-list", "scrub", + "license", "missing-source", "source-list", "scrub", "archive-name", "unexpected-name", } { t.Run(stage, func(t *testing.T) { ctx := newMockProcessorTestCtx() @@ -172,6 +174,7 @@ func TestGoVendorFailuresDoNotPublishSpec(t *testing.T) { staging := goVendorTestStaging(t, ctx) files := map[string]string{ "app-vendor.tar.bz2": "archive", "license": "MIT\n", "sources-list": "Source0: app.tar.gz\n", + "archive-name": "app-vendor.tar.bz2\n", } switch stage { @@ -185,6 +188,10 @@ func TestGoVendorFailuresDoNotPublishSpec(t *testing.T) { files["sources-list"] += "Patch0: absent.patch\n" case "source-list": files["sources-list"] = "Source0: /etc/passwd\n" + case "archive-name": + files["archive-name"] = "../outside.tar.bz2\n" + case "unexpected-name": + files["archive-name"] = "other.tar.bz2\n" } for name, data := range files { @@ -208,20 +215,8 @@ func TestGoVendorFailuresDoNotPublishSpec(t *testing.T) { } } -func TestGoVendorScriptOrdering(t *testing.T) { - script := goVendorScript("app-vendor.tar.bz2", "cmd/app", "aarch64", "app.spec") - assert.Less(t, strings.Index(script, "rpmautospec"), strings.Index(script, "rpmbuild")) - assert.Less(t, strings.Index(script, "rpmbuild"), strings.Index(script, "go_vendor_archive")) - assert.Less(t, strings.Index(script, "go_vendor_archive"), strings.Index(script, "go_vendor_license")) - assert.Contains(t, script, "cd cmd/app") - assert.Contains(t, script, "--target aarch64") - assert.Contains(t, script, "--no-prompt") - assert.Contains(t, script, "--autofill off") - assert.NotContains(t, script, "--idempotent") -} - func TestGoVendorSourceCollisions(t *testing.T) { - for _, name := range []string{"app-vendor.tar.bz2", goVendorConfig, "sources", "invalid-sources"} { + for _, name := range []string{"app-vendor.tar.bz2", govendor.ConfigFilename, "sources", "invalid-sources"} { t.Run(name, func(t *testing.T) { ctx := testctx.NewCtx() preparer := &sourcePreparerImpl{fs: ctx.FS()} @@ -238,7 +233,7 @@ func TestGoVendorSourceCollisions(t *testing.T) { } require.NoError(t, fileutils.WriteFile(ctx.FS(), "/output/"+filename, []byte(content), fileperms.PublicFile)) - require.Error(t, preparer.checkGoVendorSourceCollision("/output", "app-vendor.tar.bz2")) + require.Error(t, preparer.checkGoVendorSourceCollision("/output", "app-vendor.tar.bz2", govendor.ConfigFilename)) }) } } diff --git a/internal/govendor/generate.go b/internal/govendor/generate.go new file mode 100644 index 000000000..0f888ddfe --- /dev/null +++ b/internal/govendor/generate.go @@ -0,0 +1,253 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +// Package govendor generates vendor artifacts without resolving components or editing specs. +package govendor + +import ( + "cmp" + "context" + "errors" + "fmt" + "log/slog" + "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/rpm/spectool" + "github.com/microsoft/azure-linux-dev-tools/internal/utils/fileperms" + "github.com/microsoft/azure-linux-dev-tools/internal/utils/fileutils" +) + +const ( + // ConfigFilename is the tool configuration filename inside generation staging. + ConfigFilename = "azldev-go-vendor.toml" + sourceMount = "/azldev-go-vendor" + outputMount = "/azldev-go-scratch" + topDir = "/tmp/azldev-go-rpm" + cleanupTimeout = 5 * time.Minute +) + +// Request supplies prepared spec bytes and input files. WorkDir must be a private +// scratch directory outside SourceDir; the caller owns its cleanup and dry-run policy. +// PrepSpec must record 'azldev-go-module-root' and 'azldev-go-archive-name' in RPM's topdir. +type Request struct { + SourceDir, WorkDir, SpecName string + ArchiveFile, ArchiveSuffix string + ModuleDir, ToolConfig string + ExpectedLicense string + PrepSpec []byte + Packages []string +} + +// Artifact is validated generation output, ready for publication by the caller. +type Artifact struct { + Path, Name, License, Digest string +} + +// Generate prepares inputs and generates an archive in one isolated mock root. +// It never changes SourceDir or publishes a spec or source manifest. +func Generate(ctx context.Context, fs opctx.FS, base *mock.Runner, request Request) (Artifact, error) { + staging := filepath.Join(request.WorkDir, "work") + + sourceCopy := filepath.Join(request.WorkDir, "sources") + if err := stage(fs, request, sourceCopy, staging); err != nil { + return Artifact{}, err + } + + runner := base.Clone().WithBaseDir(filepath.Join(request.WorkDir, "mock")).EnableNetwork().WithUnprivileged() + runner.AddBindMount(sourceCopy, sourceMount).AddBindMount(staging, outputMount) + + if err := execute(ctx, runner, request); err != nil { + return Artifact{}, err + } + + if err := validateInputs(fs, staging, request.SourceDir); err != nil { + return Artifact{}, err + } + + return readArtifact(fs, staging, request) +} + +func stage(fs opctx.FS, request Request, sourceCopy, staging string) error { + for _, name := range []string{request.SpecName, request.ArchiveFile} { + if err := fileutils.ValidateFilename(name); err != nil { + return fmt.Errorf("invalid Go vendor staging filename:\n%w", err) + } + } + + if err := fileutils.MkdirAll(fs, staging); err != nil { + return fmt.Errorf("creating Go vendor staging directory:\n%w", err) + } + + if err := fileutils.CopyDirRecursiveCrossFS(fs, request.SourceDir, fs, sourceCopy, + fileutils.CopyDirOptions{CopyFileOptions: fileutils.CopyFileOptions{PreserveFileMode: true}}); err != nil { + return fmt.Errorf("copying Go sources for isolated prep:\n%w", err) + } + + for path, data := range map[string][]byte{ + filepath.Join(sourceCopy, request.SpecName): request.PrepSpec, + filepath.Join(staging, ConfigFilename): []byte(request.ToolConfig), + } { + if err := fileutils.WriteFile(fs, path, data, fileperms.PublicFile); err != nil { + return fmt.Errorf("staging Go vendor input %#q:\n%w", path, err) + } + } + + return nil +} + +func execute(ctx context.Context, runner *mock.Runner, request Request) (err error) { + defer func() { + cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), cleanupTimeout) + defer cancel() + + if cleanupErr := runner.ScrubRoot(cleanupCtx); cleanupErr != nil { + slog.Error("Failed to clean Go vendor mock root", "error", cleanupErr) + + if err == nil { + err = cleanupErr + } + } + }() + + if err := runner.InitRoot(ctx); err != nil { + return fmt.Errorf("initializing Go vendor mock root:\n%w", err) + } + + packages := append([]string{ + "go-vendor-tools", "askalono-cli", "golang", "go-rpm-macros", "rpm-build", "rpmdevtools", + "rpmautospec", "git", "python3-click", + }, request.Packages...) + if err := runner.InstallPackages(ctx, packages); err != nil { + return fmt.Errorf("installing Go vendor prerequisites:\n%w", err) + } + + cmd, err := runner.CmdInChroot(ctx, generationCommand(request, runner.ConfigOpts()["target_arch"]), false) + if err != nil { + return fmt.Errorf("constructing Go vendor command:\n%w", err) + } + + output, err := cmd.RunAndGetOutput(ctx) + if err != nil { + return fmt.Errorf("go vendor generation or license detection failed; use 'prep-packages' for missing prep tools "+ + "and 'tool-config' for reviewed license exceptions:\n%s\n%w", output, err) + } + + return nil +} + +func generationCommand(request Request, targetArch string) []string { + quote := shellquote.Join + + prepArgs := []string{ + "rpmbuild", "-bp", "--nodeps", "--define", "_topdir " + topDir, + "--define", "_builddir " + topDir + "/BUILD", "--define", "_sourcedir " + sourceMount, + } + if targetArch != "" { + prepArgs = append(prepArgs, "--target", targetArch) + } + + licenseArgs := []string{ + "go_vendor_license", "--config", outputMount + "/" + ConfigFilename, "--path", ".", + "report", "--no-prompt", "--autofill", "off", "expression", + } + if request.ExpectedLicense != "" { + licenseArgs = append(licenseArgs, "--verify", request.ExpectedLicense) + } + + commands := []string{ + "cd " + sourceMount, + "mkdir -p " + topDir + "/BUILD", + quote("git", "config", "--global", "--add", "safe.directory", sourceMount), + quote("rpmautospec", "process-distgit", request.SpecName, request.SpecName), + quote(append(prepArgs, sourceMount+"/"+request.SpecName)...), + quote("cp", topDir+"/azldev-go-archive-name", outputMount+"/archive-name"), + `IFS= read -r module_root < ` + topDir + "/azldev-go-module-root", + `cd "$module_root"`, + "cd " + quote(cmp.Or(request.ModuleDir, ".")), + "test -f go.mod", + "export GOTOOLCHAIN=local", + quote("go_vendor_archive", "create", "--config", outputMount+"/"+ConfigFilename, + "--output", outputMount+"/"+request.ArchiveFile, "."), + quote("tar", "-xf", outputMount+"/"+request.ArchiveFile), + quote(licenseArgs...) + " > " + outputMount + "/license", + "cd " + sourceMount, + quote("spectool", "--define", "_sourcedir "+sourceMount, "-l", "-a", request.SpecName) + + " > " + outputMount + "/sources-list", + } + + return []string{"bash", "-euo", "pipefail", "-c", strings.Join(commands, "\n")} +} + +func readArtifact(fs opctx.FS, staging string, request Request) (Artifact, error) { + result := Artifact{Path: filepath.Join(staging, request.ArchiveFile)} + + info, err := fs.Stat(result.Path) + if err != nil { + return result, fmt.Errorf("missing generated Go vendor archive:\n%w", err) + } + + if !info.Mode().IsRegular() || info.Size() == 0 { + return result, errors.New("generated Go vendor archive must be a nonempty regular file") + } + + for name, destination := range map[string]*string{"archive-name": &result.Name, "license": &result.License} { + data, err := fileutils.ReadFile(fs, filepath.Join(staging, name)) + if err != nil { + return result, fmt.Errorf("reading Go vendor output %#q:\n%w", name, err) + } + + *destination = strings.TrimSpace(string(data)) + if *destination == "" || strings.ContainsAny(*destination, "%\r\n") { + return result, fmt.Errorf("invalid Go vendor output %#q: %#q", name, *destination) + } + } + + if err := fileutils.ValidateFilename(result.Name); err != nil { + return result, fmt.Errorf("invalid expanded Go vendor archive name:\n%w", err) + } + + if !strings.HasSuffix(result.Name, request.ArchiveSuffix) { + return result, fmt.Errorf("unexpected expanded Go vendor archive name %#q", result.Name) + } + + result.Digest, err = fileutils.ComputeFileHash(fs, fileutils.HashTypeSHA512, result.Path) + if err != nil { + return result, fmt.Errorf("hashing generated Go vendor archive:\n%w", err) + } + + return result, nil +} + +func validateInputs(fs opctx.FS, staging, sourceDir string) error { + data, err := fileutils.ReadFile(fs, filepath.Join(staging, "sources-list")) + if err != nil { + return fmt.Errorf("reading prepared Go source list:\n%w", err) + } + + for _, line := range strings.Split(strings.TrimSpace(string(data)), "\n") { + if line == "" { + continue + } + + files := spectool.ParseSpectoolOutput(line) + if len(files) != 1 || strings.Contains(files[0], "%") { + return fmt.Errorf("cannot resolve Go source/patch reference %#q", line) + } + + info, err := fs.Stat(filepath.Join(sourceDir, files[0])) + if err != nil { + return fmt.Errorf("missing prepared Go source/patch %#q:\n%w", files[0], err) + } + + if !info.Mode().IsRegular() { + return fmt.Errorf("go source/patch %#q is not a regular file", files[0]) + } + } + + return nil +} diff --git a/internal/govendor/generate_internal_test.go b/internal/govendor/generate_internal_test.go new file mode 100644 index 000000000..68df88413 --- /dev/null +++ b/internal/govendor/generate_internal_test.go @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package govendor + +import ( + "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/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestGenerateArtifact(t *testing.T) { + for _, invalid := range []string{"", "archive-name", "license", "sources-list"} { + t.Run("invalid-"+invalid, func(t *testing.T) { + ctx := testctx.NewCtx() + ctx.CmdFactory.RegisterCommandInSearchPath(mock.MockBinary) + require.NoError(t, fileutils.WriteFile(ctx.FS(), "/input/app.spec", []byte("original"), fileperms.PublicFile)) + request := Request{ + SourceDir: "/input", WorkDir: "/scratch", SpecName: "app.spec", + ArchiveFile: "vendor.tar.bz2", ArchiveSuffix: ".tar.bz2", PrepSpec: []byte("prepared"), + } + ctx.CmdFactory.RunAndGetOutputHandler = func(command *exec.Cmd) (string, error) { + assert.Contains(t, command.Args, "--unpriv") + assert.Contains(t, command.Args, "--enable-network") + + for name, content := range map[string]string{ + request.ArchiveFile: "archive", "archive-name": "app-vendor.tar.bz2\n", + "license": "MIT\n", "sources-list": "Source0: app.spec\n", + } { + if name == invalid { + content = "%{unexpanded}" + } + + require.NoError(t, fileutils.WriteFile(ctx.FS(), + filepath.Join("/scratch/work", name), []byte(content), fileperms.PublicFile)) + } + + return "", nil + } + + artifact, err := Generate(ctx, ctx.FS(), mock.NewRunner(ctx, "/mock.cfg"), request) + if invalid != "" { + require.Error(t, err) + + return + } + + require.NoError(t, err) + assert.Equal(t, "app-vendor.tar.bz2", artifact.Name) + assert.Equal(t, "MIT", artifact.License) + digest, err := fileutils.ComputeFileHash(ctx.FS(), fileutils.HashTypeSHA512, artifact.Path) + require.NoError(t, err) + assert.Equal(t, digest, artifact.Digest) + + original, err := fileutils.ReadFile(ctx.FS(), "/input/app.spec") + require.NoError(t, err) + assert.Equal(t, "original", string(original)) + }) + } +} + +func TestGenerationCommand(t *testing.T) { + for _, expected := range []string{"", "MIT AND Apache-2.0"} { + command := generationCommand(Request{ + ArchiveFile: "app-vendor.tar.bz2", ModuleDir: "cmd/app", SpecName: "app.spec", ExpectedLicense: expected, + }, "aarch64") + assert.Equal(t, []string{"bash", "-euo", "pipefail", "-c"}, command[:4]) + script := command[4] + assert.Less(t, strings.Index(script, "rpmautospec"), strings.Index(script, "rpmbuild")) + assert.Less(t, strings.Index(script, "rpmbuild"), strings.Index(script, "go_vendor_archive")) + assert.Less(t, strings.Index(script, "go_vendor_archive"), strings.Index(script, "go_vendor_license")) + assert.Contains(t, script, "cd cmd/app") + assert.Contains(t, script, "--target aarch64") + assert.Contains(t, script, "--no-prompt") + assert.Contains(t, script, "--autofill off") + assert.NotContains(t, script, "--idempotent") + assert.Contains(t, script, "cp "+topDir+"/azldev-go-archive-name "+outputMount+"/archive-name") + assert.Equal(t, expected != "", strings.Contains(script, "--verify")) + } +} diff --git a/internal/projectconfig/component.go b/internal/projectconfig/component.go index cf753e065..d3b2404aa 100644 --- a/internal/projectconfig/component.go +++ b/internal/projectconfig/component.go @@ -644,28 +644,12 @@ func ResolveComponentConfig( // Returns a copy of the component config with relative file paths converted to absolute // file paths (relative to referenceDir, not the current working directory). func (c *ComponentConfig) WithAbsolutePaths(referenceDir string) *ComponentConfig { - // Deep copy the input to avoid unexpected sharing. Make sure *not* to deep-copy - // the SourceConfigFile, as we *do* want to alias that pointer, sharing it across - // all configs that came from that source config file. - result := &ComponentConfig{ - Name: c.Name, - SourceConfigFile: c.SourceConfigFile, - upstreamCommitConfigFile: c.upstreamCommitConfigFile, - RenderedSpecDir: c.RenderedSpecDir, - Locked: deep.MustCopy(c.Locked), - Release: c.Release, - Spec: deep.MustCopy(c.Spec), - Build: deep.MustCopy(c.Build), - Render: c.Render, - SourceFiles: deep.MustCopy(c.SourceFiles), - Packages: deep.MustCopy(c.Packages), - Publish: deep.MustCopy(c.Publish), - // OverlayFiles is consumed after component config resolution; preserve it verbatim - // here so inherited patterns can be interpreted relative to the concrete component - // config file. - OverlayFiles: slices.Clone(c.OverlayFiles), - Tests: deep.MustCopy(c.Tests), - } + // Copy all configuration fields, excluding shared back-references which can + // point back into the component map and must retain their identity. + input := *c + input.SourceConfigFile, input.upstreamCommitConfigFile = nil, nil + result := deep.MustCopy(&input) + result.SourceConfigFile, result.upstreamCommitConfigFile = c.SourceConfigFile, c.upstreamCommitConfigFile // Fix up paths. result.Spec.Path = makeAbsolute(referenceDir, result.Spec.Path) @@ -677,13 +661,8 @@ func (c *ComponentConfig) WithAbsolutePaths(referenceDir string) *ComponentConfi } } - // Copy and fix up overlays. - if c.Overlays != nil { - result.Overlays = make([]ComponentOverlay, len(c.Overlays)) - - for i := range result.Overlays { - result.Overlays[i] = *c.Overlays[i].WithAbsolutePaths(referenceDir) - } + for i := range result.Overlays { + result.Overlays[i] = *result.Overlays[i].WithAbsolutePaths(referenceDir) } return result diff --git a/internal/projectconfig/component_clone_internal_test.go b/internal/projectconfig/component_clone_internal_test.go new file mode 100644 index 000000000..2f6e43388 --- /dev/null +++ b/internal/projectconfig/component_clone_internal_test.go @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package projectconfig + +import ( + "testing" + + "github.com/samber/lo" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestComponentClonePreservesBackReferences(t *testing.T) { + source, pinSource := &ConfigFile{}, &ConfigFile{} + config := ComponentConfig{ + SourceConfigFile: source, upstreamCommitConfigFile: pinSource, + GoVendor: &GoVendorConfig{Enabled: lo.ToPtr(true), PrepPackages: []string{"git"}}, + Build: ComponentBuildConfig{Defines: map[string]string{"feature": "1"}}, + } + source.Components = map[string]ComponentConfig{"app": config} + pinSource.Components = source.Components + + resolved := config.WithAbsolutePaths("/project") + require.Same(t, source, resolved.SourceConfigFile) + require.Same(t, pinSource, resolved.upstreamCommitConfigFile) + require.NotSame(t, config.GoVendor, resolved.GoVendor) + require.Equal(t, config.GoVendor, resolved.GoVendor) + resolved.Build.Defines["feature"] = "2" + *resolved.GoVendor.Enabled = false + resolved.GoVendor.PrepPackages[0] = "changed" + assert.True(t, config.GoVendor.IsEnabled()) + + assert.Equal(t, "1", config.Build.Defines["feature"]) + assert.Equal(t, []string{"git"}, config.GoVendor.PrepPackages) +} diff --git a/internal/projectconfig/govendor_test.go b/internal/projectconfig/govendor_test.go index 1c363001a..e94ead8c6 100644 --- a/internal/projectconfig/govendor_test.go +++ b/internal/projectconfig/govendor_test.go @@ -28,6 +28,7 @@ tool-config = ''' `), &config)) require.True(t, config.GoVendor.IsEnabled()) require.NoError(t, config.GoVendor.Validate()) + require.Equal(t, config.GoVendor, config.WithAbsolutePaths("/project").GoVendor) require.NoError(t, config.MergeUpdatesFrom(&projectconfig.ComponentConfig{ GoVendor: &projectconfig.GoVendorConfig{Enabled: lo.ToPtr(false)}, })) diff --git a/internal/rpm/spec/govendor.go b/internal/rpm/spec/govendor.go index 29791e3c1..492faec23 100644 --- a/internal/rpm/spec/govendor.go +++ b/internal/rpm/spec/govendor.go @@ -22,11 +22,15 @@ type GoVendorOptions struct { ModuleDir string } -// GoVendorSpec contains the converted spec and the otherwise identical prep-only -// spec used to obtain the patched module tree before a vendor archive exists. +// GoVendorSpec is the common plan for converting or refreshing Go vendoring. type GoVendorSpec struct { - Spec []byte - PrepSpec []byte + Spec []byte + PrepSpec []byte + ArchiveFile string // Filename used inside generation staging. + ArchiveSuffix string // Required suffix of the RPM-expanded destination name, if any. + ConfigName string + ExpectedLicense string // Empty: detect and update. Otherwise: verify and preserve. + AllowReplacement bool // Permit replacing the existing vendor payload and configuration. } const goVendorEnvironment = `export GO111MODULE=on GOPROXY=off GOSUMDB=off GOTOOLCHAIN=local @@ -55,6 +59,16 @@ func ConvertGoVendor(data []byte, options GoVendorOptions) (*GoVendorSpec, error } tree := &specTree{root: root} + + configSource, err := existingVendorConfigSource(tree) + if err != nil { + return nil, err + } + + if configSource != "" { + return prepareExistingGoVendor(tree, configSource) + } + if err := validateGoVendorTree(tree); err != nil { return nil, err } @@ -69,7 +83,7 @@ func ConvertGoVendor(data []byte, options GoVendorOptions) (*GoVendorSpec, error prep.PrependLines([]string{"export GOTOOLCHAIN=local"}) prep.AppendLines([]string{"", `pwd -P > "%{_topdir}/azldev-go-module-root"`}) - prepSpec := serializeGoVendorTree(tree) + prepSpec := goVendorPrepSpec(tree, options.ArchiveName) sourceNumber, err := freeGoVendorSources(tree, options) if err != nil { @@ -97,7 +111,10 @@ func ConvertGoVendor(data []byte, options GoVendorOptions) (*GoVendorSpec, error addGoVendorBuildSections(tree, options, configRef) - return &GoVendorSpec{Spec: serializeGoVendorTree(tree), PrepSpec: prepSpec}, nil + return &GoVendorSpec{ + Spec: serializeGoVendorTree(tree), PrepSpec: prepSpec, + ArchiveFile: options.ArchiveName, ConfigName: options.ConfigName, + }, nil } func addGoVendorBuildSections(tree *specTree, options GoVendorOptions, configRef string) { @@ -111,11 +128,7 @@ func addGoVendorBuildSections(tree *specTree, options GoVendorOptions, configRef requires.PrependLines([]string{"%go_vendor_license_buildrequires -c " + configRef}) - for _, name := range []string{"%build", "%install", "%check", "%generate_buildrequires"} { - if section := tree.Section(name, ""); section != nil { - section.PrependLines([]string{goVendorEnvironment}) - } - } + addGoVendorEnvironment(tree) tree.Section("%install", "").AppendLines([]string{ "", goVendorInModule(options.ModuleDir, "%go_vendor_license_install -c "+configRef), @@ -156,6 +169,45 @@ func serializeGoVendorTree(tree *specTree) []byte { return []byte(strings.Join(serializeTree(tree.root), "\n") + "\n") } +func addGoVendorEnvironment(tree *specTree) { + for _, name := range []string{"%build", "%install", "%check", "%generate_buildrequires"} { + if section := tree.Section(name, ""); section != nil { + section.PrependLines([]string{goVendorEnvironment}) + } + } +} + +func goVendorPrepSpec(tree *specTree, archiveValue string) []byte { + prep := tree.Section("%prep", "") + prep.AppendLines([]string{ + "printf '%%s\\n' %{shescape:" + archiveValue + `} > "%{_topdir}/azldev-go-archive-name"`, + }) + + result := serializeGoVendorTree(tree) + prep.block.Children = prep.block.Children[:len(prep.block.Children)-1] + + return result +} + +// FinalizeLicense preserves a verified upstream expression or writes the detected +// expression for a newly converted spec. It does not mutate the plan. +func (p *GoVendorSpec) FinalizeLicense(expression string) ([]byte, error) { + if p.ExpectedLicense != "" { + return p.Spec, nil + } + + editor, err := openStructuralSpec(strings.NewReader(string(p.Spec))) + if err != nil { + return nil, err + } + + if err := editor.UpdateExistingTag("", "License", expression); err != nil { + return nil, err + } + + return []byte(strings.Join(editor.rawLines, "\n") + "\n"), nil +} + func goVendorInModule(moduleDir, command string) string { lines := []string{`( cd "$(cat "%{_topdir}/azldev-go-module-root")"`} if moduleDir != "" { diff --git a/internal/rpm/spec/govendor_existing.go b/internal/rpm/spec/govendor_existing.go new file mode 100644 index 000000000..b7a237c0a --- /dev/null +++ b/internal/rpm/spec/govendor_existing.go @@ -0,0 +1,212 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package spec + +import ( + "errors" + "fmt" + "path/filepath" + "regexp" + "slices" + "strings" + + "github.com/microsoft/azure-linux-dev-tools/internal/utils/fileutils" +) + +var ( + existingVendorLicense = regexp.MustCompile( + `^%go_vendor_license_(?:buildrequires|install|check)\s+-c\s+%\{(?:S:|SOURCE)([0-9]+)\}\s*$`) + existingVendorExtract = regexp.MustCompile(`^tar\s+-xf\s+%\{(?:S:|SOURCE)([0-9]+)\}\s*$`) +) + +func prepareExistingGoVendor(tree *specTree, configSource string) (*GoVendorSpec, error) { + if err := validateGoVendorSection(tree, "%prep", true); err != nil { + return nil, err + } + + configName, err := existingVendorTagValue(tree, "Source"+configSource) + if err != nil { + return nil, err + } + + if err := fileutils.ValidateFilename(configName); err != nil || strings.Contains(configName, "%") { + return nil, fmt.Errorf("existing Go vendor config Source%s must name a plain file, got %#q", configSource, configName) + } + + extraction, sourceNumber, err := existingVendorExtraction(tree) + if err != nil { + return nil, err + } + + if sourceNumber == configSource { + return nil, errors.New("go vendor archive and tool configuration cannot use the same Source tag") + } + + archiveValue, err := existingVendorTagValue(tree, "Source"+sourceNumber) + if err != nil { + return nil, err + } + + suffix, err := existingVendorArchiveSuffix(archiveValue) + if err != nil { + return nil, err + } + + license, err := existingVendorLicenseExpression(tree) + if err != nil { + return nil, err + } + + // Keep upstream's Source numbers, macro settings, file lists, and custom commands. + for _, sectionName := range []string{"%build", "%install", "%check", "%generate_buildrequires"} { + if err := validateGoVendorSection(tree, sectionName, false); err != nil { + return nil, err + } + } + + addGoVendorEnvironment(tree) + finalSpec := serializeGoVendorTree(tree) + + if err := removeExistingVendorInput(tree, sourceNumber, extraction); err != nil { + return nil, err + } + + tree.Section("%prep", "").AppendLines([]string{ + `pwd -P > "%{_topdir}/azldev-go-module-root"`, + }) + + return &GoVendorSpec{ + Spec: finalSpec, PrepSpec: goVendorPrepSpec(tree, archiveValue), + ArchiveFile: "azldev-generated-vendor" + suffix, ArchiveSuffix: suffix, ConfigName: configName, + ExpectedLicense: license, AllowReplacement: true, + }, nil +} + +func existingVendorLicenseExpression(tree *specTree) (string, error) { + license, err := existingVendorTagValue(tree, "License") + if err != nil { + return "", err + } + + if strings.ContainsAny(license, "%\r\n") || license == "" { + return "", errors.New("regenerating an existing Go vendor archive requires an explicit main-package 'License' tag") + } + + return license, nil +} + +// An empty result means the spec has no existing vendor license commands. +func existingVendorConfigSource(tree *specTree) (string, error) { + source := "" + + err := tree.VisitAllLines(func(_, _ string, line *lineHandle) error { + text := strings.TrimSpace(line.Text) + if !strings.HasPrefix(text, "%go_vendor_license_") { + return nil + } + + matches := existingVendorLicense.FindStringSubmatch(text) + if len(matches) == 0 { + return fmt.Errorf("unsupported existing Go vendor license command %#q", text) + } + + if source != "" && source != matches[1] { + return errors.New("existing Go vendor license commands reference different configuration sources") + } + + source = matches[1] + + return nil + }) + if err != nil { + return "", err + } + + return source, nil +} + +func existingVendorExtraction(tree *specTree) (line, source string, err error) { + count := 0 + + err = tree.Section("%prep", "").VisitLines(func(candidate *lineHandle) error { + matches := existingVendorExtract.FindStringSubmatch(strings.TrimSpace(candidate.Text)) + if len(matches) != 0 { + if !slices.Contains(tree.Section("%prep", "").block.Children, candidate.block) { + return errors.New("conditional Go vendor extraction requires an explicit preparation strategy") + } + + count++ + line = strings.TrimSpace(candidate.Text) + source = matches[1] + } + + return nil + }) + if err != nil { + return "", "", err + } + + if count != 1 { + return "", "", errors.New("existing Go vendoring requires one unambiguous 'tar -xf %{S:N}' prep command") + } + + return line, source, nil +} + +func existingVendorTagValue(tree *specTree, name string) (string, error) { + var values []string + + err := tree.VisitAllLines(func(section, pkg string, line *lineHandle) error { + tag, value, ok := parseTagLine(line.Text) + if ok && section == "" && pkg == "" && strings.EqualFold(tag, name) { + if !slices.Contains(tree.Section("", "").block.Children, line.block) { + return fmt.Errorf("existing Go vendoring requires an unconditional %#q tag", name) + } + + values = append(values, value) + } + + return nil + }) + if err != nil { + return "", err + } + + if len(values) != 1 { + return "", fmt.Errorf("expected exactly one %#q declaration for existing Go vendoring", name) + } + + return values[0], nil +} + +func existingVendorArchiveSuffix(value string) (string, error) { + if strings.Contains(value, "://") { + return "", errors.New("existing Go vendor archive must use a local source filename") + } + + extension := filepath.Ext(value) + switch extension { + case ".bz2", ".gz", ".xz", ".zst", ".zstd": + return ".tar" + extension, nil + case ".tar": + return ".tar", nil + default: + return "", fmt.Errorf("unsupported existing Go vendor archive format %#q", value) + } +} + +func removeExistingVendorInput(tree *specTree, sourceNumber, extraction string) error { + return tree.VisitAllLines(func(section, pkg string, line *lineHandle) error { + tag, _, ok := parseTagLine(line.Text) + if ok && section == "" && pkg == "" && strings.EqualFold(tag, "Source"+sourceNumber) { + line.Remove() + } + + if section == "%prep" && strings.TrimSpace(line.Text) == extraction { + line.Remove() + } + + return nil + }) +} diff --git a/internal/rpm/spec/govendor_existing_test.go b/internal/rpm/spec/govendor_existing_test.go new file mode 100644 index 000000000..3b1927f95 --- /dev/null +++ b/internal/rpm/spec/govendor_existing_test.go @@ -0,0 +1,87 @@ +// 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 existingVendorSpec() string { + return strings.Join([]string{ + "Name: app", "Version: 1.2", "Release: %autorelease", "Summary: Application", + "License: MIT AND Apache-2.0", + "Source0: app-%{version}.tar.gz", + "Source5: app-%{version}-vendor.tar.bz2", + "Source8: go-vendor-tools.toml", + "Source9: app.conf", + "BuildRequires: go-vendor-tools", "Requires: runtime-helper", + "%description", "Application", "%prep", "%goprep -p1", + "tar -xf %{S:5}", "sed -i 's/old/new/' go.mod", "cp %{S:9} .", + "%generate_buildrequires", "%go_vendor_license_buildrequires -c %{S:8}", + "%build", "%global gomodulesmode GO111MODULE=on", "%gobuild -o app .", + "%install", "%go_vendor_license_install -c %{S:8}", + "install -D app %{buildroot}%{_bindir}/app", + "%check", "%go_vendor_license_check -c %{S:8}", "%gocheck2 -t integration", + "%files -f %{go_vendor_license_filelist}", "%{_bindir}/app", "%changelog", "%autochangelog", "", + }, "\n") +} + +func TestExistingGoVendoringPreservesPackaging(t *testing.T) { + for _, version := range []string{"1.2", "2.4"} { + input := strings.ReplaceAll(existingVendorSpec(), "Version: 1.2", "Version: "+version) + result, err := spec.ConvertGoVendor([]byte(input), spec.GoVendorOptions{ + ArchiveName: "app-vendor.tar.bz2", ConfigName: "azldev-go-vendor.toml", + }) + require.NoError(t, err) + assert.True(t, result.AllowReplacement) + assert.Equal(t, "go-vendor-tools.toml", result.ConfigName) + assert.Equal(t, ".tar.bz2", result.ArchiveSuffix) + assert.Equal(t, "MIT AND Apache-2.0", result.ExpectedLicense) + + for _, line := range strings.Split(input, "\n") { + assert.Contains(t, string(result.Spec), line) + } + + assert.NotContains(t, string(result.Spec), "azldev-go-vendor.toml") + assert.NotContains(t, string(result.Spec), "azldev-go-module-root") + assert.Contains(t, string(result.Spec), "GOPROXY=off") + assert.NotContains(t, string(result.PrepSpec), "Source5:") + assert.NotContains(t, string(result.PrepSpec), "tar -xf %{S:5}") + assert.Contains(t, string(result.PrepSpec), "sed -i 's/old/new/' go.mod") + assert.Contains(t, string(result.PrepSpec), "%{shescape:app-%{version}-vendor.tar.bz2}") + assert.Contains(t, string(result.PrepSpec), `pwd -P > "%{_topdir}/azldev-go-module-root"`) + } +} + +func TestExistingGoVendoringRejectsAmbiguousInputs(t *testing.T) { + for name, input := range map[string]string{ + "multiple extractions": strings.ReplaceAll(existingVendorSpec(), "%goprep -p1", "%goprep -p1\ntar -xf %{S:9}"), + "no extraction": strings.ReplaceAll(existingVendorSpec(), "tar -xf %{S:5}", ""), + "mismatched config": strings.ReplaceAll(existingVendorSpec(), + "%go_vendor_license_check -c %{S:8}", "%go_vendor_license_check -c %{S:9}"), + "dynamic config": strings.ReplaceAll(existingVendorSpec(), "go-vendor-tools.toml", "%{name}.toml"), + "unknown compression": strings.ReplaceAll(existingVendorSpec(), "-vendor.tar.bz2", "-vendor.zip"), + "macro license": strings.ReplaceAll(existingVendorSpec(), "License: MIT AND Apache-2.0", "License: %{license}"), + "missing source": strings.ReplaceAll(existingVendorSpec(), "Source5:", "Source6:"), + "conditional extraction": strings.ReplaceAll(existingVendorSpec(), + "tar -xf %{S:5}", "%if 1\ntar -xf %{S:5}\n%endif"), + "conditional source": strings.ReplaceAll(existingVendorSpec(), + "Source5: app-%{version}-vendor.tar.bz2", "%if 1\nSource5: app-%{version}-vendor.tar.bz2\n%endif"), + "conditional license": strings.ReplaceAll(existingVendorSpec(), + "License: MIT AND Apache-2.0", "%if 1\nLicense: MIT AND Apache-2.0\n%endif"), + } { + t.Run(name, func(t *testing.T) { + result, err := spec.ConvertGoVendor([]byte(input), spec.GoVendorOptions{ + ArchiveName: "app-vendor.tar.bz2", ConfigName: "azldev-go-vendor.toml", + }) + require.Error(t, err) + assert.Nil(t, result) + }) + } +} diff --git a/internal/rpm/spec/govendor_test.go b/internal/rpm/spec/govendor_test.go index cfed507aa..c366de034 100644 --- a/internal/rpm/spec/govendor_test.go +++ b/internal/rpm/spec/govendor_test.go @@ -97,7 +97,10 @@ func TestConvertGoVendorPreservesUpstream(t *testing.T) { assert.Contains(t, string(result.PrepSpec), "Release: %autorelease") assert.Contains(t, string(result.PrepSpec), `pwd -P > "%{_topdir}/azldev-go-module-root"`) assert.Contains(t, string(result.PrepSpec), "sed -i 's/old/new/' go.mod") - assert.NotContains(t, string(result.PrepSpec), "app-vendor.tar.bz2") + assert.NotContains(t, string(result.PrepSpec), "Source2: app-vendor.tar.bz2") + assert.Contains(t, string(result.PrepSpec), "%{shescape:app-vendor.tar.bz2}") + assert.False(t, result.AllowReplacement) + assert.Empty(t, result.ExpectedLicense) assert.Contains(t, string(result.PrepSpec), "%autochangelog") _, err = spec.OpenSpec(strings.NewReader(output), spec.WithEditor(spec.EditorStructural)) From b9cb5a6bcc7f6d40bf88a92d9122034f00a91100 Mon Sep 17 00:00:00 2001 From: Antonio Salinas <173939267+Tonisal-byte@users.noreply.github.com> Date: Mon, 2 Nov 2026 11:20:22 -0800 Subject: [PATCH 03/16] feat: load Go vendor settings from config files Replace the inline tool-config option with config-file, resolved relative to its declaring component configuration. Explicit files replace upstream settings, including empty files, and missing or invalid files fail without fallback. Hash file contents rather than checkout paths for lock fingerprints and lock-free change detection. Preserve upstream settings when no file is selected, and update the schema, documentation, emitted guidance, and regression coverage. Validation: unit tests and all quality checks passed. The changed-code mutation audit killed all 16 mutations. Containerd source generation with a separate vendor config reproduced the prior outputs, and a file-only edit invalidated its isolated lock fingerprint. Docker scenario initialization remains unavailable in this environment. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/user/how-to/vendor-go-application.md | 34 ++++++++-- docs/user/reference/config/components.md | 27 ++++++-- .../app/azldev/agentskill/agentskill_test.go | 2 + .../agentskill/content/comp-toml.md.tmpl | 8 ++- .../content/withoutlockfile/comp-toml.md.tmpl | 8 ++- .../cmds/component/changed_upstreamcommit.go | 14 ++++ .../changed_upstreamcommit_internal_test.go | 22 +++++++ .../cmds/component/history_customizations.go | 4 +- .../cmds/component/history_internal_test.go | 1 - .../component/preparerctx_internal_test.go | 4 +- internal/app/azldev/core/sources/govendor.go | 20 ++++-- .../sources/govendor_config_internal_test.go | 41 ++++++++++++ .../core/sources/govendor_internal_test.go | 16 ++++- internal/fingerprint/doc.go | 2 +- internal/fingerprint/fingerprint.go | 16 ++++- internal/fingerprint/govendor_test.go | 62 ++++++++++++++++++ internal/govendor/generate.go | 6 +- internal/projectconfig/component.go | 3 + internal/projectconfig/fingerprint_test.go | 3 + internal/projectconfig/govendor.go | 60 +++++++++++++---- .../govendor_loader_internal_test.go | 56 ++++++++++++++++ internal/projectconfig/govendor_test.go | 64 ++++++++++++++++--- ...shots_config_generate-schema_stdout_1.snap | 9 ++- schemas/azldev.schema.json | 9 ++- 24 files changed, 433 insertions(+), 58 deletions(-) create mode 100644 internal/app/azldev/core/sources/govendor_config_internal_test.go create mode 100644 internal/fingerprint/govendor_test.go create mode 100644 internal/projectconfig/govendor_loader_internal_test.go diff --git a/docs/user/how-to/vendor-go-application.md b/docs/user/how-to/vendor-go-application.md index 068673213..3892e8426 100644 --- a/docs/user/how-to/vendor-go-application.md +++ b/docs/user/how-to/vendor-go-application.md @@ -15,6 +15,31 @@ Add this to the component definition: enabled = true ``` +For custom vendor settings, use a separate file beside the component definition: + +```toml +# example.comp.toml +[components.example.go-vendor] +enabled = true +config-file = "go-vendor-tools.toml" +``` + +```toml +# go-vendor-tools.toml +[archive] +use_module_proxy = true + +[licensing] +detector = "askalono" +``` + +This file replaces, rather than merges with, upstream settings. Carry forward +any required upstream license exceptions. Omit `config-file` to reuse those +settings unchanged. Paths are relative to the declaring component configuration, +including when inherited from defaults; no adjacent file is loaded implicitly. +File-only edits affect the component fingerprint. Inline `tool-config` values +are no longer accepted. + Then prepare the complete build inputs: ```sh @@ -35,7 +60,7 @@ This retains upstream patches and edits to module files. It then calls `go_vendor_archive create` on the prepared module tree, extracts the result for license detection, and runs `go_vendor_license` without interactive prompts. Unrecognized licenses fail preparation; add reviewed, hash-qualified exceptions -to `tool-config` rather than suppressing detection. +to the file selected by `config-file` rather than suppressing detection. The output includes the converted spec, all its original sources and patches, `-vendor.tar.bz2`, and `azldev-go-vendor.toml`. The archive is recorded @@ -84,9 +109,10 @@ the replacement does not consume the old vendor payload. RPM expands the upstream archive filename; the regenerated archive replaces that file and its `sources` checksum rather than adding a second vendor archive. -When `tool-config` is omitted, the upstream go-vendor-tools configuration is used, -including its reviewed license exceptions. An explicit `tool-config` replaces -that configuration. The detected licenses are verified against the existing +When `config-file` is omitted, the upstream go-vendor-tools configuration is used, +including its reviewed license exceptions. An explicit file replaces that configuration +even when empty; missing files or invalid TOML fail without falling back. +The detected licenses are verified against the existing main-package `License:` expression; mismatches fail instead of rewriting it. The source-fetch phase currently still downloads the upstream vendor archive alongside the other upstream sources, before regenerating its contents. diff --git a/docs/user/reference/config/components.md b/docs/user/reference/config/components.md index d16fffc7b..530b9cea3 100644 --- a/docs/user/reference/config/components.md +++ b/docs/user/reference/config/components.md @@ -182,22 +182,33 @@ enabled = true | `enabled` | boolean | `false` | Enable conversion and vendor archive generation. An explicit `false` overrides inherited enablement. | | `module-dir` | string | `""` | Relative directory containing `go.mod`, resolved from the working directory at the end of the upstream `%prep` section. Empty uses that directory itself. No absolute paths, traversal, or RPM macros. | | `prep-packages` | array of string | `[]` | Additional RPM packages needed by upstream `%prep` commands or the selected license detector. Installed only in the isolated generation chroot. | -| `tool-config` | string | `""` | Inline [go-vendor-tools TOML](https://fedora.gitlab.io/sigs/go/go-vendor-tools/config/), for dependency overrides, archive options, and reviewed license exceptions. When omitted for an already-vendored spec, reuse its upstream tool configuration. An explicit value replaces it. Use `module-dir`, not `general.go_mod_dir`. | +| `config-file` | string | `""` | Path to a separate [go-vendor-tools TOML file](https://fedora.gitlab.io/sigs/go/go-vendor-tools/config/), relative to the configuration file that declares it. Its contents replace upstream tool settings; they are not merged. When no file is configured, reuse an already-vendored spec's upstream settings or use tool defaults for a new conversion. | -The tool configuration is inline so its contents participate in component -fingerprinting without checkout-dependent paths. Configured command hooks execute -in the generation chroot; treat this configuration as trusted build code. +Custom vendor settings must live in a separate file, typically +`go-vendor-tools.toml` beside the component definition. Its contents participate +in the component fingerprint; absolute checkout paths do not. Inherited paths +retain their original declaration directory. Editing only this file makes the +lock fingerprint stale and requires the normal update/render workflow. ```toml +# example.comp.toml [components.example.go-vendor] enabled = true -prep-packages = ["git"] -tool-config = ''' +config-file = "go-vendor-tools.toml" +``` + +```toml +# go-vendor-tools.toml [archive.dependency_overrides] "example.com/dependency" = "v1.2.3" -''' ``` +The configured file must exist and contain valid TOML. An explicitly selected +empty file is an empty replacement, not a request to fall back to upstream. +Use `module-dir`, not `general.go_mod_dir`, for the module location. +Configured command hooks execute in the generation chroot; treat this file as +trusted build code. The old inline `tool-config` string/table is no longer supported. + For previously unbundled specs, preparation emits `-vendor.tar.bz2` and `azldev-go-vendor.toml`, allocating unused `Source` numbers automatically. These names are reserved for generated output; do not also declare them in `source-files` or supply them through @@ -209,6 +220,8 @@ For supported specs already using go-vendor-tools, preparation instead regenerat the existing vendor source, retaining its Source number, RPM-expanded filename, and configuration sidecar. It updates that archive's `sources` entry in place and verifies the existing `License:` expression without rewriting it. +When `config-file` is set, its contents are staged under the configuration filename +referenced by the prepared spec, retaining the existing Source number. All archive/spec/loose-file overlays run before conversion. Source preparation, builds, rendering (including `--check-only`), and source diffs use the same diff --git a/internal/app/azldev/agentskill/agentskill_test.go b/internal/app/azldev/agentskill/agentskill_test.go index 7ebe18bdf..0836c6751 100644 --- a/internal/app/azldev/agentskill/agentskill_test.go +++ b/internal/app/azldev/agentskill/agentskill_test.go @@ -168,6 +168,8 @@ func TestComponentTomlSkillDocumentsGoVendoring(t *testing.T) { assert.Contains(t, doc, "does\nnot run `go2rpm`") assert.Contains(t, doc, "Rendering and source diffs also generate") assert.Contains(t, doc, "reviewed license exceptions") + assert.Contains(t, doc, `config-file = "go-vendor-tools.toml"`) + assert.Contains(t, doc, "Inline `tool-config` is not supported.") } } diff --git a/internal/app/azldev/agentskill/content/comp-toml.md.tmpl b/internal/app/azldev/agentskill/content/comp-toml.md.tmpl index a6dbf477e..b724ea0ef 100644 --- a/internal/app/azldev/agentskill/content/comp-toml.md.tmpl +++ b/internal/app/azldev/agentskill/content/comp-toml.md.tmpl @@ -43,8 +43,12 @@ not run `go2rpm`. Rendering and source diffs also generate the vendor archive an require downloads. Review the generated cumulative `License:` expression. Use `module-dir` for a module below the final prep working directory, -`prep-packages` for additional chroot tools, and inline `tool-config` for -go-vendor-tools dependency overrides or reviewed license exceptions. +`prep-packages` for additional chroot tools, and `config-file = "go-vendor-tools.toml"` +for custom settings in a separate native TOML file beside the component definition. +Keep reviewed license exceptions in that file. +The path is relative to the declaring config, and file contents are fingerprinted. +It replaces upstream settings without merging; an explicit empty file is still a +replacement, and a missing file is an error. Inline `tool-config` is not supported. Generated `-vendor.tar.bz2` and `azldev-go-vendor.toml` must not also be declared as `source-files`. For supported already-vendored specs, regenerate the existing vendor Source instead, reuse upstream tool configuration unless overridden, 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 96690b936..cd0ec3e48 100644 --- a/internal/app/azldev/agentskill/content/withoutlockfile/comp-toml.md.tmpl +++ b/internal/app/azldev/agentskill/content/withoutlockfile/comp-toml.md.tmpl @@ -43,8 +43,12 @@ not run `go2rpm`. Rendering and source diffs also generate the vendor archive an require downloads. Review the generated cumulative `License:` expression. Use `module-dir` for a module below the final prep working directory, -`prep-packages` for additional chroot tools, and inline `tool-config` for -go-vendor-tools dependency overrides or reviewed license exceptions. +`prep-packages` for additional chroot tools, and `config-file = "go-vendor-tools.toml"` +for custom settings in a separate native TOML file beside the component definition. +Keep reviewed license exceptions in that file. +The path is relative to the declaring config, and file contents are fingerprinted. +It replaces upstream settings without merging; an explicit empty file is still a +replacement, and a missing file is an error. Inline `tool-config` is not supported. Generated `-vendor.tar.bz2` and `azldev-go-vendor.toml` must not also be declared as `source-files`. For supported already-vendored specs, regenerate the existing vendor Source instead, reuse upstream tool configuration unless overridden, diff --git a/internal/app/azldev/cmds/component/changed_upstreamcommit.go b/internal/app/azldev/cmds/component/changed_upstreamcommit.go index ce8e19ebc..ce18e0d5e 100644 --- a/internal/app/azldev/cmds/component/changed_upstreamcommit.go +++ b/internal/app/azldev/cmds/component/changed_upstreamcommit.go @@ -118,6 +118,7 @@ type componentComparisonInputs struct { Config projectconfig.ComponentConfig `json:"config"` SourceIdentity string `json:"sourceIdentity,omitempty"` OverlaySourceHashes map[string]string `json:"overlaySourceHashes,omitempty"` + GoVendorConfigHash string `json:"goVendorConfigHash,omitempty"` ReleaseVer string `json:"releaseVer,omitempty"` } @@ -252,6 +253,13 @@ func buildComponentComparisonInputs( SourceIdentity: component.EffectiveUpstreamCommit(), } + var err error + + inputs.GoVendorConfigHash, err = component.GoVendor.SourceContentIdentity(fs) + if err != nil { + return inputs, fmt.Errorf("hashing Go vendor configuration:\n%w", err) + } + if component.Spec.SourceType == projectconfig.SpecSourceTypeLocal { identity, err := sourceproviders.ResolveLocalSourceIdentity( fs, filepath.Dir(component.Spec.Path), @@ -314,7 +322,13 @@ func normalizeComponentForComparison(component projectconfig.ComponentConfig) pr normalized.Build.Hints = projectconfig.ComponentBuildHints{} normalized.OverlayFiles = nil normalized.Publish = projectconfig.ComponentPublishConfig{} + normalized.Tests = nil + if component.GoVendor != nil { + vendor := *component.GoVendor + vendor.ConfigFile = "" + normalized.GoVendor = &vendor + } normalized.Overlays = slices.Clone(component.Overlays) for idx := range normalized.Overlays { diff --git a/internal/app/azldev/cmds/component/changed_upstreamcommit_internal_test.go b/internal/app/azldev/cmds/component/changed_upstreamcommit_internal_test.go index 357f3321b..1680f2088 100644 --- a/internal/app/azldev/cmds/component/changed_upstreamcommit_internal_test.go +++ b/internal/app/azldev/cmds/component/changed_upstreamcommit_internal_test.go @@ -209,6 +209,28 @@ func TestBuildComponentComparisonInputs_ContentIdentities(t *testing.T) { assert.NotEqual(t, second.OverlaySourceHashes, third.OverlaySourceHashes) } +func TestBuildComponentComparisonInputs_GoVendorFile(t *testing.T) { + env := testutils.NewTestEnvWithoutLockfile(t) + enabled := true + component := projectconfig.ComponentConfig{GoVendor: &projectconfig.GoVendorConfig{ + Enabled: &enabled, ConfigFile: "/project/vendor.toml", + }} + require.NoError(t, fileutils.WriteFile(env.FS(), component.GoVendor.ConfigFile, + []byte("[archive]\ntidy = false\n"), fileperms.PublicFile)) + first, err := buildComponentComparisonInputs(env.FS(), env.Env, &component) + require.NoError(t, err) + assert.Empty(t, first.Config.GoVendor.ConfigFile) + assert.Equal(t, "/project/vendor.toml", component.GoVendor.ConfigFile) + require.NotEmpty(t, first.GoVendorConfigHash) + + require.NoError(t, fileutils.WriteFile(env.FS(), component.GoVendor.ConfigFile, + []byte("[archive]\ntidy = true\n"), fileperms.PublicFile)) + second, err := buildComponentComparisonInputs(env.FS(), env.Env, &component) + require.NoError(t, err) + assert.NotEqual(t, first.GoVendorConfigHash, second.GoVendorConfigHash) + assert.Equal(t, first.Config, second.Config) +} + func TestLoadHistoricalProject_UsesNormalIncludesAndMerging(t *testing.T) { rootConfig := []byte(`includes = [ "config/components.toml", diff --git a/internal/app/azldev/cmds/component/history_customizations.go b/internal/app/azldev/cmds/component/history_customizations.go index d1950fc34..8a051a54d 100644 --- a/internal/app/azldev/cmds/component/history_customizations.go +++ b/internal/app/azldev/cmds/component/history_customizations.go @@ -47,8 +47,8 @@ func appendGoVendorItems(items []CustomizationItem, config *projectconfig.GoVend items = append(items, CustomizationItem{Kind: "go-vendor.module-dir", Value: config.ModuleDir}) } - if config.ToolConfig != "" { - items = append(items, CustomizationItem{Kind: "go-vendor.tool-config", Value: config.ToolConfig}) + if config.ConfigFile != "" { + items = append(items, CustomizationItem{Kind: "go-vendor.config-file", Value: config.ConfigFile}) } for _, name := range config.PrepPackages { diff --git a/internal/app/azldev/cmds/component/history_internal_test.go b/internal/app/azldev/cmds/component/history_internal_test.go index eb9ef98fd..858d509f3 100644 --- a/internal/app/azldev/cmds/component/history_internal_test.go +++ b/internal/app/azldev/cmds/component/history_internal_test.go @@ -107,7 +107,6 @@ func TestCustomizationCollectorsCoverEveryFingerprintableField(t *testing.T) { "ComponentConfig.GoVendor": "appendGoVendorItems", "GoVendorConfig.Enabled": "go-vendor.enabled", "GoVendorConfig.ModuleDir": "go-vendor.module-dir", - "GoVendorConfig.ToolConfig": "go-vendor.tool-config", "GoVendorConfig.PrepPackages": "go-vendor.prep-packages", // ComponentBuildConfig. diff --git a/internal/app/azldev/cmds/component/preparerctx_internal_test.go b/internal/app/azldev/cmds/component/preparerctx_internal_test.go index 7118b0017..715286b8f 100644 --- a/internal/app/azldev/cmds/component/preparerctx_internal_test.go +++ b/internal/app/azldev/cmds/component/preparerctx_internal_test.go @@ -52,12 +52,12 @@ func TestGoVendorPreparerOptions(t *testing.T) { func TestGoVendorHistoryCustomizations(t *testing.T) { config := &projectconfig.GoVendorConfig{ Enabled: lo.ToPtr(true), ModuleDir: "cmd/app", - ToolConfig: "[archive]\ntidy = false", PrepPackages: []string{"git"}, + ConfigFile: "/project/go-vendor-tools.toml", PrepPackages: []string{"git"}, } assert.Equal(t, []CustomizationItem{ {Kind: "go-vendor.enabled", Value: "true"}, {Kind: "go-vendor.module-dir", Value: "cmd/app"}, - {Kind: "go-vendor.tool-config", Value: config.ToolConfig}, + {Kind: "go-vendor.config-file", Value: config.ConfigFile}, {Kind: "go-vendor.prep-packages", Value: "git"}, }, collectCustomizations("app", &projectconfig.ComponentConfig{GoVendor: config})) assert.Empty(t, appendGoVendorItems(nil, &projectconfig.GoVendorConfig{})) diff --git a/internal/app/azldev/core/sources/govendor.go b/internal/app/azldev/core/sources/govendor.go index 4d2e42b54..7709ac8e7 100644 --- a/internal/app/azldev/core/sources/govendor.go +++ b/internal/app/azldev/core/sources/govendor.go @@ -14,6 +14,7 @@ import ( "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" @@ -66,7 +67,7 @@ func (p *sourcePreparerImpl) prepareGoVendor( return fmt.Errorf("planning Go vendoring for %#q:\n%w", component.GetName(), err) } - toolConfig, err := p.resolveGoVendorConfig(outputDir, plan, config.ToolConfig) + toolConfig, err := p.resolveGoVendorConfig(outputDir, plan, config) if err != nil { return err } @@ -82,7 +83,7 @@ func (p *sourcePreparerImpl) prepareGoVendor( artifact, err := govendor.Generate(ctx, p.fs, p.goVendorRunner, govendor.Request{ SourceDir: outputDir, WorkDir: scratch, SpecName: filepath.Base(specPath), PrepSpec: plan.PrepSpec, ArchiveFile: plan.ArchiveFile, ArchiveSuffix: plan.ArchiveSuffix, ModuleDir: config.ModuleDir, - ToolConfig: toolConfig, Packages: config.PrepPackages, ExpectedLicense: plan.ExpectedLicense, + ConfigContents: toolConfig, Packages: config.PrepPackages, ExpectedLicense: plan.ExpectedLicense, }) if err != nil { return fmt.Errorf("generating Go vendor sources:\n%w", err) @@ -92,7 +93,7 @@ func (p *sourcePreparerImpl) prepareGoVendor( } func (p *sourcePreparerImpl) resolveGoVendorConfig( - outputDir string, plan *spec.GoVendorSpec, configured string, + outputDir string, plan *spec.GoVendorSpec, config *projectconfig.GoVendorConfig, ) (string, error) { if !plan.AllowReplacement { if err := p.checkGoVendorSourceCollision(outputDir, plan.ArchiveFile, plan.ConfigName); err != nil { @@ -100,8 +101,17 @@ func (p *sourcePreparerImpl) resolveGoVendorConfig( } } - if configured != "" || !plan.AllowReplacement { - return configured, nil + if config.ConfigFile != "" { + content, err := config.ReadConfigFile(p.fs) + if err != nil { + return "", fmt.Errorf("loading Go vendor configuration:\n%w", err) + } + + return content, nil + } + + if !plan.AllowReplacement { + return "", nil } data, err := fileutils.ReadFile(p.fs, filepath.Join(outputDir, plan.ConfigName)) diff --git a/internal/app/azldev/core/sources/govendor_config_internal_test.go b/internal/app/azldev/core/sources/govendor_config_internal_test.go new file mode 100644 index 000000000..f4cb285df --- /dev/null +++ b/internal/app/azldev/core/sources/govendor_config_internal_test.go @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package sources + +import ( + "testing" + + "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/rpm/spec" + "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 TestGoVendorConfigFileSelection(t *testing.T) { + for _, local := range []string{"", "[archive]\ntidy = false\n"} { + ctx := testctx.NewCtx() + require.NoError(t, fileutils.WriteFile(ctx.FS(), "/prepared/upstream.toml", + []byte("[licensing]\ndetector = 'askalono'\n"), fileperms.PublicFile)) + require.NoError(t, fileutils.WriteFile(ctx.FS(), "/project/local.toml", []byte(local), fileperms.PublicFile)) + preparer := &sourcePreparerImpl{fs: ctx.FS()} + plan := &spec.GoVendorSpec{AllowReplacement: true, ConfigName: "upstream.toml"} + config := &projectconfig.GoVendorConfig{ConfigFile: "/project/local.toml"} + actual, err := preparer.resolveGoVendorConfig("/prepared", plan, config) + require.NoError(t, err) + assert.Equal(t, local, actual, "explicit file replaces rather than merges upstream settings") + + config.ConfigFile = "" + actual, err = preparer.resolveGoVendorConfig("/prepared", plan, config) + require.NoError(t, err) + assert.Contains(t, actual, "askalono") + + config.ConfigFile = "/project/missing.toml" + _, err = preparer.resolveGoVendorConfig("/prepared", plan, config) + require.Error(t, err, "missing explicit file must not fall back to upstream") + assert.Contains(t, err.Error(), config.ConfigFile) + } +} diff --git a/internal/app/azldev/core/sources/govendor_internal_test.go b/internal/app/azldev/core/sources/govendor_internal_test.go index 6509507b2..963aeeecc 100644 --- a/internal/app/azldev/core/sources/govendor_internal_test.go +++ b/internal/app/azldev/core/sources/govendor_internal_test.go @@ -45,12 +45,18 @@ func TestPrepareSourcesGoVendor(t *testing.T) { component := components_testutils.NewMockComponent(ctrl) manager := sourceproviders_test.NewMockSourceManager(ctrl) config := &projectconfig.ComponentConfig{ - GoVendor: &projectconfig.GoVendorConfig{Enabled: lo.ToPtr(true), PrepPackages: []string{"git"}}, + GoVendor: &projectconfig.GoVendorConfig{ + Enabled: lo.ToPtr(true), PrepPackages: []string{"git"}, ConfigFile: "/project/vendor.toml", + }, Overlays: []projectconfig.ComponentOverlay{{ Type: "spec-set-tag", Tag: "Summary", Value: "overlaid", }}, } + const settings = "# reviewed settings\n[archive]\nuse_module_proxy = true\n" + require.NoError(t, fileutils.WriteFile(ctx.FS(), config.GoVendor.ConfigFile, + []byte(settings), fileperms.PublicFile)) + component.EXPECT().GetName().AnyTimes().Return("app") component.EXPECT().GetConfig().AnyTimes().Return(config) manager.EXPECT().FetchComponent(gomock.Any(), component, "/output", gomock.Any()).DoAndReturn( @@ -78,6 +84,10 @@ func TestPrepareSourcesGoVendor(t *testing.T) { assert.Contains(t, cmd.Args, "--enable-network") assert.Contains(t, strings.Join(cmd.Args, " "), "go_vendor_archive") staging := goVendorTestStaging(t, ctx) + stagedConfig, err := fileutils.ReadFile(ctx.FS(), filepath.Join(staging, govendor.ConfigFilename)) + require.NoError(t, err) + assert.Equal(t, settings, string(stagedConfig)) + prep, err := fileutils.ReadFile(ctx.FS(), filepath.Join(filepath.Dir(staging), "sources", "app.spec")) require.NoError(t, err) assert.Contains(t, string(prep), "Summary: overlaid", "overlays must run before generation") @@ -109,6 +119,10 @@ func TestPrepareSourcesGoVendor(t *testing.T) { assert.Contains(t, string(output), "tar -xf %{SOURCE1}") assert.NotContains(t, string(output), "BuildRequires: golang(") + publishedConfig, err := fileutils.ReadFile(ctx.FS(), "/output/"+govendor.ConfigFilename) + require.NoError(t, err) + assert.Equal(t, settings, string(publishedConfig)) + digest, err := fileutils.ComputeFileHash(ctx.FS(), fileutils.HashTypeSHA512, "/output/app-vendor.tar.bz2") require.NoError(t, err) sources, err := fileutils.ReadFile(ctx.FS(), "/output/sources") diff --git a/internal/fingerprint/doc.go b/internal/fingerprint/doc.go index fc655afa2..5ad05185b 100644 --- a/internal/fingerprint/doc.go +++ b/internal/fingerprint/doc.go @@ -3,7 +3,7 @@ // Package fingerprint computes deterministic identity fingerprints for components. // A fingerprint captures all resolved build inputs so that changes to any input -// (config fields, spec content, overlay files, distro context, upstream refs, or +// (config fields, spec content, overlay/vendor config files, distro context, upstream refs, or // ManualBump) produce a different fingerprint. // // The primary entry point is [ComputeIdentity], which takes a resolved diff --git a/internal/fingerprint/fingerprint.go b/internal/fingerprint/fingerprint.go index 391559d66..6ab13bb14 100644 --- a/internal/fingerprint/fingerprint.go +++ b/internal/fingerprint/fingerprint.go @@ -42,6 +42,9 @@ type ComponentInputs struct { // source file's basename and content. Keyed by index rather than path to avoid // checkout-location dependence. OverlayFileHashes map[string]string `json:"overlayFileHashes,omitempty"` + // GoVendorConfigHash records the contents of an explicitly selected vendor + // configuration without depending on its checkout-specific path. + GoVendorConfigHash string `json:"goVendorConfigHash,omitempty"` // ManualBump is the manual rebuild counter from the lock file. Almost always 0; // used for mass-rebuild scenarios. ManualBump int `json:"manualBump"` @@ -62,13 +65,13 @@ type IdentityOptions struct { // // This is caller-provided because resolving it requires network access (upstream clone) or // filesystem traversal (local content hash). [ComputeIdentity] is a pure combiner — it does - // not perform I/O beyond reading overlay files. Callers should resolve source identity via + // not perform I/O beyond reading declared input files. Callers should resolve source identity via // SourceManager.ResolveSourceIdentity before calling [ComputeIdentity]. SourceIdentity string } // ComputeIdentity computes the fingerprint for a component from its resolved config -// and additional context. The fs parameter is used to read overlay source file +// and additional context. The fs parameter is used to read declared input file // contents for hashing; spec content identity is provided via [IdentityOptions.SourceIdentity]. // // This function is a deterministic combiner: given the same resolved inputs it always @@ -141,6 +144,11 @@ func ComputeIdentity( inputs.OverlayFileHashes = overlayHashes + inputs.GoVendorConfigHash, err = component.GoVendor.SourceContentIdentity(fs) + if err != nil { + return nil, fmt.Errorf("hashing Go vendor configuration:\n%w", err) + } + // 5. Combine all inputs into the overall fingerprint. return &ComponentIdentity{ Fingerprint: combineInputs(inputs), @@ -158,6 +166,10 @@ func combineInputs(inputs ComponentInputs) string { writeField(hasher, "manual_bump", strconv.Itoa(inputs.ManualBump)) writeField(hasher, "release_ver", inputs.ReleaseVer) + if inputs.GoVendorConfigHash != "" { + writeField(hasher, "go_vendor_config", inputs.GoVendorConfigHash) + } + // Overlay file hashes in sorted key order for determinism. if len(inputs.OverlayFileHashes) > 0 { keys := make([]string, 0, len(inputs.OverlayFileHashes)) diff --git a/internal/fingerprint/govendor_test.go b/internal/fingerprint/govendor_test.go new file mode 100644 index 000000000..cd47c3838 --- /dev/null +++ b/internal/fingerprint/govendor_test.go @@ -0,0 +1,62 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package fingerprint_test + +import ( + "testing" + + "github.com/microsoft/azure-linux-dev-tools/internal/fingerprint" + "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/samber/lo" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestGoVendorConfigFileFingerprint(t *testing.T) { + ctx := newTestFS(t, map[string]string{ + "/checkout-one/vendor.toml": "[archive]\ntidy = false\n", + "/checkout-two/vendor.toml": "[archive]\ntidy = false\n", + "/empty.toml": "", + }) + component := projectconfig.ComponentConfig{GoVendor: &projectconfig.GoVendorConfig{ + Enabled: lo.ToPtr(true), ConfigFile: "/checkout-one/vendor.toml", + }} + compute := func(config projectconfig.ComponentConfig) *fingerprint.ComponentIdentity { + t.Helper() + + result, err := fingerprint.ComputeIdentity(ctx.FS(), config, testReleaseVer, fingerprint.IdentityOptions{}) + require.NoError(t, err) + + return result + } + initial := compute(component) + require.NotEmpty(t, initial.Inputs.GoVendorConfigHash) + assert.Equal(t, "/checkout-one/vendor.toml", component.GoVendor.ConfigFile) + component.GoVendor.ConfigFile = "/checkout-two/vendor.toml" + assert.Equal(t, initial.Fingerprint, compute(component).Fingerprint, "checkout location must not affect identity") + + require.NoError(t, fileutils.WriteFile(ctx.FS(), component.GoVendor.ConfigFile, + []byte("[archive]\ntidy = true\n"), fileperms.PublicFile)) + assert.NotEqual(t, initial.Fingerprint, compute(component).Fingerprint, + "file-only edits must invalidate the fingerprint") + component.GoVendor.ConfigFile = "/empty.toml" + emptyFile := compute(component) + component.GoVendor.ConfigFile = "" + noFile := compute(component) + assert.Empty(t, noFile.Inputs.GoVendorConfigHash) + assert.NotEqual(t, emptyFile.Fingerprint, noFile.Fingerprint, "an empty override is not upstream fallback") +} + +func TestGoVendorConfigFileFingerprintErrors(t *testing.T) { + ctx := newTestFS(t, map[string]string{"/bad.toml": "["}) + for _, path := range []string{"/missing.toml", "/bad.toml"} { + _, err := fingerprint.ComputeIdentity(ctx.FS(), projectconfig.ComponentConfig{ + GoVendor: &projectconfig.GoVendorConfig{Enabled: lo.ToPtr(true), ConfigFile: path}, + }, testReleaseVer, fingerprint.IdentityOptions{}) + require.Error(t, err) + assert.Contains(t, err.Error(), path) + } +} diff --git a/internal/govendor/generate.go b/internal/govendor/generate.go index 0f888ddfe..68c69889d 100644 --- a/internal/govendor/generate.go +++ b/internal/govendor/generate.go @@ -37,7 +37,7 @@ const ( type Request struct { SourceDir, WorkDir, SpecName string ArchiveFile, ArchiveSuffix string - ModuleDir, ToolConfig string + ModuleDir, ConfigContents string ExpectedLicense string PrepSpec []byte Packages []string @@ -90,7 +90,7 @@ func stage(fs opctx.FS, request Request, sourceCopy, staging string) error { for path, data := range map[string][]byte{ filepath.Join(sourceCopy, request.SpecName): request.PrepSpec, - filepath.Join(staging, ConfigFilename): []byte(request.ToolConfig), + filepath.Join(staging, ConfigFilename): []byte(request.ConfigContents), } { if err := fileutils.WriteFile(fs, path, data, fileperms.PublicFile); err != nil { return fmt.Errorf("staging Go vendor input %#q:\n%w", path, err) @@ -134,7 +134,7 @@ func execute(ctx context.Context, runner *mock.Runner, request Request) (err err output, err := cmd.RunAndGetOutput(ctx) if err != nil { return fmt.Errorf("go vendor generation or license detection failed; use 'prep-packages' for missing prep tools "+ - "and 'tool-config' for reviewed license exceptions:\n%s\n%w", output, err) + "and 'config-file' for reviewed license exceptions:\n%s\n%w", output, err) } return nil diff --git a/internal/projectconfig/component.go b/internal/projectconfig/component.go index d3b2404aa..be9e8c0ef 100644 --- a/internal/projectconfig/component.go +++ b/internal/projectconfig/component.go @@ -653,6 +653,9 @@ func (c *ComponentConfig) WithAbsolutePaths(referenceDir string) *ComponentConfi // Fix up paths. result.Spec.Path = makeAbsolute(referenceDir, result.Spec.Path) + if result.GoVendor != nil { + result.GoVendor.ConfigFile = makeAbsolute(referenceDir, result.GoVendor.ConfigFile) + } for i := range result.SourceFiles { origin := &result.SourceFiles[i].Origin diff --git a/internal/projectconfig/fingerprint_test.go b/internal/projectconfig/fingerprint_test.go index dcf89f830..881ea95fb 100644 --- a/internal/projectconfig/fingerprint_test.go +++ b/internal/projectconfig/fingerprint_test.go @@ -106,6 +106,9 @@ func TestAllFingerprintedFieldsHaveDecision(t *testing.T) { // SpecSource.Path — absolute path that varies by checkout location. // Spec content identity is captured separately via SourceIdentity. "SpecSource.Path": true, + + // GoVendorConfig.ConfigFile — absolute declaration path; contents are hashed separately. + "GoVendorConfig.ConfigFile": true, } // Collect all actual exclusions found via reflection, and flag invalid tag values. diff --git a/internal/projectconfig/govendor.go b/internal/projectconfig/govendor.go index cf9fc4eae..415a2a7c7 100644 --- a/internal/projectconfig/govendor.go +++ b/internal/projectconfig/govendor.go @@ -4,10 +4,13 @@ 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" ) @@ -18,8 +21,9 @@ type GoVendorConfig struct { Enabled *bool `toml:"enabled,omitempty" json:"enabled,omitempty" jsonschema:"title=Enabled,description=Enable Go application vendoring"` // ModuleDir is relative to the directory left by the spec's prep section. ModuleDir string `toml:"module-dir,omitempty" json:"moduleDir,omitempty" jsonschema:"title=Module directory,description=Relative module directory within the prepared source tree; defaults to its root"` - // ToolConfig is inline go-vendor-tools TOML, including reviewed license exceptions. - ToolConfig string `toml:"tool-config,omitempty" json:"toolConfig,omitempty" jsonschema:"title=Tool configuration,description=Inline go-vendor-tools TOML for dependency overrides and licensing settings"` + // ConfigFile identifies a native go-vendor-tools TOML file, relative to the declaring + // config file. Resolved to an absolute path; its contents are fingerprinted separately. + ConfigFile string `toml:"config-file,omitempty" json:"configFile,omitempty" jsonschema:"title=Vendor configuration file,description=Path to a go-vendor-tools TOML file relative to the declaring component configuration. Replaces upstream settings when specified,example=go-vendor-tools.toml" fingerprint:"-"` // PrepPackages supplies additional tools used by upstream prep commands. PrepPackages []string `toml:"prep-packages,omitempty" json:"prepPackages,omitempty" jsonschema:"title=Prep packages,description=Additional RPM packages needed to execute the upstream prep section in mock"` } @@ -29,7 +33,7 @@ func (c *GoVendorConfig) IsEnabled() bool { return c != nil && c.Enabled != nil && *c.Enabled } -// Validate checks paths and tool configuration before any source processing. +// Validate checks configuration values before any source processing. func (c *GoVendorConfig) Validate() error { if c == nil { return nil @@ -45,15 +49,8 @@ func (c *GoVendorConfig) Validate() error { } } - var toolConfig map[string]any - if err := toml.Unmarshal([]byte(c.ToolConfig), &toolConfig); err != nil { - return fmt.Errorf("invalid 'tool-config' TOML:\n%w", err) - } - - if general, ok := toolConfig["general"].(map[string]any); ok { - if _, exists := general["go_mod_dir"]; exists { - return errors.New("use 'module-dir' instead of 'general.go_mod_dir' in 'tool-config'") - } + if strings.ContainsAny(c.ConfigFile, "\x00\r\n") { + return errors.New("'config-file' must be a local file path without NUL or newlines") } for _, name := range c.PrepPackages { @@ -64,3 +61,42 @@ func (c *GoVendorConfig) Validate() error { return nil } + +// SourceContentIdentity hashes the selected configuration independently of its path. +// No configured file yields no identity; an explicitly empty file still has a hash. +func (c *GoVendorConfig) SourceContentIdentity(fs opctx.FS) (string, error) { + if c == nil || c.ConfigFile == "" { + return "", nil + } + + content, err := c.ReadConfigFile(fs) + if err != nil { + return "", err + } + + digest := sha256.Sum256([]byte(content)) + + return hex.EncodeToString(digest[:]), nil +} + +// ReadConfigFile reads and validates the explicitly selected native configuration. +// An empty file is a valid, intentional replacement; callers must not fall back to upstream settings. +func (c *GoVendorConfig) ReadConfigFile(fs opctx.FS) (string, error) { + data, err := fileutils.ReadFile(fs, c.ConfigFile) + if err != nil { + return "", fmt.Errorf("reading 'go-vendor.config-file' %#q:\n%w", c.ConfigFile, err) + } + + var settings map[string]any + if err := toml.Unmarshal(data, &settings); err != nil { + return "", fmt.Errorf("invalid TOML in 'go-vendor.config-file' %#q:\n%w", c.ConfigFile, err) + } + + if general, ok := settings["general"].(map[string]any); ok { + if _, exists := general["go_mod_dir"]; exists { + return "", fmt.Errorf("use 'module-dir' instead of 'general.go_mod_dir' in %#q", c.ConfigFile) + } + } + + return string(data), nil +} diff --git a/internal/projectconfig/govendor_loader_internal_test.go b/internal/projectconfig/govendor_loader_internal_test.go new file mode 100644 index 000000000..a0af07a33 --- /dev/null +++ b/internal/projectconfig/govendor_loader_internal_test.go @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package projectconfig + +import ( + "testing" + + "github.com/microsoft/azure-linux-dev-tools/internal/global/testctx" + "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 TestGoVendorConfigFileDeclarationAndInheritance(t *testing.T) { + ctx := testctx.NewCtx() + + files := map[string]string{ + "/project/azldev.toml": `includes = ["defaults/group.toml", "components/app.comp.toml"]`, + "/project/defaults/group.toml": ` +[component-groups.base] +components = ["app"] +[component-groups.base.default-component-config.go-vendor] +enabled = true +config-file = "go-vendor-tools.toml" +`, + "/project/components/app.comp.toml": `[components.app]`, + } + for path, content := range files { + require.NoError(t, fileutils.WriteFile(ctx.FS(), path, []byte(content), fileperms.PublicFile)) + } + + for _, withoutLockfile := range []bool{false, true} { + config, err := loadAndResolveProjectConfig(ctx.FS(), loadOptions{withoutLockfile: withoutLockfile}, + "/project/azldev.toml") + require.NoError(t, err) + resolved, err := ResolveComponentConfig(config.Components["app"], config.DefaultComponentConfig, + ComponentConfig{}, config.ComponentGroups, []string{"base"}) + require.NoError(t, err) + assert.Equal(t, "/project/defaults/go-vendor-tools.toml", resolved.GoVendor.ConfigFile) + assert.True(t, resolved.GoVendor.IsEnabled()) + } +} + +func TestGoVendorInlineConfigurationIsRejected(t *testing.T) { + for _, contents := range []string{ + "[components.app.go-vendor]\nenabled = true\ntool-config = '[archive]'", + "[components.app.go-vendor.tool-config.archive]\nuse_module_proxy = true", + } { + ctx := testctx.NewCtx() + require.NoError(t, fileutils.WriteFile(ctx.FS(), "/project/azldev.toml", []byte(contents), fileperms.PublicFile)) + _, err := loadAndResolveProjectConfig(ctx.FS(), loadOptions{}, "/project/azldev.toml") + require.Error(t, err) + } +} diff --git a/internal/projectconfig/govendor_test.go b/internal/projectconfig/govendor_test.go index e94ead8c6..02feb6943 100644 --- a/internal/projectconfig/govendor_test.go +++ b/internal/projectconfig/govendor_test.go @@ -4,9 +4,14 @@ package projectconfig_test import ( + "os" + "path/filepath" "testing" + "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/mitchellh/hashstructure/v2" "github.com/pelletier/go-toml/v2" "github.com/samber/lo" @@ -21,14 +26,14 @@ func TestGoVendorConfig(t *testing.T) { enabled = true module-dir = "cmd/app" prep-packages = ["git"] -tool-config = ''' -[archive.dependency_overrides] -"example.com/module" = "v1.2.3" -''' +config-file = "go-vendor-tools.toml" `), &config)) require.True(t, config.GoVendor.IsEnabled()) require.NoError(t, config.GoVendor.Validate()) - require.Equal(t, config.GoVendor, config.WithAbsolutePaths("/project").GoVendor) + resolved := config.WithAbsolutePaths("/project") + assert.Equal(t, filepath.Join("/project", "go-vendor-tools.toml"), resolved.GoVendor.ConfigFile) + assert.Equal(t, "go-vendor-tools.toml", config.GoVendor.ConfigFile) + assert.Equal(t, resolved.GoVendor, resolved.WithAbsolutePaths("/elsewhere").GoVendor) require.NoError(t, config.MergeUpdatesFrom(&projectconfig.ComponentConfig{ GoVendor: &projectconfig.GoVendorConfig{Enabled: lo.ToPtr(false)}, })) @@ -40,8 +45,8 @@ func TestGoVendorConfigValidation(t *testing.T) { {ModuleDir: "../outside"}, {ModuleDir: "/absolute"}, {ModuleDir: "%{macro}"}, - {ToolConfig: "["}, - {ToolConfig: "[general]\ngo_mod_dir = 'subdir'"}, + {ConfigFile: "bad\x00path"}, + {ConfigFile: "bad\npath"}, {PrepPackages: []string{"--bad"}}, {PrepPackages: []string{""}}, } { @@ -69,7 +74,6 @@ func TestGoVendorFingerprint(t *testing.T) { for _, config := range []*projectconfig.GoVendorConfig{ {Enabled: lo.ToPtr(false)}, {Enabled: lo.ToPtr(true), ModuleDir: "sub"}, - {Enabled: lo.ToPtr(true), ToolConfig: "[archive]\ntidy = false"}, {Enabled: lo.ToPtr(true), PrepPackages: []string{"git"}}, } { changed := base @@ -79,3 +83,47 @@ func TestGoVendorFingerprint(t *testing.T) { assert.NotEqual(t, original, hash) } } + +func TestGoVendorConfigFileContentIdentity(t *testing.T) { + ctx := testctx.NewCtx() + + var absent *projectconfig.GoVendorConfig + + identity, err := absent.SourceContentIdentity(ctx.FS()) + require.NoError(t, err) + assert.Empty(t, identity) + + config := &projectconfig.GoVendorConfig{} + identity, err = config.SourceContentIdentity(ctx.FS()) + require.NoError(t, err) + assert.Empty(t, identity) + + config.ConfigFile = "/project/vendor.toml" + _, err = config.SourceContentIdentity(ctx.FS()) + require.ErrorIs(t, err, os.ErrNotExist) + + for _, contents := range []string{"", "# reviewed\n[archive]\nuse_module_proxy = true\n"} { + require.NoError(t, fileutils.WriteFile(ctx.FS(), config.ConfigFile, []byte(contents), fileperms.PublicFile)) + actual, err := config.ReadConfigFile(ctx.FS()) + require.NoError(t, err) + assert.Equal(t, contents, actual) + + identity, err = config.SourceContentIdentity(ctx.FS()) + require.NoError(t, err) + expected, err := fileutils.ComputeFileHash(ctx.FS(), fileutils.HashTypeSHA256, config.ConfigFile) + require.NoError(t, err) + assert.Equal(t, expected, identity) + } +} + +func TestGoVendorConfigFileValidation(t *testing.T) { + for _, contents := range []string{"[", "[general]\ngo_mod_dir = 'subdir'"} { + ctx := testctx.NewCtx() + require.NoError(t, fileutils.WriteFile(ctx.FS(), "/project/vendor.toml", []byte(contents), fileperms.PublicFile)) + + config := projectconfig.GoVendorConfig{ConfigFile: "/project/vendor.toml"} + _, err := config.ReadConfigFile(ctx.FS()) + require.Error(t, err) + assert.Contains(t, err.Error(), config.ConfigFile) + } +} diff --git a/scenario/__snapshots__/TestSnapshots_config_generate-schema_stdout_1.snap b/scenario/__snapshots__/TestSnapshots_config_generate-schema_stdout_1.snap index 65c59d83a..9259ce684 100755 --- a/scenario/__snapshots__/TestSnapshots_config_generate-schema_stdout_1.snap +++ b/scenario/__snapshots__/TestSnapshots_config_generate-schema_stdout_1.snap @@ -699,10 +699,13 @@ "title": "Module directory", "description": "Relative module directory within the prepared source tree; defaults to its root" }, - "tool-config": { + "config-file": { "type": "string", - "title": "Tool configuration", - "description": "Inline go-vendor-tools TOML for dependency overrides and licensing settings" + "title": "Vendor configuration file", + "description": "Path to a go-vendor-tools TOML file relative to the declaring component configuration. Replaces upstream settings when specified", + "examples": [ + "go-vendor-tools.toml" + ] }, "prep-packages": { "items": { diff --git a/schemas/azldev.schema.json b/schemas/azldev.schema.json index 65c59d83a..9259ce684 100644 --- a/schemas/azldev.schema.json +++ b/schemas/azldev.schema.json @@ -699,10 +699,13 @@ "title": "Module directory", "description": "Relative module directory within the prepared source tree; defaults to its root" }, - "tool-config": { + "config-file": { "type": "string", - "title": "Tool configuration", - "description": "Inline go-vendor-tools TOML for dependency overrides and licensing settings" + "title": "Vendor configuration file", + "description": "Path to a go-vendor-tools TOML file relative to the declaring component configuration. Replaces upstream settings when specified", + "examples": [ + "go-vendor-tools.toml" + ] }, "prep-packages": { "items": { From 26eb3559daec4c35288cdd3d8dee2979b652eaeb Mon Sep 17 00:00:00 2001 From: Antonio Salinas <173939267+Tonisal-byte@users.noreply.github.com> Date: Mon, 2 Nov 2026 12:58:50 -0800 Subject: [PATCH 04/16] fix: harden Go vendor source regeneration Address the eight unique findings in PR #424: reject source-file collisions, pin expanded archive names, snapshot regular chroot outputs without following symlinks, preserve module-aware checks, extract generated metadata after prep edits, reject ambiguous extraction layouts, honor native module subdirectories, and run archive hooks from staged dist-git. Add regression coverage and update user documentation and emitted agent guidance. Unit and quality checks pass; changed-code mutation audit kills all 37 mutations. The containerd update/prepare/render/build flow and isolated RPM daemon smoke test pass, including staged-sidecar hook checks. Ran ./magefile.go scenarioUpdate before pushing; the schema snapshot is current. Full Docker-dependent scenarios remain blocked by the unavailable Docker provider. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/user/how-to/vendor-go-application.md | 19 ++- docs/user/reference/config/components.md | 12 +- .../app/azldev/agentskill/agentskill_test.go | 2 + .../agentskill/content/comp-toml.md.tmpl | 4 + .../content/withoutlockfile/comp-toml.md.tmpl | 4 + internal/app/azldev/core/sources/govendor.go | 8 +- .../govendor_existing_internal_test.go | 46 ++++++- internal/govendor/generate.go | 80 +++++++++++- internal/govendor/generate_internal_test.go | 123 ++++++++++++++++++ internal/rpm/spec/govendor.go | 29 +++-- internal/rpm/spec/govendor_existing.go | 30 ++++- internal/rpm/spec/govendor_existing_test.go | 46 ++++++- internal/rpm/spec/govendor_test.go | 5 +- internal/utils/fileutils/copy.go | 17 ++- internal/utils/fileutils/file.go | 26 ++++ internal/utils/fileutils/nofollow_test.go | 74 +++++++++++ 16 files changed, 488 insertions(+), 37 deletions(-) create mode 100644 internal/utils/fileutils/nofollow_test.go diff --git a/docs/user/how-to/vendor-go-application.md b/docs/user/how-to/vendor-go-application.md index 3892e8426..4cb103c32 100644 --- a/docs/user/how-to/vendor-go-application.md +++ b/docs/user/how-to/vendor-go-application.md @@ -59,6 +59,8 @@ there and runs the existing `%prep` section with `rpmbuild -bp --nodeps`. This retains upstream patches and edits to module files. It then calls `go_vendor_archive create` on the prepared module tree, extracts the result for license detection, and runs `go_vendor_license` without interactive prompts. +The archive tool runs from staged dist-git, so hooks can find preserved patches +and sidecars through `GVT_CWD`. Unrecognized licenses fail preparation; add reviewed, hash-qualified exceptions to the file selected by `config-file` rather than suppressing detection. @@ -102,11 +104,17 @@ For an already-vendored spec, azldev recognizes a single referenced by `%go_vendor_license_* -c %{S:M}` commands. The Source numbers need not be 1 and 2. The configuration must name a plain sidecar file. -The original Source declarations, extraction command, license/file-list macros, -module-mode settings, and custom packaging are retained. The temporary prep spec +The original Source numbers, license/file-list macros, module-mode settings, and +custom packaging are retained. The vendor extraction moves to the end of `%prep`, +after module-file patches and edits, because the replacement archive already +contains their results. Directory changes after the original extraction and +secondary-source extraction with `%setup -a/-b` or `%autosetup -a/-b` are rejected +as ambiguous; adapt these layouts with an overlay. The temporary prep spec omits the vendor Source declaration and its extraction command, so generating the replacement does not consume the old vendor payload. RPM expands the -upstream archive filename; the regenerated archive replaces that file and its +upstream archive filename and pins the vendor Source tag to that expanded name, +so subsequent release/history changes cannot desynchronize the spec and payload. +The regenerated archive replaces that file and its `sources` checksum rather than adding a second vendor archive. When `config-file` is omitted, the upstream go-vendor-tools configuration is used, @@ -114,6 +122,11 @@ including its reviewed license exceptions. An explicit file replaces that config even when empty; missing files or invalid TOML fail without falling back. The detected licenses are verified against the existing main-package `License:` expression; mismatches fail instead of rewriting it. +Upstream `general.go_mod_dir` is honored by generation and licensing, preserving +the module subdirectory within the archive. A conflicting `module-dir` fails; +use a separate `config-file` to replace upstream settings when changing the layout. +Neither the regenerated archive nor its configuration sidecar may also be +declared in `source-files`, even with `replace-upstream = true`. The source-fetch phase currently still downloads the upstream vendor archive alongside the other upstream sources, before regenerating its contents. diff --git a/docs/user/reference/config/components.md b/docs/user/reference/config/components.md index 530b9cea3..f483f671f 100644 --- a/docs/user/reference/config/components.md +++ b/docs/user/reference/config/components.md @@ -205,7 +205,9 @@ config-file = "go-vendor-tools.toml" The configured file must exist and contain valid TOML. An explicitly selected empty file is an empty replacement, not a request to fall back to upstream. -Use `module-dir`, not `general.go_mod_dir`, for the module location. +In an explicitly selected file, use `module-dir`, not `general.go_mod_dir`, for +the module location. Reused upstream `general.go_mod_dir` settings remain honored; +an inconsistent component `module-dir` is rejected. Configured command hooks execute in the generation chroot; treat this file as trusted build code. The old inline `tool-config` string/table is no longer supported. @@ -218,8 +220,14 @@ The recorded digest identifies that output, not a separately pinned vendor lock. For supported specs already using go-vendor-tools, preparation instead regenerates the existing vendor source, retaining its Source number, RPM-expanded filename, -and configuration sidecar. It updates that archive's `sources` entry in place and +and configuration sidecar. The Source tag is pinned to the generated filename +before release/history updates, and extraction moves after prep's module edits +to avoid applying patches twice. Ambiguous secondary-source setup and +post-extraction directory changes require a prep overlay. +It updates that archive's `sources` entry in place and verifies the existing `License:` expression without rewriting it. +These generated archive/config filenames must not also appear in `source-files`, +including entries with `replace-upstream = true`. When `config-file` is set, its contents are staged under the configuration filename referenced by the prepared spec, retaining the existing Source number. diff --git a/internal/app/azldev/agentskill/agentskill_test.go b/internal/app/azldev/agentskill/agentskill_test.go index 0836c6751..5805e5282 100644 --- a/internal/app/azldev/agentskill/agentskill_test.go +++ b/internal/app/azldev/agentskill/agentskill_test.go @@ -170,6 +170,8 @@ func TestComponentTomlSkillDocumentsGoVendoring(t *testing.T) { assert.Contains(t, doc, "reviewed license exceptions") assert.Contains(t, doc, `config-file = "go-vendor-tools.toml"`) assert.Contains(t, doc, "Inline `tool-config` is not supported.") + assert.Contains(t, doc, "Upstream `general.go_mod_dir` is honored") + assert.Contains(t, doc, "Source filename is pinned before") } } diff --git a/internal/app/azldev/agentskill/content/comp-toml.md.tmpl b/internal/app/azldev/agentskill/content/comp-toml.md.tmpl index b724ea0ef..7059b2ae3 100644 --- a/internal/app/azldev/agentskill/content/comp-toml.md.tmpl +++ b/internal/app/azldev/agentskill/content/comp-toml.md.tmpl @@ -53,6 +53,10 @@ Generated `-vendor.tar.bz2` and `azldev-go-vendor.toml` must not also declared as `source-files`. For supported already-vendored specs, regenerate the existing vendor Source instead, reuse upstream tool configuration unless overridden, and verify rather than replace the reviewed `License:` expression. +The regenerated archive and configuration must not also be `source-files` entries. +Upstream `general.go_mod_dir` is honored; conflicting `module-dir` values fail. +Vendor extraction runs after prep edits, and its Source filename is pinned before +release/history updates. Ambiguous secondary-source setup requires an overlay. Unsupported constructs (notably automatic Go devel subpackages, flagged `%gocheck`, or ambiguous sections) require explicit overlays; never replace the upstream spec wholesale to bypass a conversion error. 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 cd0ec3e48..2ac8df159 100644 --- a/internal/app/azldev/agentskill/content/withoutlockfile/comp-toml.md.tmpl +++ b/internal/app/azldev/agentskill/content/withoutlockfile/comp-toml.md.tmpl @@ -53,6 +53,10 @@ Generated `-vendor.tar.bz2` and `azldev-go-vendor.toml` must not also declared as `source-files`. For supported already-vendored specs, regenerate the existing vendor Source instead, reuse upstream tool configuration unless overridden, and verify rather than replace the reviewed `License:` expression. +The regenerated archive and configuration must not also be `source-files` entries. +Upstream `general.go_mod_dir` is honored; conflicting `module-dir` values fail. +Vendor extraction runs after prep edits, and its Source filename is pinned before +release/history updates. Ambiguous secondary-source setup requires an overlay. Unsupported constructs (notably automatic Go devel subpackages, flagged `%gocheck`, or ambiguous sections) require explicit overlays; never replace the upstream spec wholesale to bypass a conversion error. diff --git a/internal/app/azldev/core/sources/govendor.go b/internal/app/azldev/core/sources/govendor.go index 7709ac8e7..fb0619758 100644 --- a/internal/app/azldev/core/sources/govendor.go +++ b/internal/app/azldev/core/sources/govendor.go @@ -89,6 +89,12 @@ func (p *sourcePreparerImpl) prepareGoVendor( return fmt.Errorf("generating Go vendor sources:\n%w", err) } + for _, ref := range component.GetConfig().SourceFiles { + if ref.Filename == artifact.Name || ref.Filename == plan.ConfigName { + return fmt.Errorf("'source-files' entry %#q conflicts with generated Go vendor sources", ref.Filename) + } + } + return p.publishGoVendor(outputDir, filepath.Base(specPath), toolConfig, plan, artifact) } @@ -129,7 +135,7 @@ func (p *sourcePreparerImpl) publishGoVendor( return fmt.Errorf("generated Go archive %#q does not match planned name %#q", artifact.Name, plan.ArchiveFile) } - finalSpec, err := plan.FinalizeLicense(artifact.License) + finalSpec, err := plan.Finalize(artifact.Name, artifact.License) if err != nil { return fmt.Errorf("finalizing Go vendor spec:\n%w", err) } diff --git a/internal/app/azldev/core/sources/govendor_existing_internal_test.go b/internal/app/azldev/core/sources/govendor_existing_internal_test.go index b9d47d92b..3ab85fd8a 100644 --- a/internal/app/azldev/core/sources/govendor_existing_internal_test.go +++ b/internal/app/azldev/core/sources/govendor_existing_internal_test.go @@ -23,12 +23,30 @@ import ( ) func TestPrepareExistingGoVendorReplacesPayload(t *testing.T) { + for _, conflict := range []string{"", "app-1.2-vendor.tar.bz2", "go-vendor-tools.toml"} { + t.Run("source-file-"+conflict, func(t *testing.T) { + testPrepareExistingGoVendor(t, conflict) + }) + } +} + +func testPrepareExistingGoVendor(t *testing.T, conflict string) { + t.Helper() + ctx := newMockProcessorTestCtx() component := components_testutils.NewMockComponent(gomock.NewController(t)) component.EXPECT().GetName().AnyTimes().Return("app") - component.EXPECT().GetConfig().AnyTimes().Return(&projectconfig.ComponentConfig{ + + config := &projectconfig.ComponentConfig{ GoVendor: &projectconfig.GoVendorConfig{Enabled: lo.ToPtr(true)}, - }) + } + if conflict != "" { + config.SourceFiles = []projectconfig.SourceFileReference{{ + Filename: conflict, ReplaceUpstream: true, Hash: strings.Repeat("a", 128), HashType: fileutils.HashTypeSHA512, + }} + } + + component.EXPECT().GetConfig().AnyTimes().Return(config) input := strings.Join([]string{ "Name: app", "Version: 1.2", "Release: 1", "License: MIT AND Apache-2.0", @@ -75,14 +93,34 @@ func TestPrepareExistingGoVendorReplacesPayload(t *testing.T) { return "", nil } preparer := &sourcePreparerImpl{fs: ctx.FS(), dryRunnable: ctx, goVendorRunner: mock.NewRunner(ctx, "/mock.cfg")} - require.NoError(t, preparer.prepareGoVendor(ctx, component, "/output")) + + err := preparer.prepareGoVendor(ctx, component, "/output") + if conflict != "" { + require.ErrorContains(t, err, "'source-files'") + + unchanged, readErr := fileutils.ReadFile(ctx.FS(), "/output/app.spec") + require.NoError(t, readErr) + assert.Equal(t, input, string(unchanged)) + + payload, readErr := fileutils.ReadFile(ctx.FS(), "/output/"+archiveName) + require.NoError(t, readErr) + assert.Equal(t, "old vendor", string(payload)) + + manifest, readErr := fileutils.ReadFile(ctx.FS(), "/output/sources") + require.NoError(t, readErr) + assert.Equal(t, oldEntry+"\n", string(manifest)) + + return + } + + require.NoError(t, err) payload, err := fileutils.ReadFile(ctx.FS(), "/output/"+archiveName) require.NoError(t, err) assert.Equal(t, "new vendor", string(payload)) finalSpec, err := fileutils.ReadFile(ctx.FS(), "/output/app.spec") require.NoError(t, err) - assert.Contains(t, string(finalSpec), "Source1: app-%{version}-vendor.tar.bz2") + assert.Contains(t, string(finalSpec), "Source1: "+archiveName) assert.Contains(t, string(finalSpec), "License: MIT AND Apache-2.0") assert.NotContains(t, string(finalSpec), "azldev-go-vendor.toml") diff --git a/internal/govendor/generate.go b/internal/govendor/generate.go index 68c69889d..3d8fa4a02 100644 --- a/internal/govendor/generate.go +++ b/internal/govendor/generate.go @@ -20,6 +20,7 @@ import ( "github.com/microsoft/azure-linux-dev-tools/internal/rpm/spectool" "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" ) const ( @@ -41,6 +42,7 @@ type Request struct { ExpectedLicense string PrepSpec []byte Packages []string + configModuleDir string } // Artifact is validated generation output, ready for publication by the caller. @@ -51,6 +53,11 @@ type Artifact struct { // Generate prepares inputs and generates an archive in one isolated mock root. // It never changes SourceDir or publishes a spec or source manifest. func Generate(ctx context.Context, fs opctx.FS, base *mock.Runner, request Request) (Artifact, error) { + request, err := resolveModuleDir(request) + if err != nil { + return Artifact{}, err + } + staging := filepath.Join(request.WorkDir, "work") sourceCopy := filepath.Join(request.WorkDir, "sources") @@ -65,11 +72,73 @@ func Generate(ctx context.Context, fs opctx.FS, base *mock.Runner, request Reque return Artifact{}, err } - if err := validateInputs(fs, staging, request.SourceDir); err != nil { + // Snapshot only regular outputs into a host-only directory. Subsequent + // validation, hashing and publication never reopen chroot-writable paths. + trusted := filepath.Join(request.WorkDir, "artifacts") + if err := fileutils.MkdirAll(fs, trusted); err != nil { + return Artifact{}, fmt.Errorf("creating trusted Go vendor output directory:\n%w", err) + } + + for _, name := range []string{request.ArchiveFile, "archive-name", "license", "sources-list"} { + if err := fileutils.CopyFileCrossFS(nilDryRun{}, fs, filepath.Join(staging, name), + fs, filepath.Join(trusted, name), fileutils.CopyFileOptions{NoFollow: true}); err != nil { + return Artifact{}, fmt.Errorf("collecting Go vendor output %#q:\n%w", name, err) + } + } + + if err := validateInputs(fs, trusted, request.SourceDir); err != nil { return Artifact{}, err } - return readArtifact(fs, staging, request) + return readArtifact(fs, trusted, request) +} + +type nilDryRun struct{} + +func (nilDryRun) DryRun() bool { return false } + +func resolveModuleDir(request Request) (Request, error) { + var settings map[string]any + if err := toml.Unmarshal([]byte(request.ConfigContents), &settings); err != nil { + return request, fmt.Errorf("parsing Go vendor tool configuration:\n%w", err) + } + + general, _ := settings["general"].(map[string]any) + if raw, exists := general["go_mod_dir"]; exists { + directory, ok := raw.(string) + if !ok { + return request, errors.New("go vendor 'general.go_mod_dir' must be a string") + } + + request.configModuleDir = directory + } + + for _, directory := range []string{request.ModuleDir, request.configModuleDir} { + if directory == "" || directory == "." { + continue + } + + if err := fileutils.ValidateRelPath(directory); err != nil { + return request, fmt.Errorf("invalid Go vendor module directory:\n%w", err) + } + + if strings.ContainsAny(directory, "%\r\n") { + return request, errors.New("go vendor module directory must not contain RPM macros or newlines") + } + } + + if request.configModuleDir != "" { + if request.ModuleDir != "" && request.ModuleDir != request.configModuleDir { + return request, errors.New("'module-dir' conflicts with upstream 'general.go_mod_dir'; " + + "use 'config-file' to replace the upstream settings") + } + + // Native tools preserve this subdirectory in the archive and use it for + // licensing. Keep their root and config intact, without descending twice. + request.ModuleDir = "" + } + + return request, nil } func stage(fs opctx.FS, request Request, sourceCopy, staging string) error { @@ -169,10 +238,13 @@ func generationCommand(request Request, targetArch string) []string { `IFS= read -r module_root < ` + topDir + "/azldev-go-module-root", `cd "$module_root"`, "cd " + quote(cmp.Or(request.ModuleDir, ".")), - "test -f go.mod", + quote("test", "-f", filepath.Join(request.configModuleDir, "go.mod")), + `module_root=$(pwd -P)`, "export GOTOOLCHAIN=local", + "cd " + sourceMount, quote("go_vendor_archive", "create", "--config", outputMount+"/"+ConfigFilename, - "--output", outputMount+"/"+request.ArchiveFile, "."), + "--output", outputMount+"/"+request.ArchiveFile) + ` "$module_root"`, + `cd "$module_root"`, quote("tar", "-xf", outputMount+"/"+request.ArchiveFile), quote(licenseArgs...) + " > " + outputMount + "/license", "cd " + sourceMount, diff --git a/internal/govendor/generate_internal_test.go b/internal/govendor/generate_internal_test.go index 68df88413..1d3f7b49e 100644 --- a/internal/govendor/generate_internal_test.go +++ b/internal/govendor/generate_internal_test.go @@ -4,6 +4,7 @@ package govendor import ( + "os" "os/exec" "path/filepath" "strings" @@ -54,6 +55,8 @@ func TestGenerateArtifact(t *testing.T) { } require.NoError(t, err) + assert.Equal(t, "/scratch/artifacts/vendor.tar.bz2", artifact.Path, + "published artifacts must come from the host-only snapshot") assert.Equal(t, "app-vendor.tar.bz2", artifact.Name) assert.Equal(t, "MIT", artifact.License) digest, err := fileutils.ComputeFileHash(ctx.FS(), fileutils.HashTypeSHA512, artifact.Path) @@ -78,6 +81,9 @@ func TestGenerationCommand(t *testing.T) { assert.Less(t, strings.Index(script, "rpmbuild"), strings.Index(script, "go_vendor_archive")) assert.Less(t, strings.Index(script, "go_vendor_archive"), strings.Index(script, "go_vendor_license")) assert.Contains(t, script, "cd cmd/app") + assert.Contains(t, script, + "cd "+sourceMount+"\ngo_vendor_archive create --config "+outputMount+"/"+ConfigFilename+ + " --output "+outputMount+`/app-vendor.tar.bz2 "$module_root"`+"\n"+`cd "$module_root"`) assert.Contains(t, script, "--target aarch64") assert.Contains(t, script, "--no-prompt") assert.Contains(t, script, "--autofill off") @@ -86,3 +92,120 @@ func TestGenerationCommand(t *testing.T) { assert.Equal(t, expected != "", strings.Contains(script, "--verify")) } } + +func TestResolveModuleDir(t *testing.T) { + for _, testCase := range []struct { + name, config, module, want string + wantErr bool + }{ + {name: "default"}, + {name: "upstream", config: "[general]\ngo_mod_dir = 'cmd/app'\n[archive]\ntidy = false"}, + {name: "matching", config: "[general]\ngo_mod_dir = 'cmd/app'", module: "cmd/app"}, + {name: "conflicting", config: "[general]\ngo_mod_dir = 'upstream'", module: "cmd/app", wantErr: true}, + {name: "explicit", module: "cmd/app", want: "cmd/app"}, + {name: "root", config: "[general]\ngo_mod_dir = '.'"}, + {name: "absolute", config: "[general]\ngo_mod_dir = '/etc'", wantErr: true}, + {name: "traversal", config: "[general]\ngo_mod_dir = '../outside'", wantErr: true}, + {name: "macro", config: "[general]\ngo_mod_dir = '%{bad}'", wantErr: true}, + {name: "type", config: "[general]\ngo_mod_dir = 42", wantErr: true}, + {name: "toml", config: "[broken", wantErr: true}, + } { + t.Run(testCase.name, func(t *testing.T) { + original := Request{ModuleDir: testCase.module, ConfigContents: testCase.config} + + actual, err := resolveModuleDir(original) + if testCase.wantErr { + require.Error(t, err) + + return + } + + require.NoError(t, err) + assert.Equal(t, testCase.want, actual.ModuleDir) + assert.Equal(t, testCase.config, actual.ConfigContents) + assert.Equal(t, testCase.config, original.ConfigContents) + }) + } +} + +// Kernel-enforced O_NOFOLLOW cannot be exercised by the in-memory filesystem. +func TestGenerateRejectsSymlinkOutputs(t *testing.T) { + for _, name := range []string{"vendor.tar.bz2", "archive-name", "license", "sources-list"} { + t.Run(name, func(t *testing.T) { + ctx := testctx.NewCtx(testctx.WithHostFS()) + ctx.CmdFactory.RegisterCommandInSearchPath(mock.MockBinary) + + root := t.TempDir() + request := Request{ + SourceDir: filepath.Join(root, "input"), WorkDir: filepath.Join(root, "scratch"), SpecName: "app.spec", + ArchiveFile: "vendor.tar.bz2", ArchiveSuffix: ".tar.bz2", PrepSpec: []byte("prepared"), + } + require.NoError(t, fileutils.MkdirAll(ctx.FS(), request.SourceDir)) + require.NoError(t, fileutils.WriteFile(ctx.FS(), filepath.Join(request.SourceDir, "app.spec"), + []byte("original"), fileperms.PublicFile)) + target := filepath.Join(root, "host-only") + require.NoError(t, fileutils.WriteFile(ctx.FS(), target, []byte("host-only contents"), fileperms.PublicFile)) + ctx.CmdFactory.RunAndGetOutputHandler = func(_ *exec.Cmd) (string, error) { + for filename, content := range map[string]string{ + request.ArchiveFile: "archive", "archive-name": "app-vendor.tar.bz2\n", + "license": "MIT\n", "sources-list": "Source0: app.spec\n", + } { + path := filepath.Join(request.WorkDir, "work", filename) + if filename == name { + require.NoError(t, os.Symlink(target, path)) + } else { + require.NoError(t, fileutils.WriteFile(ctx.FS(), path, []byte(content), fileperms.PublicFile)) + } + } + + return "", nil + } + artifact, err := Generate(ctx, ctx.FS(), mock.NewRunner(ctx, "/mock.cfg"), request) + require.ErrorContains(t, err, "without following symlinks") + assert.Empty(t, artifact.Path) + }) + } +} + +func TestCollectOutputRejectsNonRegularFile(t *testing.T) { + ctx := testctx.NewCtx() + require.NoError(t, fileutils.MkdirAll(ctx.FS(), "/input/directory")) + err := fileutils.CopyFile(ctx, ctx.FS(), "/input/directory", "/output/file", + fileutils.CopyFileOptions{NoFollow: true}) + require.ErrorContains(t, err, "not a regular file") +} + +func TestGenerateUsesUpstreamModuleWithoutChangingInputs(t *testing.T) { + ctx := testctx.NewCtx() + ctx.CmdFactory.RegisterCommandInSearchPath(mock.MockBinary) + require.NoError(t, fileutils.WriteFile(ctx.FS(), "/input/app.spec", []byte("original"), fileperms.PublicFile)) + + settings := "[general]\ngo_mod_dir = 'cmd/app'\n" + ctx.CmdFactory.RunAndGetOutputHandler = func(command *exec.Cmd) (string, error) { + script := strings.Join(command.Args, " ") + assert.Contains(t, script, "test -f cmd/app/go.mod") + assert.NotContains(t, script, "cd cmd/app") + + config, err := fileutils.ReadFile(ctx.FS(), "/scratch/work/"+ConfigFilename) + require.NoError(t, err) + assert.Equal(t, settings, string(config)) + + for name, content := range map[string]string{ + "vendor.tar.bz2": "archive", "archive-name": "app-vendor.tar.bz2\n", + "license": "MIT\n", "sources-list": "Source0: app.spec\n", + } { + require.NoError(t, fileutils.WriteFile(ctx.FS(), filepath.Join("/scratch/work", name), + []byte(content), fileperms.PublicFile)) + } + + return "", nil + } + request := Request{ + SourceDir: "/input", WorkDir: "/scratch", SpecName: "app.spec", + ArchiveFile: "vendor.tar.bz2", ConfigContents: settings, + } + _, err := Generate(ctx, ctx.FS(), mock.NewRunner(ctx, "/mock.cfg"), request) + require.NoError(t, err) + assert.Equal(t, settings, request.ConfigContents) + assert.Empty(t, request.ModuleDir) +} diff --git a/internal/rpm/spec/govendor.go b/internal/rpm/spec/govendor.go index 492faec23..2422df37e 100644 --- a/internal/rpm/spec/govendor.go +++ b/internal/rpm/spec/govendor.go @@ -29,6 +29,7 @@ type GoVendorSpec struct { ArchiveFile string // Filename used inside generation staging. ArchiveSuffix string // Required suffix of the RPM-expanded destination name, if any. ConfigName string + ArchiveSource string // Existing Source tag to pin to the generated filename. ExpectedLicense string // Empty: detect and update. Otherwise: verify and preserve. AllowReplacement bool // Permit replacing the existing vendor payload and configuration. } @@ -73,7 +74,7 @@ func ConvertGoVendor(data []byte, options GoVendorOptions) (*GoVendorSpec, error return nil, err } - if err := convertGoVendorLines(tree); err != nil { + if err := convertGoVendorLines(tree, options.ModuleDir); err != nil { return nil, err } @@ -189,20 +190,24 @@ func goVendorPrepSpec(tree *specTree, archiveValue string) []byte { return result } -// FinalizeLicense preserves a verified upstream expression or writes the detected -// expression for a newly converted spec. It does not mutate the plan. -func (p *GoVendorSpec) FinalizeLicense(expression string) ([]byte, error) { - if p.ExpectedLicense != "" { - return p.Spec, nil - } - +// Finalize pins an existing archive reference before release/history processing, +// and updates the license only for newly converted specs. It does not mutate the plan. +func (p *GoVendorSpec) Finalize(archiveName, expression string) ([]byte, error) { editor, err := openStructuralSpec(strings.NewReader(string(p.Spec))) if err != nil { return nil, err } - if err := editor.UpdateExistingTag("", "License", expression); err != nil { - return nil, err + if p.ArchiveSource != "" { + if err := editor.UpdateExistingTag("", p.ArchiveSource, archiveName); err != nil { + return nil, err + } + } + + if p.ExpectedLicense == "" { + if err := editor.UpdateExistingTag("", "License", expression); err != nil { + return nil, err + } } return []byte(strings.Join(editor.rawLines, "\n") + "\n"), nil @@ -298,7 +303,7 @@ func validateGoVendorBlock(blk *block) error { return nil } -func convertGoVendorLines(tree *specTree) error { +func convertGoVendorLines(tree *specTree, moduleDir string) error { return tree.VisitAllLines(func(section, _ string, line *lineHandle) error { text := strings.TrimSpace(line.Text) if strings.HasPrefix(text, "#") { @@ -326,7 +331,7 @@ func convertGoVendorLines(tree *specTree) error { return fmt.Errorf("unsupported Go check command %#q; use a module-aware check overlay", text) } - line.Replace("%gotest ./...") + line.Replace(goVendorInModule(moduleDir, "%gotest ./...")) } return nil diff --git a/internal/rpm/spec/govendor_existing.go b/internal/rpm/spec/govendor_existing.go index b7a237c0a..3013eacb7 100644 --- a/internal/rpm/spec/govendor_existing.go +++ b/internal/rpm/spec/govendor_existing.go @@ -18,6 +18,8 @@ var ( existingVendorLicense = regexp.MustCompile( `^%go_vendor_license_(?:buildrequires|install|check)\s+-c\s+%\{(?:S:|SOURCE)([0-9]+)\}\s*$`) existingVendorExtract = regexp.MustCompile(`^tar\s+-xf\s+%\{(?:S:|SOURCE)([0-9]+)\}\s*$`) + existingVendorSetup = regexp.MustCompile(`%(?:\{[!?]*)?(?:(?:auto)?setup|goprep)\b.*\s-[a-zA-Z]*[ab]`) + existingVendorChdir = regexp.MustCompile(`^(?:cd|pushd|popd|%(?:auto)?setup|%goprep)\b`) ) func prepareExistingGoVendor(tree *specTree, configSource string) (*GoVendorSpec, error) { @@ -34,7 +36,7 @@ func prepareExistingGoVendor(tree *specTree, configSource string) (*GoVendorSpec return nil, fmt.Errorf("existing Go vendor config Source%s must name a plain file, got %#q", configSource, configName) } - extraction, sourceNumber, err := existingVendorExtraction(tree) + extraction, sourceNumber, err := takeExistingVendorExtraction(tree) if err != nil { return nil, err } @@ -65,6 +67,9 @@ func prepareExistingGoVendor(tree *specTree, configSource string) (*GoVendorSpec } } + // Regeneration already includes prep's module edits. Extract the resulting + // module files after those edits so the RPM build cannot apply them twice. + tree.Section("%prep", "").AppendLines([]string{extraction}) addGoVendorEnvironment(tree) finalSpec := serializeGoVendorTree(tree) @@ -79,7 +84,7 @@ func prepareExistingGoVendor(tree *specTree, configSource string) (*GoVendorSpec return &GoVendorSpec{ Spec: finalSpec, PrepSpec: goVendorPrepSpec(tree, archiveValue), ArchiveFile: "azldev-generated-vendor" + suffix, ArchiveSuffix: suffix, ConfigName: configName, - ExpectedLicense: license, AllowReplacement: true, + ArchiveSource: "Source" + sourceNumber, ExpectedLicense: license, AllowReplacement: true, }, nil } @@ -126,19 +131,34 @@ func existingVendorConfigSource(tree *specTree) (string, error) { return source, nil } -func existingVendorExtraction(tree *specTree) (line, source string, err error) { +func takeExistingVendorExtraction(tree *specTree) (line, source string, err error) { count := 0 err = tree.Section("%prep", "").VisitLines(func(candidate *lineHandle) error { - matches := existingVendorExtract.FindStringSubmatch(strings.TrimSpace(candidate.Text)) + text := strings.TrimSpace(candidate.Text) + if existingVendorSetup.MatchString(text) { + return errors.New("secondary-source extraction in '%setup' or '%autosetup' makes Go vendoring ambiguous") + } + + if count > 0 && existingVendorChdir.MatchString(text) { + return errors.New("directory changes after Go vendor extraction require an explicit prep overlay") + } + + matches := existingVendorExtract.FindStringSubmatch(text) + if strings.HasPrefix(text, "tar ") && strings.Contains(text, "%{S") && len(matches) == 0 { + return fmt.Errorf("unsupported secondary-source extraction %#q", text) + } + if len(matches) != 0 { if !slices.Contains(tree.Section("%prep", "").block.Children, candidate.block) { return errors.New("conditional Go vendor extraction requires an explicit preparation strategy") } count++ - line = strings.TrimSpace(candidate.Text) + line = text source = matches[1] + + candidate.Remove() } return nil diff --git a/internal/rpm/spec/govendor_existing_test.go b/internal/rpm/spec/govendor_existing_test.go index 3b1927f95..280c9b4c0 100644 --- a/internal/rpm/spec/govendor_existing_test.go +++ b/internal/rpm/spec/govendor_existing_test.go @@ -61,8 +61,13 @@ func TestExistingGoVendoringPreservesPackaging(t *testing.T) { func TestExistingGoVendoringRejectsAmbiguousInputs(t *testing.T) { for name, input := range map[string]string{ - "multiple extractions": strings.ReplaceAll(existingVendorSpec(), "%goprep -p1", "%goprep -p1\ntar -xf %{S:9}"), - "no extraction": strings.ReplaceAll(existingVendorSpec(), "tar -xf %{S:5}", ""), + "multiple extractions": strings.ReplaceAll(existingVendorSpec(), "%goprep -p1", "%goprep -p1\ntar -xf %{S:9}"), + "autosetup secondary": strings.ReplaceAll(existingVendorSpec(), "%goprep -p1", "%autosetup -a 1"), + "setup secondary": strings.ReplaceAll(existingVendorSpec(), "%goprep -p1", "%setup -qb1"), + "braced autosetup secondary": strings.ReplaceAll(existingVendorSpec(), "%goprep -p1", "%{autosetup -a 1}"), + "other tar flags": strings.ReplaceAll(existingVendorSpec(), "%goprep -p1", "%goprep -p1\ntar -xjf %{S:9}"), + "directory after extraction": strings.ReplaceAll(existingVendorSpec(), "sed -i 's/old/new/' go.mod", "cd submodule"), + "no extraction": strings.ReplaceAll(existingVendorSpec(), "tar -xf %{S:5}", ""), "mismatched config": strings.ReplaceAll(existingVendorSpec(), "%go_vendor_license_check -c %{S:8}", "%go_vendor_license_check -c %{S:9}"), "dynamic config": strings.ReplaceAll(existingVendorSpec(), "go-vendor-tools.toml", "%{name}.toml"), @@ -85,3 +90,40 @@ func TestExistingGoVendoringRejectsAmbiguousInputs(t *testing.T) { }) } } + +func TestExistingGoVendorExtractsAfterModulePatches(t *testing.T) { + input := strings.ReplaceAll(existingVendorSpec(), "%goprep -p1", "%setup -q") + input = strings.ReplaceAll(input, "sed -i 's/old/new/' go.mod", "%autopatch -p1\nsed -i 's/old/new/' go.mod") + result, err := spec.ConvertGoVendor([]byte(input), spec.GoVendorOptions{ + ArchiveName: "app-vendor.tar.bz2", ConfigName: "vendor.toml", + }) + require.NoError(t, err) + + output := string(result.Spec) + assert.Less(t, strings.Index(output, "%autopatch -p1"), strings.Index(output, "tar -xf %{S:5}")) + assert.Less(t, strings.Index(output, "sed -i"), strings.Index(output, "tar -xf %{S:5}")) + assert.Less(t, strings.Index(output, "cp %{S:9} ."), strings.Index(output, "tar -xf %{S:5}")) + assert.Contains(t, string(result.PrepSpec), "%autopatch -p1") + assert.NotContains(t, string(result.PrepSpec), "tar -xf %{S:5}") +} + +func TestExistingGoVendorPinsExpandedArchiveBeforeReleaseChanges(t *testing.T) { + input := strings.ReplaceAll(existingVendorSpec(), "app-%{version}-vendor", "app-%{version}-%{release}-vendor") + result, err := spec.ConvertGoVendor([]byte(input), spec.GoVendorOptions{ + ArchiveName: "app-vendor.tar.bz2", ConfigName: "vendor.toml", + }) + require.NoError(t, err) + final, err := result.Finalize("app-1.2-7-vendor.tar.bz2", "MIT AND Apache-2.0") + require.NoError(t, err) + assert.Contains(t, string(final), "Source5: app-1.2-7-vendor.tar.bz2") + assert.NotContains(t, string(final), "app-%{version}-%{release}-vendor") + assert.Contains(t, string(result.Spec), "Source5: app-%{version}-%{release}-vendor.tar.bz2", + "finalization must not mutate the plan") + editor, err := spec.OpenSpec(strings.NewReader(string(final)), spec.WithEditor(spec.EditorStructural)) + require.NoError(t, err) + require.NoError(t, editor.UpdateExistingTag("", "Release", "8")) + + var output strings.Builder + require.NoError(t, editor.Serialize(&output)) + assert.Contains(t, output.String(), "Source5: app-1.2-7-vendor.tar.bz2") +} diff --git a/internal/rpm/spec/govendor_test.go b/internal/rpm/spec/govendor_test.go index c366de034..a29a44a3f 100644 --- a/internal/rpm/spec/govendor_test.go +++ b/internal/rpm/spec/govendor_test.go @@ -78,7 +78,8 @@ func TestConvertGoVendorPreservesUpstream(t *testing.T) { "%package tools", "Requires: app = %{version}-%{release}", "%goprep -p1", "sed -i 's/old/new/' go.mod", "echo custom-build-dependency", "%gobuild -o app %{goipath}", "install -D app %{buildroot}%{_bindir}/app", - "%if %{with check}\n%gotest ./...\n./custom-test\n%endif", + "%if %{with check}\n" + + `( cd "$(cat "%{_topdir}/azldev-go-module-root")"` + "\n%gotest ./...\n)\n./custom-test\n%endif", "%files tools\n%{_bindir}/tool", "%autochangelog", "Source2: app-vendor.tar.bz2", "Source3: vendor.toml", "tar -xf %{SOURCE2}", "%go_vendor_license_buildrequires -c %{SOURCE3}", @@ -153,6 +154,8 @@ func TestConvertGoVendorModuleDirAndStaticRequires(t *testing.T) { require.NoError(t, err) assert.Contains(t, string(result.Spec), "tar -xf %{SOURCE2} -C cmd/app") assert.Contains(t, string(result.Spec), "cd cmd/app\n%go_vendor_license_install") + assert.Contains(t, string(result.Spec), + `( cd "$(cat "%{_topdir}/azldev-go-module-root")"`+"\ncd cmd/app\n%gotest ./...\n)") assert.Contains(t, string(result.Spec), `( cd "$(cat "%{_topdir}/azldev-go-module-root")"`) assert.Contains(t, string(result.Spec), "%generate_buildrequires\n") } diff --git a/internal/utils/fileutils/copy.go b/internal/utils/fileutils/copy.go index 790822976..d0002e7c0 100644 --- a/internal/utils/fileutils/copy.go +++ b/internal/utils/fileutils/copy.go @@ -18,11 +18,14 @@ import ( type CopyFileOptions struct { // Whether or not to preserve POSIX mode bits on files. Does *not* apply to directories. PreserveFileMode bool + // NoFollow requires a regular source file and rejects final-component symlinks. + NoFollow bool } // Copies the contents of an existing file to a new file at the given destination path. // May preserve mode bits if "options" says so but does *not* preserve ownership, timestamps, -// or other metadata. *Does* follow symlinks. Is enlightened to skip copying in dry-run mode. +// or other metadata. Follows source symlinks unless [CopyFileOptions.NoFollow] is set. +// Is enlightened to skip copying in dry-run mode. func CopyFile(dryRunnable opctx.DryRunnable, fs opctx.FS, sourcePath, destPath string, options CopyFileOptions) error { return CopyFileCrossFS(dryRunnable, fs, sourcePath, fs, destPath, options) } @@ -30,7 +33,8 @@ func CopyFile(dryRunnable opctx.DryRunnable, fs opctx.FS, sourcePath, destPath s // Copies the contents of an existing file to a new file at the given destination path, // potentially across two [opctx.FS] filesystem instances. May preserve mode bits if // "options" says so but does *not* preserve ownership, timestamps, or other metadata. -// *Does* follow symlinks. Is enlightened to skip copying in dry-run mode. +// Follows source symlinks unless [CopyFileOptions.NoFollow] is set. +// Is enlightened to skip copying in dry-run mode. func CopyFileCrossFS( dryRunnable opctx.DryRunnable, sourceFS opctx.FS, sourcePath string, @@ -67,7 +71,14 @@ func copyFileCrossFS( destFileMode = stat.Mode() } - sourceFile, err := sourceFS.Open(sourcePath) + var sourceFile opctx.File + + if options.NoFollow { + sourceFile, err = OpenRegularFileNoFollow(sourceFS, sourcePath) + } else { + sourceFile, err = sourceFS.Open(sourcePath) + } + if err != nil { err = fmt.Errorf("failed to open copy source '%s':\n%w", sourcePath, err) diff --git a/internal/utils/fileutils/file.go b/internal/utils/fileutils/file.go index 52fbcbd3e..50e9d5dd3 100644 --- a/internal/utils/fileutils/file.go +++ b/internal/utils/fileutils/file.go @@ -14,6 +14,7 @@ import ( "github.com/bmatcuk/doublestar/v4" "github.com/microsoft/azure-linux-dev-tools/internal/global/opctx" "github.com/spf13/afero" + "golang.org/x/sys/unix" ) // Adaptation of [os.WriteFile] that works with [opctx.FS]. @@ -28,6 +29,31 @@ func ReadFile(fs opctx.FS, filename string) ([]byte, error) { return afero.ReadFile(fs, filename) } +// OpenRegularFileNoFollow atomically rejects final-component symlinks and checks +// the opened descriptor rather than a path that could change before reading. +// The parent directory must be trusted. Nonblocking mode avoids opening a FIFO indefinitely. +func OpenRegularFileNoFollow(fs opctx.FS, filename string) (opctx.File, error) { + file, err := fs.OpenFile(filename, os.O_RDONLY|unix.O_NOFOLLOW|unix.O_NONBLOCK, 0) + if err != nil { + return nil, fmt.Errorf("opening regular file %#q without following symlinks:\n%w", filename, err) + } + + info, err := file.Stat() + if err != nil { + file.Close() + + return nil, fmt.Errorf("checking opened file %#q:\n%w", filename, err) + } + + if !info.Mode().IsRegular() { + file.Close() + + return nil, fmt.Errorf("%#q is not a regular file", filename) + } + + return file, nil +} + // Adaptation of [filepath.Glob] that works with [opctx.FS] and also uses the // [doublestar] package to supports standard double-star globs ('**'). func Glob(fs opctx.FS, pattern string, opts ...doublestar.GlobOption) ([]string, error) { diff --git a/internal/utils/fileutils/nofollow_test.go b/internal/utils/fileutils/nofollow_test.go new file mode 100644 index 000000000..9e87e3afc --- /dev/null +++ b/internal/utils/fileutils/nofollow_test.go @@ -0,0 +1,74 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package fileutils_test + +import ( + "io" + "os" + "path/filepath" + "testing" + + "github.com/microsoft/azure-linux-dev-tools/internal/global/opctx/opctx_test" + "github.com/microsoft/azure-linux-dev-tools/internal/global/testctx" + "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" + "golang.org/x/sys/unix" +) + +func TestOpenRegularFileNoFollow(t *testing.T) { + ctx := testctx.NewCtx() + require.NoError(t, fileutils.WriteFile(ctx.FS(), "/regular", []byte("contents"), fileperms.PublicFile)) + file, err := fileutils.OpenRegularFileNoFollow(ctx.FS(), "/regular") + require.NoError(t, err) + + defer file.Close() + + data, err := io.ReadAll(file) + require.NoError(t, err) + assert.Equal(t, "contents", string(data)) + + missing, err := fileutils.OpenRegularFileNoFollow(ctx.FS(), "/missing") + require.ErrorIs(t, err, os.ErrNotExist) + assert.Nil(t, missing) + require.NoError(t, fileutils.MkdirAll(ctx.FS(), "/directory")) + directory, err := fileutils.OpenRegularFileNoFollow(ctx.FS(), "/directory") + require.ErrorContains(t, err, "not a regular file") + assert.Nil(t, directory) +} + +func TestOpenRegularFileNoFollowFlagsAndStatErrors(t *testing.T) { + ctrl := gomock.NewController(t) + mockFS := opctx_test.NewMockFS(ctrl) + flags := os.O_RDONLY | unix.O_NOFOLLOW | unix.O_NONBLOCK + mockFS.EXPECT().OpenFile("/denied", flags, os.FileMode(0)).Return(nil, os.ErrPermission) + file, err := fileutils.OpenRegularFileNoFollow(mockFS, "/denied") + require.ErrorIs(t, err, os.ErrPermission) + assert.Nil(t, file) + + opened := opctx_test.NewMockFile(ctrl) + mockFS.EXPECT().OpenFile("/bad-stat", flags, os.FileMode(0)).Return(opened, nil) + opened.EXPECT().Stat().Return(nil, os.ErrPermission) + opened.EXPECT().Close().Return(nil) + + file, err = fileutils.OpenRegularFileNoFollow(mockFS, "/bad-stat") + require.ErrorIs(t, err, os.ErrPermission) + assert.Nil(t, file) +} + +// Kernel-enforced symlink rejection requires a real filesystem. +func TestCopyFileNoFollowRejectsSymlinks(t *testing.T) { + ctx := testctx.NewCtx(testctx.WithHostFS()) + root := t.TempDir() + target, link, output := filepath.Join(root, "target"), filepath.Join(root, "link"), filepath.Join(root, "output") + require.NoError(t, fileutils.WriteFile(ctx.FS(), target, []byte("host-only contents"), fileperms.PublicFile)) + require.NoError(t, os.Symlink(target, link)) + err := fileutils.CopyFile(ctx, ctx.FS(), link, output, fileutils.CopyFileOptions{NoFollow: true}) + require.ErrorContains(t, err, "without following symlinks") + exists, err := fileutils.Exists(ctx.FS(), output) + require.NoError(t, err) + assert.False(t, exists) +} From 3e512ffa63a22c3271e1c5d81c9480accf6ecc10 Mon Sep 17 00:00:00 2001 From: Antonio Salinas <173939267+Tonisal-byte@users.noreply.github.com> Date: Mon, 2 Nov 2026 13:26:29 -0800 Subject: [PATCH 05/16] test: refresh container schema snapshot for Go vendoring The Go vendor configuration intentionally extends the schema, but scenarioUpdate refreshed only the local baseline when Docker was unavailable. CI reached the container schema check and failed on the missing 37 lines. Update the container baseline to match the actual generated CLI schema and document that incomplete Docker runs can leave this second snapshot stale. Both stdout snapshots and the checked-in schema match the rebuilt CLI output byte-for-byte. Local scenario/scenarioUpdate runs remain blocked by the unavailable Docker provider. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/copilot-instructions.md | 3 ++ ...ainer_config_generate-schema_stdout_1.snap | 37 +++++++++++++++++++ 2 files changed, 40 insertions(+) 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/scenario/__snapshots__/TestSnapshotsContainer_config_generate-schema_stdout_1.snap b/scenario/__snapshots__/TestSnapshotsContainer_config_generate-schema_stdout_1.snap index 9cf47bd35..9259ce684 100755 --- a/scenario/__snapshots__/TestSnapshotsContainer_config_generate-schema_stdout_1.snap +++ b/scenario/__snapshots__/TestSnapshotsContainer_config_generate-schema_stdout_1.snap @@ -150,6 +150,11 @@ "title": "Source files", "description": "Source files to download for this component" }, + "go-vendor": { + "$ref": "#/$defs/GoVendorConfig", + "title": "Go vendoring", + "description": "Convert a Go application spec and generate its vendor archive during source preparation" + }, "packages": { "additionalProperties": { "$ref": "#/$defs/PackageConfig" @@ -682,6 +687,38 @@ "additionalProperties": false, "type": "object" }, + "GoVendorConfig": { + "properties": { + "enabled": { + "type": "boolean", + "title": "Enabled", + "description": "Enable Go application vendoring" + }, + "module-dir": { + "type": "string", + "title": "Module directory", + "description": "Relative module directory within the prepared source tree; defaults to its root" + }, + "config-file": { + "type": "string", + "title": "Vendor configuration file", + "description": "Path to a go-vendor-tools TOML file relative to the declaring component configuration. Replaces upstream settings when specified", + "examples": [ + "go-vendor-tools.toml" + ] + }, + "prep-packages": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Prep packages", + "description": "Additional RPM packages needed to execute the upstream prep section in mock" + } + }, + "additionalProperties": false, + "type": "object" + }, "ImageCapabilities": { "properties": { "machine-bootable": { From 485c179e86d5d4668a6bbd9cd16afe409926f71e Mon Sep 17 00:00:00 2001 From: Antonio Salinas <173939267+Tonisal-byte@users.noreply.github.com> Date: Mon, 2 Nov 2026 13:26:29 -0800 Subject: [PATCH 06/16] test: refresh container schema snapshot for Go vendoring The Go vendor configuration intentionally extends the schema, but scenarioUpdate refreshed only the local baseline when Docker was unavailable. CI reached the container schema check and failed on the missing 37 lines. Update the container baseline to match the actual generated CLI schema and document that incomplete Docker runs can leave this second snapshot stale. Both stdout snapshots and the checked-in schema match the rebuilt CLI output byte-for-byte. Local scenario/scenarioUpdate runs remain blocked by the unavailable Docker provider. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/copilot-instructions.md | 3 + docs/developer/README.md | 1 + .../reference/go-vendor-packaging-design.md | 96 +++++++++++++++++++ docs/user/how-to/vendor-go-application.md | 9 +- docs/user/reference/cli/azldev.md | 2 +- docs/user/reference/cli/azldev_advanced.md | 2 +- docs/user/reference/cli/azldev_completion.md | 2 +- docs/user/reference/cli/azldev_component.md | 2 +- docs/user/reference/cli/azldev_config.md | 2 +- docs/user/reference/cli/azldev_docs.md | 2 +- docs/user/reference/cli/azldev_image.md | 2 +- docs/user/reference/cli/azldev_package.md | 2 +- docs/user/reference/cli/azldev_project.md | 2 +- docs/user/reference/cli/azldev_repo.md | 2 +- docs/user/reference/cli/azldev_version.md | 2 +- docs/user/reference/config/components.md | 10 +- .../app/azldev/agentskill/agentskill_test.go | 2 + .../agentskill/content/comp-toml.md.tmpl | 3 +- .../content/withoutlockfile/comp-toml.md.tmpl | 3 +- internal/app/azldev/core/sources/govendor.go | 10 ++ .../sources/govendor_config_internal_test.go | 31 ++++++ .../core/sources/govendor_internal_test.go | 48 ++++++++-- .../app/azldev/core/sources/sourceprep.go | 38 +++++--- internal/projectconfig/component.go | 8 +- internal/projectconfig/govendor_test.go | 34 +++++++ internal/rpm/spec/govendor.go | 5 + internal/rpm/spec/govendor_existing_test.go | 8 ++ ...ainer_config_generate-schema_stdout_1.snap | 37 +++++++ 28 files changed, 327 insertions(+), 41 deletions(-) create mode 100644 docs/developer/reference/go-vendor-packaging-design.md 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/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..28645c989 --- /dev/null +++ b/docs/developer/reference/go-vendor-packaging-design.md @@ -0,0 +1,96 @@ +# Go vendor packaging: one-page design + +**Status:** Design comparison, not approval to replace the current implementation. +“Current” describes this branch, including pending review fixes. + +## Goal and requirements + +Bundle application dependencies while preserving package-specific RPM behavior. +`prepare-sources` must produce all build inputs, including the vendor archive; +builds must consume those inputs without downloading Go modules. Configuration +should survive version upgrades without embedding versioned filenames, Source +numbers, import paths, or spec line numbers. Preserve unrelated dependencies, +patches, subpackages, and reviewed licensing. Generate in an isolated environment, +fail on ambiguous layouts, and record/verify archive hashes. Changes to source, +patches, native vendor settings, or toolchain must be accounted for when assessing +reproducibility; a generated checksum alone does not guarantee reproducibility. + +## Use cases and current gaps + +| Use case | Current behavior and gap | +|---|---| +| Fedora, already vendored: **containerd** | Regenerates a recognized vendor Source after patched `%prep`; preserves native configuration and verifies licensing. Containerd was exercised end-to-end. Recognition requires specific extraction/license macros; changing module layout or replacing a lookaside-backed config is rejected. Dependency overrides/hooks can regenerate patched content; directly patching the old vendor archive is not sufficient because regeneration replaces it. | +| Fedora, not vendored: **Go applications**; requested example **rust-uutils** | Converts supported Go application specs to vendor extraction, offline module builds, and license handling. Complex macros/subpackages require overlays. **rust-uutils is Rust:** it needs Cargo vendoring, Cargo build integration, and Rust license handling; neither this Go implementation nor a Go tarball provider covers it. | +| Downstream-only: **Telegraf** (assuming “telgraf”) | Local specs can use the same Go conversion pipeline when their layout is supported. A downstream-owned spec could instead consume a stable vendor Source directly. This particular package has not been validated; local-source, patch-order, and offline-build coverage remains necessary. | + +## Current design and schema + +```toml +[components.containerd.go-vendor] +enabled = true +config-file = "go-vendor-tools.toml" # optional; omission reuses upstream settings +``` + +Additional fields are `module-dir` and `prep-packages`. Custom native settings +live in a separate declaration-relative file, replace rather than merge upstream +settings, and participate in fingerprints. + +The pipeline fetches sources, applies overlays, plans a narrowly scoped spec +adaptation, runs private `%prep`, and invokes `go-vendor-tools` for generation and +licensing. It publishes the archive, spec/config, and `sources` digest. +`internal/govendor` separates execution from spec planning, but still requires a +prepared RPM spec. Render/diff also regenerate, so they require downloads. +Generated files cannot also be declared in `source-files`. + +## Alternative: automatic tarball through `source-files` + +**Proposed syntax and defaults only; this origin is not implemented:** + +```toml +[[components.containerd.source-files]] +hash-type = "SHA512" +# filename = "vendor.tar.bz2" # optional override of automatic discovery +# hash = "" # optional output verification +origin.type = "go-vendor" +origin.config-file = "go-vendor-tools.toml" +``` + +Filename discovery is default behavior, not a separate field: resolve the unique +vendor Source from the effective spec and expand RPM macros. An explicit +`filename` overrides discovery; require it when no unique target can be resolved. +New/downstream specs can reference a stable `vendor.tar.bz2`. Regeneration owns +the discovered vendor output; an explicit filename that replaces another existing +source remains subject to existing collision/replacement safeguards. Native +settings stay in the sidecar; origin options reuse `module-dir`/`prep-packages`. + +For this generated origin, `hash` is optional: azldev computes the archive digest +and records it in `sources`. A supplied hash must match; omission records output +identity but does not detect unexpected changes between regenerations. This is an +intentional exception to current `source-files` preparation, which generally +requires hashes unless bootstrapping with `--allow-no-hashes`. + +This needs more than a new provider switch: `FetchFiles` currently runs **before** +overlays. Defer vendor generation until patched inputs are prepared, excluding +its own output from fetching/prep to break the dependency cycle. Reuse the narrow +temporary-prep planner for recognized specs; reject unsupported extraction rather +than invent a general shell interpreter. Generate from patched module files, +apply vendor-specific changes through generation hooks, validate licensing and +regular-file outputs, then publish the final digest. Never silently refresh a +configured expected hash. Extend origin validation, schema, +fingerprints, deferred scheduling, and replacement/render handling together. + +## Trade-offs and recommendation + +| Current combined feature | Tarball-only alternative | +|---|---| +| Low-effort opt-in for supported Go specs. | Smaller spec-mutation surface, reusable source artifact. | +| azldev maintains conversion and licensing rules. | Maintainers own extraction, dependency removal, offline flags, bundled-license installation, and spec updates through overlays/local specs. | +| Handles generation and consumption together. | Tarball existence does **not** prove the RPM consumes it; offline-build and licensing checks remain required. | + +**Recommendation:** retain the current bounded converter for now. If artifact-only +generation is prioritized, reuse its backend behind a deferred `go-vendor` origin, +with spec conversion remaining an optional adapter; reject simultaneous ownership +of one archive by both configurations. Validate containerd regeneration, a genuinely +unbundled Go application, and a downstream local package before migration. Treat +Cargo support as separate work. This reduces azldev's responsibilities only by +moving packaging work to maintainers, not by eliminating it. diff --git a/docs/user/how-to/vendor-go-application.md b/docs/user/how-to/vendor-go-application.md index 4cb103c32..9f9387c83 100644 --- a/docs/user/how-to/vendor-go-application.md +++ b/docs/user/how-to/vendor-go-application.md @@ -56,6 +56,8 @@ neither `go2rpm` nor the Go vendor tools are required on the host. Configure The pipeline fetches the selected upstream sources, applies overlays, and copies them into isolated staging. It processes automatic release/changelog metadata there and runs the existing `%prep` section with `rpmbuild -bp --nodeps`. +Upstream Git history remains available for this processing even with +`--without-git`; it is removed from the final output when that option is used. This retains upstream patches and edits to module files. It then calls `go_vendor_archive create` on the prepared module tree, extracts the result for license detection, and runs `go_vendor_license` without interactive prompts. @@ -123,8 +125,11 @@ even when empty; missing files or invalid TOML fail without falling back. The detected licenses are verified against the existing main-package `License:` expression; mismatches fail instead of rewriting it. Upstream `general.go_mod_dir` is honored by generation and licensing, preserving -the module subdirectory within the archive. A conflicting `module-dir` fails; -use a separate `config-file` to replace upstream settings when changing the layout. +the module subdirectory within the archive. Non-root `module-dir` overrides are +rejected for already-vendored specs; their extraction and licensing retain the +upstream layout. +Replacing a configuration listed in upstream `sources` is also rejected before +generation; custom configurations must replace a tracked sidecar instead. Neither the regenerated archive nor its configuration sidecar may also be declared in `source-files`, even with `replace-upstream = true`. The source-fetch phase currently still downloads the upstream vendor archive diff --git a/docs/user/reference/cli/azldev.md b/docs/user/reference/cli/azldev.md index c5de33703..c896e7c3c 100644 --- a/docs/user/reference/cli/azldev.md +++ b/docs/user/reference/cli/azldev.md @@ -2,7 +2,7 @@ ## azldev -🐧 Azure Linux Dev Tool +🐧 Azure Linux Dev Tool 0.0.0-devel ### Synopsis diff --git a/docs/user/reference/cli/azldev_advanced.md b/docs/user/reference/cli/azldev_advanced.md index f76116d52..28a397d69 100644 --- a/docs/user/reference/cli/azldev_advanced.md +++ b/docs/user/reference/cli/azldev_advanced.md @@ -38,7 +38,7 @@ output but fully supported. ### SEE ALSO -* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool +* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool 0.0.0-devel * [azldev advanced download-sources](azldev_advanced_download-sources.md) - Download source files listed in a Fedora-format sources file * [azldev advanced mcp](azldev_advanced_mcp.md) - Run in MCP server mode * [azldev advanced mock](azldev_advanced_mock.md) - Run RPM mock tool diff --git a/docs/user/reference/cli/azldev_completion.md b/docs/user/reference/cli/azldev_completion.md index 109d7858e..6b375b33b 100644 --- a/docs/user/reference/cli/azldev_completion.md +++ b/docs/user/reference/cli/azldev_completion.md @@ -36,7 +36,7 @@ See each sub-command's help for details on how to use the generated script. ### SEE ALSO -* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool +* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool 0.0.0-devel * [azldev completion bash](azldev_completion_bash.md) - Generate the autocompletion script for bash * [azldev completion fish](azldev_completion_fish.md) - Generate the autocompletion script for fish * [azldev completion powershell](azldev_completion_powershell.md) - Generate the autocompletion script for powershell diff --git a/docs/user/reference/cli/azldev_component.md b/docs/user/reference/cli/azldev_component.md index df0e9622b..f0cd76071 100644 --- a/docs/user/reference/cli/azldev_component.md +++ b/docs/user/reference/cli/azldev_component.md @@ -40,7 +40,7 @@ components defined in the project configuration. ### SEE ALSO -* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool +* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool 0.0.0-devel * [azldev component add](azldev_component_add.md) - Add component(s) to this project * [azldev component build](azldev_component_build.md) - Build packages for components * [azldev component changed](azldev_component_changed.md) - Detect which components changed between two git refs diff --git a/docs/user/reference/cli/azldev_config.md b/docs/user/reference/cli/azldev_config.md index 6eed54b63..5fa5ec450 100644 --- a/docs/user/reference/cli/azldev_config.md +++ b/docs/user/reference/cli/azldev_config.md @@ -37,7 +37,7 @@ JSON schema used for validating TOML config files. ### SEE ALSO -* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool +* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool 0.0.0-devel * [azldev config dump](azldev_config_dump.md) - Dump the current configuration * [azldev config generate-schema](azldev_config_generate-schema.md) - Generates JSON schema for validating .toml config files diff --git a/docs/user/reference/cli/azldev_docs.md b/docs/user/reference/cli/azldev_docs.md index 787033cbb..5351b11a0 100644 --- a/docs/user/reference/cli/azldev_docs.md +++ b/docs/user/reference/cli/azldev_docs.md @@ -37,7 +37,7 @@ command tree, suitable for inclusion in the user guide. ### SEE ALSO -* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool +* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool 0.0.0-devel * [azldev docs agent](azldev_docs_agent.md) - Emit AI agent skill and instruction files * [azldev docs markdown](azldev_docs_markdown.md) - Generates Markdown (.md) docs for this tool diff --git a/docs/user/reference/cli/azldev_image.md b/docs/user/reference/cli/azldev_image.md index ea678cf94..725d10144 100644 --- a/docs/user/reference/cli/azldev_image.md +++ b/docs/user/reference/cli/azldev_image.md @@ -38,7 +38,7 @@ can be customized using Azure Linux Image Customizer. ### SEE ALSO -* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool +* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool 0.0.0-devel * [azldev image boot](azldev_image_boot.md) - Boot an Azure Linux image in a QEMU VM * [azldev image build](azldev_image_build.md) - Build an image using kiwi-ng * [azldev image customize](azldev_image_customize.md) - Customizes a pre-built Azure Linux image diff --git a/docs/user/reference/cli/azldev_package.md b/docs/user/reference/cli/azldev_package.md index 678421bcc..a4e882e35 100644 --- a/docs/user/reference/cli/azldev_package.md +++ b/docs/user/reference/cli/azldev_package.md @@ -38,6 +38,6 @@ publish channel assignments derived from package groups and component overrides. ### SEE ALSO -* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool +* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool 0.0.0-devel * [azldev package list](azldev_package_list.md) - List resolved configuration for packages (RPMs and SRPMs) diff --git a/docs/user/reference/cli/azldev_project.md b/docs/user/reference/cli/azldev_project.md index fef53ace7..d9c40b6c7 100644 --- a/docs/user/reference/cli/azldev_project.md +++ b/docs/user/reference/cli/azldev_project.md @@ -37,7 +37,7 @@ as an Azure Linux project with a basic configuration. ### SEE ALSO -* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool +* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool 0.0.0-devel * [azldev project init](azldev_project_init.md) - Initialize the current working directory with a basic Azure Linux project config * [azldev project new](azldev_project_new.md) - Create a new Azure Linux project with basic config diff --git a/docs/user/reference/cli/azldev_repo.md b/docs/user/reference/cli/azldev_repo.md index ccbc3f5ee..024cbdae6 100644 --- a/docs/user/reference/cli/azldev_repo.md +++ b/docs/user/reference/cli/azldev_repo.md @@ -38,7 +38,7 @@ under one or more URL prefixes. ### SEE ALSO -* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool +* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool 0.0.0-devel * [azldev repo compare](azldev_repo_compare.md) - Compare package inventories in two RPM repo sets * [azldev repo query](azldev_repo_query.md) - Run dnf against auto-discovered RPM repos diff --git a/docs/user/reference/cli/azldev_version.md b/docs/user/reference/cli/azldev_version.md index 5ebddbcdd..a59c7968e 100644 --- a/docs/user/reference/cli/azldev_version.md +++ b/docs/user/reference/cli/azldev_version.md @@ -42,5 +42,5 @@ azldev version -O json ### SEE ALSO -* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool +* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool 0.0.0-devel diff --git a/docs/user/reference/config/components.md b/docs/user/reference/config/components.md index f483f671f..a30019ea2 100644 --- a/docs/user/reference/config/components.md +++ b/docs/user/reference/config/components.md @@ -205,9 +205,10 @@ config-file = "go-vendor-tools.toml" The configured file must exist and contain valid TOML. An explicitly selected empty file is an empty replacement, not a request to fall back to upstream. -In an explicitly selected file, use `module-dir`, not `general.go_mod_dir`, for -the module location. Reused upstream `general.go_mod_dir` settings remain honored; -an inconsistent component `module-dir` is rejected. +For a new conversion, set the module location with component `module-dir`, not +`general.go_mod_dir` in the selected file. Already-vendored specs retain the +upstream module layout, honoring native `general.go_mod_dir`; non-root +`module-dir` overrides are rejected. Configured command hooks execute in the generation chroot; treat this file as trusted build code. The old inline `tool-config` string/table is no longer supported. @@ -229,7 +230,8 @@ verifies the existing `License:` expression without rewriting it. These generated archive/config filenames must not also appear in `source-files`, including entries with `replace-upstream = true`. When `config-file` is set, its contents are staged under the configuration filename -referenced by the prepared spec, retaining the existing Source number. +referenced by the prepared spec, retaining the existing Source number. Replacing +a configuration listed in upstream `sources` is unsupported and fails before generation. All archive/spec/loose-file overlays run before conversion. Source preparation, builds, rendering (including `--check-only`), and source diffs use the same diff --git a/internal/app/azldev/agentskill/agentskill_test.go b/internal/app/azldev/agentskill/agentskill_test.go index 5805e5282..ac0f49949 100644 --- a/internal/app/azldev/agentskill/agentskill_test.go +++ b/internal/app/azldev/agentskill/agentskill_test.go @@ -171,6 +171,8 @@ func TestComponentTomlSkillDocumentsGoVendoring(t *testing.T) { assert.Contains(t, doc, `config-file = "go-vendor-tools.toml"`) assert.Contains(t, doc, "Inline `tool-config` is not supported.") assert.Contains(t, doc, "Upstream `general.go_mod_dir` is honored") + assert.Contains(t, doc, "non-root `module-dir` overrides fail") + assert.Contains(t, doc, "Replacing a config listed in upstream `sources` is unsupported.") assert.Contains(t, doc, "Source filename is pinned before") } } diff --git a/internal/app/azldev/agentskill/content/comp-toml.md.tmpl b/internal/app/azldev/agentskill/content/comp-toml.md.tmpl index 7059b2ae3..d6a1de295 100644 --- a/internal/app/azldev/agentskill/content/comp-toml.md.tmpl +++ b/internal/app/azldev/agentskill/content/comp-toml.md.tmpl @@ -54,7 +54,8 @@ declared as `source-files`. For supported already-vendored specs, regenerate the existing vendor Source instead, reuse upstream tool configuration unless overridden, and verify rather than replace the reviewed `License:` expression. The regenerated archive and configuration must not also be `source-files` entries. -Upstream `general.go_mod_dir` is honored; conflicting `module-dir` values fail. +Upstream `general.go_mod_dir` is honored; non-root `module-dir` overrides fail +for already-vendored specs. Replacing a config listed in upstream `sources` is unsupported. Vendor extraction runs after prep edits, and its Source filename is pinned before release/history updates. Ambiguous secondary-source setup requires an overlay. Unsupported constructs (notably automatic Go devel 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 2ac8df159..7a884e086 100644 --- a/internal/app/azldev/agentskill/content/withoutlockfile/comp-toml.md.tmpl +++ b/internal/app/azldev/agentskill/content/withoutlockfile/comp-toml.md.tmpl @@ -54,7 +54,8 @@ declared as `source-files`. For supported already-vendored specs, regenerate the existing vendor Source instead, reuse upstream tool configuration unless overridden, and verify rather than replace the reviewed `License:` expression. The regenerated archive and configuration must not also be `source-files` entries. -Upstream `general.go_mod_dir` is honored; conflicting `module-dir` values fail. +Upstream `general.go_mod_dir` is honored; non-root `module-dir` overrides fail +for already-vendored specs. Replacing a config listed in upstream `sources` is unsupported. Vendor extraction runs after prep edits, and its Source filename is pinned before release/history updates. Ambiguous secondary-source setup requires an overlay. Unsupported constructs (notably automatic Go devel diff --git a/internal/app/azldev/core/sources/govendor.go b/internal/app/azldev/core/sources/govendor.go index fb0619758..708c3d074 100644 --- a/internal/app/azldev/core/sources/govendor.go +++ b/internal/app/azldev/core/sources/govendor.go @@ -108,6 +108,12 @@ func (p *sourcePreparerImpl) resolveGoVendorConfig( } if config.ConfigFile != "" { + if plan.AllowReplacement { + if err := p.checkGoVendorManifestCollision(outputDir, plan.ConfigName); err != nil { + return "", err + } + } + content, err := config.ReadConfigFile(p.fs) if err != nil { return "", fmt.Errorf("loading Go vendor configuration:\n%w", err) @@ -166,6 +172,10 @@ func (p *sourcePreparerImpl) checkGoVendorSourceCollision(outputDir string, name } } + return p.checkGoVendorManifestCollision(outputDir, names...) +} + +func (p *sourcePreparerImpl) checkGoVendorManifestCollision(outputDir string, names ...string) error { content, err := p.readSourcesFileIfExists(filepath.Join(outputDir, fedorasource.SourcesFileName)) if err != nil { return err diff --git a/internal/app/azldev/core/sources/govendor_config_internal_test.go b/internal/app/azldev/core/sources/govendor_config_internal_test.go index f4cb285df..0e74d02ea 100644 --- a/internal/app/azldev/core/sources/govendor_config_internal_test.go +++ b/internal/app/azldev/core/sources/govendor_config_internal_test.go @@ -4,10 +4,12 @@ package sources import ( + "strings" "testing" "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/providers/sourceproviders/fedorasource" "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" @@ -39,3 +41,32 @@ func TestGoVendorConfigFileSelection(t *testing.T) { assert.Contains(t, err.Error(), config.ConfigFile) } } + +func TestGoVendorRejectsLookasideConfigReplacement(t *testing.T) { + ctx := testctx.NewCtx() + + const upstream = "[archive]\ntidy = true\n" + + entry := fedorasource.FormatSourcesEntry("upstream.toml", fileutils.HashTypeSHA512, strings.Repeat("a", 128)) + for path, content := range map[string]string{ + "/prepared/upstream.toml": upstream, + "/prepared/sources": entry + "\n", + "/project/local.toml": "[archive]\ntidy = false\n", + } { + require.NoError(t, fileutils.WriteFile(ctx.FS(), path, []byte(content), fileperms.PublicFile)) + } + + preparer := &sourcePreparerImpl{fs: ctx.FS()} + plan := &spec.GoVendorSpec{AllowReplacement: true, ConfigName: "upstream.toml"} + config := &projectconfig.GoVendorConfig{ConfigFile: "/project/local.toml"} + _, err := preparer.resolveGoVendorConfig("/prepared", plan, config) + require.ErrorContains(t, err, "'sources' entry") + data, err := fileutils.ReadFile(ctx.FS(), "/prepared/upstream.toml") + require.NoError(t, err) + assert.Equal(t, upstream, string(data)) + + config.ConfigFile = "" + actual, err := preparer.resolveGoVendorConfig("/prepared", plan, config) + require.NoError(t, err) + assert.Equal(t, upstream, actual, "unchanged upstream settings remain supported") +} diff --git a/internal/app/azldev/core/sources/govendor_internal_test.go b/internal/app/azldev/core/sources/govendor_internal_test.go index 963aeeecc..dc4f0a61d 100644 --- a/internal/app/azldev/core/sources/govendor_internal_test.go +++ b/internal/app/azldev/core/sources/govendor_internal_test.go @@ -38,8 +38,8 @@ func goVendorTestSpec() string { } func TestPrepareSourcesGoVendor(t *testing.T) { - for _, skipLookaside := range []bool{false, true} { - t.Run(map[bool]string{false: "prepare", true: "render"}[skipLookaside], func(t *testing.T) { + for _, mode := range []string{"prepare", "render", "diff"} { + t.Run(mode, func(t *testing.T) { ctx := newMockProcessorTestCtx() ctrl := gomock.NewController(t) component := components_testutils.NewMockComponent(ctrl) @@ -59,18 +59,28 @@ func TestPrepareSourcesGoVendor(t *testing.T) { component.EXPECT().GetName().AnyTimes().Return("app") component.EXPECT().GetConfig().AnyTimes().Return(config) - manager.EXPECT().FetchComponent(gomock.Any(), component, "/output", gomock.Any()).DoAndReturn( - func(_ context.Context, _ any, _ string, _ ...sourceproviders.FetchComponentOption) error { + manager.EXPECT().FetchComponent(gomock.Any(), component, gomock.Any(), gomock.Any()).DoAndReturn( + func(_ context.Context, _ any, outputDir string, opts ...sourceproviders.FetchComponentOption) error { + var fetch sourceproviders.FetchComponentOptions + for _, option := range opts { + option(&fetch) + } + + require.True(t, fetch.PreserveGitDir, "rpmautospec needs upstream history even without output git") + for name, content := range map[string]string{ - "app.spec": goVendorTestSpec(), "app.tar.gz": "upstream", "fix.patch": "patch", + "app.spec": strings.ReplaceAll(goVendorTestSpec(), "Release: 1", "Release: %autorelease"), + "app.tar.gz": "upstream", "fix.patch": "patch", ".git/HEAD": "upstream-history", "sources": "# upstream\n", ".gitignore": "/app.tar.gz\n", } { - require.NoError(t, fileutils.WriteFile(ctx.FS(), "/output/"+name, []byte(content), fileperms.PublicFile)) + require.NoError(t, fileutils.MkdirAll(ctx.FS(), filepath.Dir(filepath.Join(outputDir, name)))) + require.NoError(t, fileutils.WriteFile(ctx.FS(), filepath.Join(outputDir, name), + []byte(content), fileperms.PublicFile)) } return nil }) - manager.EXPECT().FetchFiles(gomock.Any(), component, "/output").Return(nil) + manager.EXPECT().FetchFiles(gomock.Any(), component, gomock.Any()).Return(nil) var calls []string @@ -92,6 +102,10 @@ func TestPrepareSourcesGoVendor(t *testing.T) { require.NoError(t, err) assert.Contains(t, string(prep), "Summary: overlaid", "overlays must run before generation") + history, err := fileutils.ReadFile(ctx.FS(), filepath.Join(filepath.Dir(staging), "sources", ".git", "HEAD")) + require.NoError(t, err) + assert.Equal(t, "upstream-history", string(history)) + for name, content := range map[string]string{ "app-vendor.tar.bz2": "generated archive", "archive-name": "app-vendor.tar.bz2\n", @@ -106,13 +120,31 @@ func TestPrepareSourcesGoVendor(t *testing.T) { } options := []PreparerOption{WithGoVendorRunner(mock.NewRunner(ctx, "/mock.cfg"))} - if skipLookaside { + if mode == "render" { options = append(options, WithSkipLookaside()) } preparer, err := NewPreparer(manager, ctx.FS(), ctx, ctx, options...) require.NoError(t, err) + + if mode == "diff" { + require.NoError(t, fileutils.MkdirAll(ctx.FS(), "/output")) + diff, err := preparer.DiffSources(ctx, component, "/output") + require.NoError(t, err) + assert.Contains(t, diff.String(), "app-vendor.tar.bz2") + + for _, file := range diff.Files { + assert.NotContains(t, file.Path, ".git/") + } + + return + } + require.NoError(t, preparer.PrepareSources(ctx, component, "/output", true)) + exists, err := fileutils.Exists(ctx.FS(), "/output/.git") + require.NoError(t, err) + assert.False(t, exists, "private generation history must not leak into --without-git output") + output, err := fileutils.ReadFile(ctx.FS(), "/output/app.spec") require.NoError(t, err) assert.Contains(t, string(output), "License: Apache-2.0 AND MIT") diff --git a/internal/app/azldev/core/sources/sourceprep.go b/internal/app/azldev/core/sources/sourceprep.go index 8759787d8..d4977c5a5 100644 --- a/internal/app/azldev/core/sources/sourceprep.go +++ b/internal/app/azldev/core/sources/sourceprep.go @@ -201,6 +201,9 @@ type sourcePreparerImpl struct { // source preparation. Git-tracked files are still fetched. skipLookaside bool + // Preserve upstream history for rpmautospec during private Go vendor generation. + preserveGoVendorHistory bool + // cmdFactory is used to shell out to git for fingerprint change detection // in the project repository. Set via [WithGitRepo]. cmdFactory opctx.CmdFactory @@ -300,19 +303,17 @@ func NewPreparer( func (p *sourcePreparerImpl) PrepareSources( ctx context.Context, component components.Component, outputDir string, applyOverlays bool, ) error { - p = p.withRequiredDownloads(component, applyOverlays) - if applyOverlays { if err := p.validateArchiveOverlayConfig(component); err != nil { return err } } - // 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. + p = p.withGoVendorInputs(component, applyOverlays) + + // Go vendor prep needs history for rpmautospec even without output dist-git. var fetchOpts []sourceproviders.FetchComponentOption - if applyOverlays && p.withGitRepo { + if (applyOverlays && p.withGitRepo) || p.preserveGoVendorHistory { fetchOpts = append(fetchOpts, sourceproviders.WithPreserveGitDir()) } @@ -362,17 +363,20 @@ func (p *sourcePreparerImpl) PrepareSources( } } - return nil + return p.removePrivateGoVendorHistory(outputDir, applyOverlays) } -func (p *sourcePreparerImpl) withRequiredDownloads( +func (p *sourcePreparerImpl) withGoVendorInputs( component components.Component, applyConversion bool, ) *sourcePreparerImpl { - if applyConversion && p.skipLookaside && component.GetConfig().GoVendor.IsEnabled() { + if applyConversion && component.GetConfig().GoVendor.IsEnabled() { effective := *p effective.skipLookaside = false + effective.preserveGoVendorHistory = true - slog.Info("Go vendoring requires source downloads, including during rendering", "component", component.GetName()) + if p.skipLookaside { + slog.Info("Go vendoring requires source downloads, including during rendering", "component", component.GetName()) + } return &effective } @@ -380,6 +384,18 @@ func (p *sourcePreparerImpl) withRequiredDownloads( return p } +func (p *sourcePreparerImpl) removePrivateGoVendorHistory(outputDir string, applyConversion bool) error { + if !applyConversion || !p.preserveGoVendorHistory || p.withGitRepo || p.dryRunnable.DryRun() { + return nil + } + + if err := p.fs.RemoveAll(filepath.Join(outputDir, ".git")); err != nil { + return fmt.Errorf("removing private Go vendor history:\n%w", err) + } + + return nil +} + func (p *sourcePreparerImpl) validateArchiveOverlayConfig(component components.Component) error { config := component.GetConfig() if err := config.ValidateArchiveOverlays(p.allowNoHashes); err != nil { @@ -764,7 +780,7 @@ func removeSubmoduleEntries(fs opctx.FS, repo *gogit.Repository, repoDir string) func (p *sourcePreparerImpl) DiffSources( ctx context.Context, component components.Component, baseDir string, ) (result *dirdiff.DiffResult, err error) { - p = p.withRequiredDownloads(component, true) + p = p.withGoVendorInputs(component, true) event := p.eventListener.StartEvent("Computing overlay diff", "component", component.GetName()) defer event.End() diff --git a/internal/projectconfig/component.go b/internal/projectconfig/component.go index be9e8c0ef..67e4f6295 100644 --- a/internal/projectconfig/component.go +++ b/internal/projectconfig/component.go @@ -472,10 +472,12 @@ var AllowedSourceFilesHashTypes = map[fileutils.HashType]bool{ // Mutates the component config, updating it with overrides present in other. func (c *ComponentConfig) MergeUpdatesFrom(other *ComponentConfig) error { + c.GoVendor = deep.MustCopy(c.GoVendor) otherOverlayFiles := slices.Clone(other.OverlayFiles) otherSourceConfigFile := other.SourceConfigFile otherWithoutSourceConfigFile := *other otherWithoutSourceConfigFile.SourceConfigFile = nil + otherWithoutSourceConfigFile.GoVendor = deep.MustCopy(other.GoVendor) err := mergo.Merge(c, &otherWithoutSourceConfigFile, mergo.WithOverride, mergo.WithAppendSlice) if err != nil { @@ -497,10 +499,8 @@ func (c *ComponentConfig) MergeUpdatesFrom(other *ComponentConfig) error { func (c *ComponentConfig) overrideGoVendorEnabled(other *ComponentConfig) { if other.GoVendor != nil && other.GoVendor.Enabled != nil { - config := *c.GoVendor enabled := *other.GoVendor.Enabled - config.Enabled = &enabled - c.GoVendor = &config + c.GoVendor.Enabled = &enabled } } @@ -526,11 +526,13 @@ func (c *ComponentConfig) resolveLocalCustomScriptPaths() { // primary definition rather than merge with it. Slices in the build config are // still appended, matching [ComponentConfig.MergeUpdatesFrom]. func (c *ComponentConfig) MergeOverridesFrom(other *ComponentConfig) error { + c.GoVendor = deep.MustCopy(c.GoVendor) otherOverlayFiles := slices.Clone(other.OverlayFiles) // Merge the nested config blocks separately so that mergo does not descend // into them with slice-appending semantics. otherTopLevel := *other + otherTopLevel.GoVendor = deep.MustCopy(other.GoVendor) otherTopLevel.Spec = SpecSource{} otherTopLevel.Release = ReleaseConfig{} otherTopLevel.Build = ComponentBuildConfig{} diff --git a/internal/projectconfig/govendor_test.go b/internal/projectconfig/govendor_test.go index 02feb6943..44a656321 100644 --- a/internal/projectconfig/govendor_test.go +++ b/internal/projectconfig/govendor_test.go @@ -40,6 +40,40 @@ config-file = "go-vendor-tools.toml" assert.False(t, config.GoVendor.IsEnabled(), "explicit false must override an inherited true") } +func TestGoVendorMergeDoesNotMutateDefaults(t *testing.T) { + for name, merge := range map[string]func(*projectconfig.ComponentConfig, *projectconfig.ComponentConfig) error{ + "updates": (*projectconfig.ComponentConfig).MergeUpdatesFrom, + "overrides": (*projectconfig.ComponentConfig).MergeOverridesFrom, + } { + t.Run(name, func(t *testing.T) { + defaults := projectconfig.ComponentConfig{GoVendor: &projectconfig.GoVendorConfig{ + ConfigFile: "defaults.toml", ModuleDir: "default-module", PrepPackages: []string{"patch"}, + }} + + var first projectconfig.ComponentConfig + require.NoError(t, merge(&first, &defaults)) + second := first + overrides := projectconfig.ComponentConfig{GoVendor: &projectconfig.GoVendorConfig{ + Enabled: lo.ToPtr(true), ModuleDir: "custom-module", + }} + require.NoError(t, merge(&first, &overrides)) + first.GoVendor.PrepPackages[0] = "changed" + + for _, unchanged := range []*projectconfig.ComponentConfig{&defaults, &second} { + assert.Nil(t, unchanged.GoVendor.Enabled) + assert.Equal(t, "default-module", unchanged.GoVendor.ModuleDir) + assert.Equal(t, "defaults.toml", unchanged.GoVendor.ConfigFile) + assert.Equal(t, []string{"patch"}, unchanged.GoVendor.PrepPackages) + } + + assert.True(t, first.GoVendor.IsEnabled()) + assert.Equal(t, "custom-module", first.GoVendor.ModuleDir) + assert.Equal(t, "custom-module", overrides.GoVendor.ModuleDir) + assert.True(t, overrides.GoVendor.IsEnabled()) + }) + } +} + func TestGoVendorConfigValidation(t *testing.T) { for _, config := range []*projectconfig.GoVendorConfig{ {ModuleDir: "../outside"}, diff --git a/internal/rpm/spec/govendor.go b/internal/rpm/spec/govendor.go index 2422df37e..050e87ff9 100644 --- a/internal/rpm/spec/govendor.go +++ b/internal/rpm/spec/govendor.go @@ -67,6 +67,11 @@ func ConvertGoVendor(data []byte, options GoVendorOptions) (*GoVendorSpec, error } if configSource != "" { + if options.ModuleDir != "" && options.ModuleDir != "." { + return nil, errors.New("'module-dir' overrides are unsupported for already-vendored specs; " + + "retain the upstream module layout") + } + return prepareExistingGoVendor(tree, configSource) } diff --git a/internal/rpm/spec/govendor_existing_test.go b/internal/rpm/spec/govendor_existing_test.go index 280c9b4c0..35c1ada1a 100644 --- a/internal/rpm/spec/govendor_existing_test.go +++ b/internal/rpm/spec/govendor_existing_test.go @@ -59,6 +59,14 @@ func TestExistingGoVendoringPreservesPackaging(t *testing.T) { } } +func TestExistingGoVendoringRejectsModuleOverride(t *testing.T) { + result, err := spec.ConvertGoVendor([]byte(existingVendorSpec()), spec.GoVendorOptions{ + ArchiveName: "app-vendor.tar.bz2", ConfigName: "vendor.toml", ModuleDir: "cmd/app", + }) + require.ErrorContains(t, err, "'module-dir' overrides") + assert.Nil(t, result) +} + func TestExistingGoVendoringRejectsAmbiguousInputs(t *testing.T) { for name, input := range map[string]string{ "multiple extractions": strings.ReplaceAll(existingVendorSpec(), "%goprep -p1", "%goprep -p1\ntar -xf %{S:9}"), diff --git a/scenario/__snapshots__/TestSnapshotsContainer_config_generate-schema_stdout_1.snap b/scenario/__snapshots__/TestSnapshotsContainer_config_generate-schema_stdout_1.snap index 9cf47bd35..9259ce684 100755 --- a/scenario/__snapshots__/TestSnapshotsContainer_config_generate-schema_stdout_1.snap +++ b/scenario/__snapshots__/TestSnapshotsContainer_config_generate-schema_stdout_1.snap @@ -150,6 +150,11 @@ "title": "Source files", "description": "Source files to download for this component" }, + "go-vendor": { + "$ref": "#/$defs/GoVendorConfig", + "title": "Go vendoring", + "description": "Convert a Go application spec and generate its vendor archive during source preparation" + }, "packages": { "additionalProperties": { "$ref": "#/$defs/PackageConfig" @@ -682,6 +687,38 @@ "additionalProperties": false, "type": "object" }, + "GoVendorConfig": { + "properties": { + "enabled": { + "type": "boolean", + "title": "Enabled", + "description": "Enable Go application vendoring" + }, + "module-dir": { + "type": "string", + "title": "Module directory", + "description": "Relative module directory within the prepared source tree; defaults to its root" + }, + "config-file": { + "type": "string", + "title": "Vendor configuration file", + "description": "Path to a go-vendor-tools TOML file relative to the declaring component configuration. Replaces upstream settings when specified", + "examples": [ + "go-vendor-tools.toml" + ] + }, + "prep-packages": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Prep packages", + "description": "Additional RPM packages needed to execute the upstream prep section in mock" + } + }, + "additionalProperties": false, + "type": "object" + }, "ImageCapabilities": { "properties": { "machine-bootable": { From a4f835f4bd2b991e15deb267a9a1416fe8f63e40 Mon Sep 17 00:00:00 2001 From: Antonio Salinas <173939267+Tonisal-byte@users.noreply.github.com> Date: Mon, 9 Nov 2026 15:29:48 -0800 Subject: [PATCH 07/16] feat: generate Go vendor tarballs through source-files Add the go-vendor source origin with automatic vendor Source discovery, optional explicit filenames and expected hashes, declaration-relative native settings, and isolated generation after overlays. Keep generated output identity out of declarative fingerprints and reuse manifest replacement and render filtering. Prepare only a private spec copy to avoid consuming the archive being generated. Do not convert published packaging, rewrite licenses, remove dependencies, or add offline build settings. Support local and upstream inputs with private rpmautospec history and reject ambiguous prep layouts. Validated mage scenarioUpdate, mage all, mage check all, and targeted regression/mutation tests. A real mock-based fixture generated explicit and discovered archives, built and ran its offline RPM, rendered idempotently without the vendor payload, and rejected stale output hashes before publication. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/user/how-to/vendor-go-application.md | 96 ++++++ .../reference/cli/azldev_component_render.md | 6 +- docs/user/reference/config/components.md | 31 +- .../app/azldev/agentskill/agentskill_test.go | 10 + .../agentskill/content/comp-toml.md.tmpl | 9 + .../content/withoutlockfile/comp-toml.md.tmpl | 9 + internal/app/azldev/cmds/component/build.go | 3 +- .../cmds/component/changed_upstreamcommit.go | 16 + .../app/azldev/cmds/component/diffsources.go | 2 +- .../cmds/component/history_customizations.go | 11 + .../cmds/component/history_internal_test.go | 2 + .../app/azldev/cmds/component/preparerctx.go | 28 ++ .../azldev/cmds/component/preparesources.go | 2 +- internal/app/azldev/cmds/component/render.go | 14 +- .../azldev/cmds/component/render_sources.go | 52 +++ .../azldev/cmds/component/sourcepreparer.go | 26 +- internal/app/azldev/core/sources/govendor.go | 301 ++++++++++++++++++ .../core/sources/govendor_internal_test.go | 254 +++++++++++++++ .../app/azldev/core/sources/sourceprep.go | 84 ++++- internal/fingerprint/fingerprint.go | 13 +- internal/govendor/generate.go | 280 ++++++++++++++++ internal/govendor/generate_internal_test.go | 120 +++++++ internal/projectconfig/component.go | 27 +- internal/projectconfig/configfile.go | 12 +- internal/projectconfig/fingerprint_test.go | 2 + internal/projectconfig/govendor.go | 123 +++++++ internal/projectconfig/govendor_test.go | 73 +++++ .../sourceproviders/sourcemanager.go | 5 +- internal/rpm/spec/vendorprep.go | 231 ++++++++++++++ internal/rpm/spec/vendorprep_test.go | 76 +++++ ...ainer_config_generate-schema_stdout_1.snap | 29 +- ...shots_config_generate-schema_stdout_1.snap | 29 +- schemas/azldev.schema.json | 29 +- 33 files changed, 1950 insertions(+), 55 deletions(-) create mode 100644 docs/user/how-to/vendor-go-application.md create mode 100644 internal/app/azldev/cmds/component/render_sources.go create mode 100644 internal/app/azldev/core/sources/govendor.go create mode 100644 internal/app/azldev/core/sources/govendor_internal_test.go create mode 100644 internal/govendor/generate.go create mode 100644 internal/govendor/generate_internal_test.go create mode 100644 internal/projectconfig/govendor.go create mode 100644 internal/projectconfig/govendor_test.go create mode 100644 internal/rpm/spec/vendorprep.go create mode 100644 internal/rpm/spec/vendorprep_test.go 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..4142851e2 --- /dev/null +++ b/docs/user/how-to/vendor-go-application.md @@ -0,0 +1,96 @@ +# 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]] +origin.type = "go-vendor" +# Optional native settings, relative to this TOML: +origin.config-file = "go-vendor-tools.toml" +``` + +By default, azldev finds the single unconditional +`tar -xf %{S:N}` or `tar -xf %{SOURCEN}` in `%prep` referencing a secondary Source, +then asks RPM to expand its filename. Source numbers and package versions are not +embedded in the config. Ambiguous/conditional extraction, secondary setup +extraction (`-a`/`-b`), and release-dependent archive filenames fail rather than +guessing. Use a narrowly scoped prep/Source overlay to make these layouts explicit. +The discovered vendor archive's existing `sources` entry is replaced automatically. +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` overrides discovery and is required when no unique target is found. +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. + +`hash` is optional specifically for `go-vendor`: 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 +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. + +Render and source diffs also regenerate and need network access. Render retains +the updated manifest, not lookaside payloads. 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..af16bc4a6 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 source-files require downloads and regeneration; only the manifest, +not archive payloads, is rendered. 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..c8d8e45f6 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 | Conditional | Name of the file in the sources directory; optional discovery for `go-vendor`. | +| 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,32 @@ 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]] +origin.type = "go-vendor" +origin.config-file = "go-vendor-tools.toml" +``` + +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` | Discover from the unique secondary Source extraction in `%prep` | Optional plain basename override; explicit collisions use the normal replacement rules. | +| `hash` | Compute and record | Optional expected output digest; 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. Automatic discovery can replace +the discovered vendor manifest entry without replacement fields. Generation runs +after overlays and requires source downloads during prepare, render, and diff. +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..930c0ebbd 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, "`hash` is optional output verification") + } +} + 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..aff0cf9f1 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. +Omit `filename` to discover a unique vendor Source; set a stable basename for new +packaging. `hash` is optional output verification; configured mismatches fail. +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, including during render/diff, and needs network/mock access. +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..3e34d609e 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. +Omit `filename` to discover a unique vendor Source; set a stable basename for new +packaging. `hash` is optional output verification; configured mismatches fail. +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, including during render/diff, and needs network/mock access. +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..462f483bf 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()), )...) 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..f49a20532 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 source-files require downloads and regeneration; only the manifest, +not archive payloads, is rendered. 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 @@ -540,11 +540,12 @@ func prepareComponentSources( sources.WithUpstreamProvenance(sources.FedoraDistTag(distro.Ref.Name, distro.Version.ReleaseVer)), sources.WithMockProcessor(mockProcessor), ) + if rpmDevBumpspec { preparerOpts = append(preparerOpts, sources.WithRPMDevBumpspec(env, env.WorkDir(), "")) } - preparer, err := newSourcePreparer(sourceManager, env.FS(), env, env, append( + preparer, err := newComponentSourcePreparer(env, comp, sourceManager, nil, append( preparerOpts, sources.WithSpecEditor(specEditor), )...) @@ -768,6 +769,11 @@ func finishComponentRender( } // Remove .git directory — must not appear in rendered output. + if prep.comp.GetConfig().HasGoVendorSources() { + if err := removeVendorRenderPayloads(env.FS(), componentDir); err != nil { + return false, err + } + } // rpmautospec already read it during the batch mock phase. gitDir := filepath.Join(componentDir, ".git") if removeErr := env.FS().RemoveAll(gitDir); removeErr != nil { diff --git a/internal/app/azldev/cmds/component/render_sources.go b/internal/app/azldev/cmds/component/render_sources.go new file mode 100644 index 000000000..71fd020be --- /dev/null +++ b/internal/app/azldev/cmds/component/render_sources.go @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +package component + +import ( + "fmt" + "path/filepath" + + "github.com/microsoft/azure-linux-dev-tools/internal/global/opctx" + "github.com/microsoft/azure-linux-dev-tools/internal/providers/sourceproviders/fedorasource" + "github.com/microsoft/azure-linux-dev-tools/internal/utils/fileutils" +) + +func removeVendorRenderPayloads(fs opctx.FS, directory string) error { + path := filepath.Join(directory, fedorasource.SourcesFileName) + + data, err := fileutils.ReadFile(fs, path) + if err != nil { + return fmt.Errorf("reading generated source manifest:\n%w", err) + } + + lines, err := fedorasource.ReadSourcesFile(string(data)) + if err != nil { + return fmt.Errorf("parsing generated source manifest:\n%w", err) + } + + for _, line := range lines { + if line.Entry == nil { + continue + } + + if err := fileutils.ValidateFilename(line.Entry.Filename); err != nil { + return fmt.Errorf("validating payload filename:\n%w", err) + } + + file := filepath.Join(directory, line.Entry.Filename) + + exists, err := fileutils.Exists(fs, file) + if err != nil { + return fmt.Errorf("checking rendered payload:\n%w", err) + } + + if exists { + if err := fs.Remove(file); err != nil { + return fmt.Errorf("excluding generated source payload %#q:\n%w", file, err) + } + } + } + + return nil +} 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..d788e96cc --- /dev/null +++ b/internal/app/azldev/core/sources/govendor.go @@ -0,0 +1,301 @@ +// 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 } +} + +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 and discovered names 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, 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, plan.Automatic) +} + +func (p *sourcePreparerImpl) publishVendorSource( + component components.Component, directory string, ref projectconfig.SourceFileReference, + artifact govendor.Artifact, automatic bool, +) (projectconfig.SourceFileReference, error) { + ref.Filename = artifact.Name + 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.validateVendorTarget(component, directory, ref, automatic); err != nil { + return ref, err + } + + manifest, err := p.readSourcesFileIfExists(filepath.Join(directory, fedorasource.SourcesFileName)) + if err != nil { + return ref, err + } + + lines, err := fedorasource.ReadSourcesFile(manifest) + if err != nil { + return ref, fmt.Errorf("reading vendor source manifest:\n%w", err) + } + + for _, line := range lines { + if automatic && line.Entry != nil && line.Entry.Filename == ref.Filename { + ref.ReplaceUpstream = true + ref.ReplaceReason = "Regenerate the discovered Go vendor Source" + } + } + + 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) validateVendorTarget( + component components.Component, directory string, ref projectconfig.SourceFileReference, automatic bool, +) 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) + } + + existing := map[string]fedorasource.SourcesFileEntry{} + + for _, line := range lines { + if line.Entry != nil { + existing[line.Entry.Filename] = *line.Entry + } + } + + 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 !automatic || ref.ReplaceUpstream { + _, _, _, err := p.processSourceRef(ref, existing, component.GetName(), directory) + + return err + } + + return nil +} 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..d3dd2ed92 --- /dev/null +++ b/internal/app/azldev/core/sources/govendor_internal_test.go @@ -0,0 +1,254 @@ +// 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{ + "discover", 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", + }} + if mode == newSource || mode == "collision" { + ref.Filename = "vendor.tar.bz2" + } + + 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(), "/tmp/azldev-vendor-*/output/config.toml") + require.NoError(t, err) + require.Len(t, matches, 1) + 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)) + + for name, content := range map[string]string{"name": "vendor.tar.bz2\n", "vendor.tar.bz2": payload} { + require.NoError(t, fileutils.WriteFile(ctx.FS(), filepath.Join(directory, name), + []byte(content), fileperms.PublicFile)) + } + + return "", nil + } + preparer, err := NewPreparer(manager, ctx.FS(), ctx, ctx, + WithGoVendorRunner(mock.NewRunner(ctx, "/mock.cfg")), 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 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") +} + +func TestVendorScratchUsesProjectWorkDir(t *testing.T) { + ctx := newMockProcessorTestCtx() + preparer := &sourcePreparerImpl{ + fs: ctx.FS(), goVendorRunner: mock.NewRunner(ctx, "/mock.cfg").WithBaseDir("/project/build/vendor"), + } + path, err := preparer.vendorScratchDir() + require.NoError(t, err) + assert.True(t, strings.HasPrefix(path, "/project/build/vendor/azldev-vendor-")) + assert.NotContains(t, path, "*") +} diff --git a/internal/app/azldev/core/sources/sourceprep.go b/internal/app/azldev/core/sources/sourceprep.go index 4edeb30b6..d19ed048a 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,9 @@ type sourcePreparerImpl struct { // source preparation. Git-tracked files are still fetched. skipLookaside bool + goVendorRunner *mock.Runner + vendorFetchOnly 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 +307,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 := declaredConfig.HasGoVendorSources() + 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 +328,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 +357,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 +366,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 +801,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 +831,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 { 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..af86384fe --- /dev/null +++ b/internal/govendor/generate.go @@ -0,0 +1,280 @@ +// 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 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) +} + +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().WithBaseDir(filepath.Join(req.WorkDir, "mock")).EnableNetwork().WithUnprivileged() + 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 string) (Artifact, error) { + var artifact Artifact + // Copy opened regular files, never following chroot-controlled symlinks. + nameFile := filepath.Join(workDir, "name") + if err := collect(fs, filepath.Join(output, "name"), nameFile); err != nil { + return artifact, err + } + + name, err := fileutils.ReadFile(fs, nameFile) + if err != nil { + return artifact, fmt.Errorf("reading generated vendor name:\n%w", err) + } + + artifact.Name = strings.TrimSpace(string(name)) + if err := fileutils.ValidateFilename(artifact.Name); err != nil { + return artifact, fmt.Errorf("invalid generated vendor filename:\n%w", err) + } + + if strings.ContainsAny(artifact.Name, "%\r\n") || !archiveFilename(artifact.Name) { + return artifact, fmt.Errorf("unsupported generated vendor filename %#q", artifact.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", + "IFS= read -r name < /tmp/azldev-vendor/azldev-vendor-name", + `case "$name" in ""|*/*|*%*|.*) echo 'Invalid vendor filename' >&2; exit 1;; esac`, + `cd "$root"`, + "cd " + quote(module), + quote("test", "-f", filepath.Join(config.General.ModuleDir, "go.mod")), + `root=$(pwd -P)`, + "cd /azldev-vendor-sources", + `go_vendor_archive create --config /azldev-vendor-output/config.toml --output "/azldev-vendor-output/$name" "$root"`, + `printf '%s\n' "$name" > /azldev-vendor-output/name`, + } + + 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..f8655abe9 --- /dev/null +++ b/internal/govendor/generate_internal_test.go @@ -0,0 +1,120 @@ +// 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 TestGenerate(t *testing.T) { + for _, mode := range []string{"success", "failure", "missing name", "bad name", "empty archive"} { + t.Run(mode, func(t *testing.T) { + ctx := testctx.NewCtx() + ctx.CmdFactory.RegisterCommandInSearchPath(mock.MockBinary) + require.NoError(t, fileutils.WriteFile(ctx.FS(), "/input/app.spec", []byte("upstream"), fileperms.PublicFile)) + + var commands []string + + ctx.CmdFactory.RunHandler = func(cmd *exec.Cmd) error { + commands = append(commands, strings.Join(cmd.Args, " ")) + + return nil + } + ctx.CmdFactory.RunAndGetOutputHandler = func(cmd *exec.Cmd) (string, error) { + assert.Contains(t, strings.Join(cmd.Args, " "), "go_vendor_archive create") + + if mode == "failure" { + return "native tool failed", errors.New("generation failed") + } + + name := "vendor.tar.bz2" + if mode == "bad name" { + name = "../host" + } + + if mode != "missing name" { + require.NoError(t, fileutils.WriteFile(ctx.FS(), "/work/output/name", []byte(name+"\n"), fileperms.PublicFile)) + } + + payload := "archive" + if mode == "empty archive" { + payload = "" + } + + require.NoError(t, fileutils.WriteFile(ctx.FS(), "/work/output/vendor.tar.bz2", + []byte(payload), fileperms.PublicFile)) + + return "", nil + } + req := Request{SourceDir: "/input", WorkDir: "/work", SpecName: "app.spec", PrepSpec: []byte("private")} + artifact, err := Generate(ctx, ctx.FS(), mock.NewRunner(ctx, "/mock.cfg"), req) + + assert.Contains(t, strings.Join(commands, "\n"), "--scrub all") + + if mode != "success" { + require.Error(t, err) + + return + } + + require.NoError(t, err) + assert.Equal(t, "vendor.tar.bz2", artifact.Name) + assert.Equal(t, "/work/vendor.tar.bz2", artifact.Path) + + source, err := fileutils.ReadFile(ctx.FS(), "/input/app.spec") + require.NoError(t, err) + assert.Equal(t, "upstream", string(source)) + }) + } +} + +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") + assert.Contains(t, command[len(command)-1], "go_vendor_archive create") + assert.LessOrEqual(t, strings.Count(command[len(command)-1], "cd cmd/app"), 1) + } + + 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..172ca5495 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,omitempty" json:"filename,omitempty" jsonschema:"description=Source basename. Optional for go-vendor to discover the vendor Source from the spec."` // Hash of the source file, expressed as a hex string. Hash string `toml:"hash,omitempty" json:"hash,omitempty"` @@ -649,6 +662,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..5bc1d4cc5 --- /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 && ref.Filename == "" { + return nil + } + + 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..636e5e751 --- /dev/null +++ b/internal/projectconfig/govendor_test.go @@ -0,0 +1,73 @@ +// 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{ + "discovered": {Origin: projectconfig.Origin{Type: projectconfig.OriginTypeGoVendor}}, + "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()) + }) + } + + 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.OriginTypeOverlay, ConfigFile: "vendor.toml"}, + } { + t.Run(name, func(t *testing.T) { + file := projectconfig.ConfigFile{Components: map[string]projectconfig.ComponentConfig{ + "app": {SourceFiles: []projectconfig.SourceFileReference{{Origin: origin}}}, + }} + require.Error(t, file.Validate()) + }) + } +} + +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..005bae54f --- /dev/null +++ b/internal/rpm/spec/vendorprep.go @@ -0,0 +1,231 @@ +// 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 + Automatic bool +} + +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]`) +) + +// 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 filename != "" { + 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, archive, 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") + } + } + + appendVendorOutputCommands(prep, archive, filename, sources[number]) + + return &VendorPrep{ + Spec: []byte(strings.Join(serializeTree(root), "\n") + "\n"), + ConfigName: configName, Automatic: filename == "", + }, nil +} + +func appendVendorOutputCommands(prep *sectionHandle, archive, filename, selectedSource string) { + if filename != "" && selectedSource != "" { + prep.AppendLines([]string{"test %{shescape:" + selectedSource + "} = %{shescape:" + filename + "}"}) + } + + prep.AppendLines([]string{ + `pwd -P > "%{_topdir}/azldev-vendor-root"`, + "printf '%%s\\n' %{shescape:" + archive + `} > "%{_topdir}/azldev-vendor-name"`, + }) +} + +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") + } + + 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, +) (number, archive string, err error) { + if len(candidates) > 1 || (filename == "" && len(candidates) != 1) { + return "", "", errors.New("cannot discover a unique vendor Source; set 'filename' and simplify prep extraction") + } + + archive = filename + + if len(candidates) == 1 { + number = candidates[0] + if filename == "" { + archive = sources[number] + } else if !strings.Contains(sources[number], "%") && sources[number] != filename { + return "", "", errors.New("explicit vendor filename does not match the extracted Source") + } + } + + if strings.Contains(archive, "://") || strings.ContainsAny(archive, "\r\n") { + return "", "", errors.New("vendor Source must be a local archive filename") + } + + if strings.Contains(archive, "%{release}") { + return "", "", errors.New("release-dependent vendor filenames require a stable Source overlay") + } + + if filename != "" && number == "" { + number, err = vendorSourceWithFilename(sources, filename) + if err != nil { + return "", "", err + } + } + + return number, archive, 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..fd26c9dc3 --- /dev/null +++ b/internal/rpm/spec/vendorprep_test.go @@ -0,0 +1,76 @@ +// 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), "") + require.NoError(t, err) + assert.True(t, plan.Automatic) + 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}") + assert.Equal(t, input, vendorSpec(), "planning only produces a private spec") + + newSpec := strings.ReplaceAll(input, "tar -xf %{S:5}", "") + plan, err = spec.PrepareVendorSource([]byte(newSpec), "vendor.tar.bz2") + require.NoError(t, err) + assert.False(t, plan.Automatic) + assert.Contains(t, string(plan.Spec), "%{shescape: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"), + "no extraction": strings.ReplaceAll(vendorSpec(), "tar -xf %{S:5}", ""), + "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:"), + "release filename": strings.ReplaceAll(vendorSpec(), "app-%{version}-vendor", "app-%{release}-vendor"), + "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), "") + 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) + } + + _, err := spec.PrepareVendorSource([]byte(vendorSpec()), "different.tar.bz2") + require.NoError(t, err, "macro-expanded filenames are checked by RPM during private prep") +} diff --git a/scenario/__snapshots__/TestSnapshotsContainer_config_generate-schema_stdout_1.snap b/scenario/__snapshots__/TestSnapshotsContainer_config_generate-schema_stdout_1.snap index 9cf47bd35..51b7123a8 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 basename. Optional for go-vendor to discover the vendor Source from the spec." }, "hash": { "type": "string" @@ -1361,10 +1381,7 @@ } }, "additionalProperties": false, - "type": "object", - "required": [ - "filename" - ] + "type": "object" }, "SpecSource": { "properties": { diff --git a/scenario/__snapshots__/TestSnapshots_config_generate-schema_stdout_1.snap b/scenario/__snapshots__/TestSnapshots_config_generate-schema_stdout_1.snap index 9cf47bd35..51b7123a8 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 basename. Optional for go-vendor to discover the vendor Source from the spec." }, "hash": { "type": "string" @@ -1361,10 +1381,7 @@ } }, "additionalProperties": false, - "type": "object", - "required": [ - "filename" - ] + "type": "object" }, "SpecSource": { "properties": { diff --git a/schemas/azldev.schema.json b/schemas/azldev.schema.json index 9cf47bd35..51b7123a8 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 basename. Optional for go-vendor to discover the vendor Source from the spec." }, "hash": { "type": "string" @@ -1361,10 +1381,7 @@ } }, "additionalProperties": false, - "type": "object", - "required": [ - "filename" - ] + "type": "object" }, "SpecSource": { "properties": { From 10621358b149b49f7fd58b2d134490ab1b959633 Mon Sep 17 00:00:00 2001 From: Antonio Salinas <173939267+Tonisal-byte@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:52:21 -0800 Subject: [PATCH 08/16] refactor: retire the component-level Go spec converter Replace the earlier implementation with the source-files design on this PR, retaining the design history and avoiding automatic changes to published specs. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/user/how-to/vendor-go-application.md | 160 -------- docs/user/reference/cli/azldev.md | 2 +- docs/user/reference/cli/azldev_advanced.md | 2 +- docs/user/reference/cli/azldev_completion.md | 2 +- docs/user/reference/cli/azldev_component.md | 2 +- .../cli/azldev_component_prepare-sources.md | 4 +- .../reference/cli/azldev_component_render.md | 6 +- docs/user/reference/cli/azldev_config.md | 2 +- docs/user/reference/cli/azldev_docs.md | 2 +- docs/user/reference/cli/azldev_image.md | 2 +- docs/user/reference/cli/azldev_package.md | 2 +- docs/user/reference/cli/azldev_project.md | 2 +- docs/user/reference/cli/azldev_repo.md | 2 +- docs/user/reference/cli/azldev_version.md | 2 +- docs/user/reference/config/components.md | 74 ---- .../app/azldev/agentskill/agentskill_test.go | 17 - .../agentskill/content/comp-toml.md.tmpl | 29 -- .../content/withoutlockfile/comp-toml.md.tmpl | 29 -- internal/app/azldev/cmds/component/build.go | 2 +- .../cmds/component/changed_upstreamcommit.go | 14 - .../changed_upstreamcommit_internal_test.go | 22 - .../app/azldev/cmds/component/diffsources.go | 2 +- .../cmds/component/history_customizations.go | 25 -- .../cmds/component/history_internal_test.go | 5 - .../app/azldev/cmds/component/preparerctx.go | 26 -- .../component/preparerctx_internal_test.go | 64 --- .../azldev/cmds/component/preparesources.go | 14 +- internal/app/azldev/cmds/component/render.go | 18 +- .../azldev/cmds/component/render_govendor.go | 53 --- .../render_govendor_internal_test.go | 51 --- .../azldev/cmds/component/sourcepreparer.go | 19 +- internal/app/azldev/core/sources/govendor.go | 267 ------------ .../sources/govendor_config_internal_test.go | 72 ---- .../govendor_existing_internal_test.go | 135 ------ .../core/sources/govendor_internal_test.go | 285 ------------- .../app/azldev/core/sources/sourceprep.go | 62 +-- internal/fingerprint/doc.go | 2 +- internal/fingerprint/fingerprint.go | 16 +- internal/fingerprint/govendor_test.go | 62 --- internal/govendor/generate.go | 325 --------------- internal/govendor/generate_internal_test.go | 211 ---------- internal/projectconfig/component.go | 65 ++- .../component_clone_internal_test.go | 36 -- internal/projectconfig/configfile.go | 4 - internal/projectconfig/fingerprint_test.go | 4 - internal/projectconfig/govendor.go | 102 ----- .../govendor_loader_internal_test.go | 56 --- internal/projectconfig/govendor_test.go | 163 -------- internal/rpm/spec/govendor.go | 384 ------------------ internal/rpm/spec/govendor_existing.go | 232 ----------- internal/rpm/spec/govendor_existing_test.go | 137 ------- internal/rpm/spec/govendor_test.go | 203 --------- internal/utils/fileutils/copy.go | 17 +- internal/utils/fileutils/file.go | 26 -- internal/utils/fileutils/nofollow_test.go | 74 ---- ...ainer_config_generate-schema_stdout_1.snap | 37 -- ...shots_config_generate-schema_stdout_1.snap | 37 -- schemas/azldev.schema.json | 37 -- 58 files changed, 73 insertions(+), 3634 deletions(-) delete mode 100644 docs/user/how-to/vendor-go-application.md delete mode 100644 internal/app/azldev/cmds/component/preparerctx_internal_test.go delete mode 100644 internal/app/azldev/cmds/component/render_govendor.go delete mode 100644 internal/app/azldev/cmds/component/render_govendor_internal_test.go delete mode 100644 internal/app/azldev/core/sources/govendor.go delete mode 100644 internal/app/azldev/core/sources/govendor_config_internal_test.go delete mode 100644 internal/app/azldev/core/sources/govendor_existing_internal_test.go delete mode 100644 internal/app/azldev/core/sources/govendor_internal_test.go delete mode 100644 internal/fingerprint/govendor_test.go delete mode 100644 internal/govendor/generate.go delete mode 100644 internal/govendor/generate_internal_test.go delete mode 100644 internal/projectconfig/component_clone_internal_test.go delete mode 100644 internal/projectconfig/govendor.go delete mode 100644 internal/projectconfig/govendor_loader_internal_test.go delete mode 100644 internal/projectconfig/govendor_test.go delete mode 100644 internal/rpm/spec/govendor.go delete mode 100644 internal/rpm/spec/govendor_existing.go delete mode 100644 internal/rpm/spec/govendor_existing_test.go delete mode 100644 internal/rpm/spec/govendor_test.go delete mode 100644 internal/utils/fileutils/nofollow_test.go diff --git a/docs/user/how-to/vendor-go-application.md b/docs/user/how-to/vendor-go-application.md deleted file mode 100644 index 9f9387c83..000000000 --- a/docs/user/how-to/vendor-go-application.md +++ /dev/null @@ -1,160 +0,0 @@ -# Vendor a Go application - -Use `go-vendor` to bundle a Go application's module dependencies instead of -building against separately packaged `golang(...)` libraries. This is a targeted -conversion of the selected upstream spec, not a `go2rpm` wrapper or a newly -generated replacement spec. The same setting regenerates sources for supported -specs that already use go-vendor-tools. - -## Enable and prepare - -Add this to the component definition: - -```toml -[components.example.go-vendor] -enabled = true -``` - -For custom vendor settings, use a separate file beside the component definition: - -```toml -# example.comp.toml -[components.example.go-vendor] -enabled = true -config-file = "go-vendor-tools.toml" -``` - -```toml -# go-vendor-tools.toml -[archive] -use_module_proxy = true - -[licensing] -detector = "askalono" -``` - -This file replaces, rather than merges with, upstream settings. Carry forward -any required upstream license exceptions. Omit `config-file` to reuse those -settings unchanged. Paths are relative to the declaring component configuration, -including when inherited from defaults; no adjacent file is loaded implicitly. -File-only edits affect the component fingerprint. Inline `tool-config` values -are no longer accepted. - -Then prepare the complete build inputs: - -```sh -azldev component prepare-sources -p example -o prepared-example --without-git -``` - -The project/build distro must have a working mock configuration and provide -`go-vendor-tools`, `askalono-cli`, `golang`, `go-rpm-macros`, `rpm-build`, and -`rpmdevtools`, `rpmautospec`, `git`, and `python3-click`. These are installed in a -fresh, network-enabled generation chroot; -neither `go2rpm` nor the Go vendor tools are required on the host. Configure -`prep-packages` for additional tools required by upstream prep scripts. - -The pipeline fetches the selected upstream sources, applies overlays, and copies -them into isolated staging. It processes automatic release/changelog metadata -there and runs the existing `%prep` section with `rpmbuild -bp --nodeps`. -Upstream Git history remains available for this processing even with -`--without-git`; it is removed from the final output when that option is used. -This retains upstream patches and edits to module files. It then calls -`go_vendor_archive create` on the prepared module tree, extracts the result for -license detection, and runs `go_vendor_license` without interactive prompts. -The archive tool runs from staged dist-git, so hooks can find preserved patches -and sidecars through `GVT_CWD`. -Unrecognized licenses fail preparation; add reviewed, hash-qualified exceptions -to the file selected by `config-file` rather than suppressing detection. - -The output includes the converted spec, all its original sources and patches, -`-vendor.tar.bz2`, and `azldev-go-vendor.toml`. The archive is recorded -with SHA-512 in `sources` and excluded from synthetic git commits with `.gitignore`. -The upstream release/changelog is retained; ordinary azldev release handling -still applies afterwards. - -## What is converted - -The converter removes standalone `BuildRequires: golang(import/path)` tags, -including version constraints, and bare `%go_generate_buildrequires` invocations. -It changes a bare `%gocheck` to `%gotest ./...`, adds vendor extraction at the end -of `%prep`, and enables module/vendor mode for subsequent build scripts. -It adds the Go compiler/macros and vendor tooling build requirements, dynamic -license backend requirements, license installation/file-list handling, and a -license check in `%build` so disabling `%check` does not bypass license validation. -The main `License:` tag is updated to the detected cumulative SPDX expression. - -Unrelated runtime dependencies, C-library build dependencies, custom commands, -patches, metadata, and ordinary subpackages are retained. Go vendoring does not -eliminate dependencies on shared libraries used by cgo. - -The initial supported scope is application specs with one unconditional -main-package `%prep`, `%build`, `%install`, and `%files` section. The prep section -must finish in the module root, or use `module-dir` for a relative subdirectory. -Custom build/install commands must already address that same module. Conditional -commands within those sections are retained. - -Automatic Go development subpackages (`%gopkg`, `%goinstall`, Go file-list macros), -flagged `%gocheck` commands, compound/rich Go BuildRequires, -explicit conflicting module-mode settings, and ambiguous/conditional -target sections are rejected. Use narrowly scoped overlays to adapt these cases; -azldev does not silently drop subpackages or rewrite arbitrary shell scripts. - -## Regenerate an existing vendor archive - -For an already-vendored spec, azldev recognizes a single -`tar -xf %{S:N}` (or `%{SOURCEN}`) prep command and the configuration source -referenced by `%go_vendor_license_* -c %{S:M}` commands. The Source numbers need -not be 1 and 2. The configuration must name a plain sidecar file. - -The original Source numbers, license/file-list macros, module-mode settings, and -custom packaging are retained. The vendor extraction moves to the end of `%prep`, -after module-file patches and edits, because the replacement archive already -contains their results. Directory changes after the original extraction and -secondary-source extraction with `%setup -a/-b` or `%autosetup -a/-b` are rejected -as ambiguous; adapt these layouts with an overlay. The temporary prep spec -omits the vendor Source declaration and its extraction command, so generating -the replacement does not consume the old vendor payload. RPM expands the -upstream archive filename and pins the vendor Source tag to that expanded name, -so subsequent release/history changes cannot desynchronize the spec and payload. -The regenerated archive replaces that file and its -`sources` checksum rather than adding a second vendor archive. - -When `config-file` is omitted, the upstream go-vendor-tools configuration is used, -including its reviewed license exceptions. An explicit file replaces that configuration -even when empty; missing files or invalid TOML fail without falling back. -The detected licenses are verified against the existing -main-package `License:` expression; mismatches fail instead of rewriting it. -Upstream `general.go_mod_dir` is honored by generation and licensing, preserving -the module subdirectory within the archive. Non-root `module-dir` overrides are -rejected for already-vendored specs; their extraction and licensing retain the -upstream layout. -Replacing a configuration listed in upstream `sources` is also rejected before -generation; custom configurations must replace a tracked sidecar instead. -Neither the regenerated archive nor its configuration sidecar may also be -declared in `source-files`, even with `replace-upstream = true`. -The source-fetch phase currently still downloads the upstream vendor archive -alongside the other upstream sources, before regenerating its contents. - -## Review and upgrade - -Run `azldev component diff-sources -p example` to inspect the conversion, or -`azldev component render -p example` to refresh checked-in rendered output. -Rendering and source diffs also generate the archive: they need network access and -can be substantially slower for enabled components. -Rendered output retains the `sources` checksums but excludes payloads listed in -that manifest; archives remain preparation/build artifacts rather than checked-in files. - -Review the cumulative license expression and the retained build/install/check -commands before building. Automatic detection is not approval of a dependency's -license. The converter sets `GO111MODULE=on`, `-mod=vendor`, `GOPROXY=off`, -`GOSUMDB=off`, and `GOTOOLCHAIN=local` for build scripts; custom commands must not -override these settings to download dependencies. - -The same TOML applies after an upstream version update: no archive version, -import path, Source number, or spec line number is embedded in the declaration. -Generation reruns against the newly selected and patched inputs. Review changed -vendor hashes and licenses; an upstream packaging change may require updating -an overlay or resolving a newly unsupported construct. - -See [Go vendoring configuration](../reference/config/components.md#go-vendoring) -for module layout, dependency overrides, and license exceptions. diff --git a/docs/user/reference/cli/azldev.md b/docs/user/reference/cli/azldev.md index c896e7c3c..c5de33703 100644 --- a/docs/user/reference/cli/azldev.md +++ b/docs/user/reference/cli/azldev.md @@ -2,7 +2,7 @@ ## azldev -🐧 Azure Linux Dev Tool 0.0.0-devel +🐧 Azure Linux Dev Tool ### Synopsis diff --git a/docs/user/reference/cli/azldev_advanced.md b/docs/user/reference/cli/azldev_advanced.md index 28a397d69..f76116d52 100644 --- a/docs/user/reference/cli/azldev_advanced.md +++ b/docs/user/reference/cli/azldev_advanced.md @@ -38,7 +38,7 @@ output but fully supported. ### SEE ALSO -* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool 0.0.0-devel +* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool * [azldev advanced download-sources](azldev_advanced_download-sources.md) - Download source files listed in a Fedora-format sources file * [azldev advanced mcp](azldev_advanced_mcp.md) - Run in MCP server mode * [azldev advanced mock](azldev_advanced_mock.md) - Run RPM mock tool diff --git a/docs/user/reference/cli/azldev_completion.md b/docs/user/reference/cli/azldev_completion.md index 6b375b33b..109d7858e 100644 --- a/docs/user/reference/cli/azldev_completion.md +++ b/docs/user/reference/cli/azldev_completion.md @@ -36,7 +36,7 @@ See each sub-command's help for details on how to use the generated script. ### SEE ALSO -* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool 0.0.0-devel +* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool * [azldev completion bash](azldev_completion_bash.md) - Generate the autocompletion script for bash * [azldev completion fish](azldev_completion_fish.md) - Generate the autocompletion script for fish * [azldev completion powershell](azldev_completion_powershell.md) - Generate the autocompletion script for powershell diff --git a/docs/user/reference/cli/azldev_component.md b/docs/user/reference/cli/azldev_component.md index f0cd76071..df0e9622b 100644 --- a/docs/user/reference/cli/azldev_component.md +++ b/docs/user/reference/cli/azldev_component.md @@ -40,7 +40,7 @@ components defined in the project configuration. ### SEE ALSO -* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool 0.0.0-devel +* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool * [azldev component add](azldev_component_add.md) - Add component(s) to this project * [azldev component build](azldev_component_build.md) - Build packages for components * [azldev component changed](azldev_component_changed.md) - Detect which components changed between two git refs diff --git a/docs/user/reference/cli/azldev_component_prepare-sources.md b/docs/user/reference/cli/azldev_component_prepare-sources.md index b133f34c5..45f9f8cb7 100644 --- a/docs/user/reference/cli/azldev_component_prepare-sources.md +++ b/docs/user/reference/cli/azldev_component_prepare-sources.md @@ -41,8 +41,8 @@ azldev component prepare-sources [flags] -o, --output-dir string output directory --rpmdev-bumpspec Use rpmdev-bumpspec instead of the legacy static release calculation --skip-lock-validation skip lock file consistency checks - --skip-overlays skip overlays and Go vendor conversion, preserving upstream packaging - --skip-sources skip downloading sources unless Go vendor conversion requires them + --skip-overlays skip applying overlays to prepared sources + --skip-sources skip downloading fetched sources when preparing the package (useful to extract dist-git metadata when source files are not needed) -s, --spec-path stringArray Spec path --without-git Disable dist-git repository creation (enabled by default) ``` diff --git a/docs/user/reference/cli/azldev_component_render.md b/docs/user/reference/cli/azldev_component_render.md index 239018bd4..88a9d5157 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). -Render normally skips source downloads. Go vendoring downloads and prepares sources for archive generation -and license checks, but excludes payloads from checked-in output. Only specs, patches, scripts, checksums, -and sidecar files are included. Multiple components can be rendered at once. +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. 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/cli/azldev_config.md b/docs/user/reference/cli/azldev_config.md index 5fa5ec450..6eed54b63 100644 --- a/docs/user/reference/cli/azldev_config.md +++ b/docs/user/reference/cli/azldev_config.md @@ -37,7 +37,7 @@ JSON schema used for validating TOML config files. ### SEE ALSO -* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool 0.0.0-devel +* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool * [azldev config dump](azldev_config_dump.md) - Dump the current configuration * [azldev config generate-schema](azldev_config_generate-schema.md) - Generates JSON schema for validating .toml config files diff --git a/docs/user/reference/cli/azldev_docs.md b/docs/user/reference/cli/azldev_docs.md index 5351b11a0..787033cbb 100644 --- a/docs/user/reference/cli/azldev_docs.md +++ b/docs/user/reference/cli/azldev_docs.md @@ -37,7 +37,7 @@ command tree, suitable for inclusion in the user guide. ### SEE ALSO -* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool 0.0.0-devel +* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool * [azldev docs agent](azldev_docs_agent.md) - Emit AI agent skill and instruction files * [azldev docs markdown](azldev_docs_markdown.md) - Generates Markdown (.md) docs for this tool diff --git a/docs/user/reference/cli/azldev_image.md b/docs/user/reference/cli/azldev_image.md index 725d10144..ea678cf94 100644 --- a/docs/user/reference/cli/azldev_image.md +++ b/docs/user/reference/cli/azldev_image.md @@ -38,7 +38,7 @@ can be customized using Azure Linux Image Customizer. ### SEE ALSO -* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool 0.0.0-devel +* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool * [azldev image boot](azldev_image_boot.md) - Boot an Azure Linux image in a QEMU VM * [azldev image build](azldev_image_build.md) - Build an image using kiwi-ng * [azldev image customize](azldev_image_customize.md) - Customizes a pre-built Azure Linux image diff --git a/docs/user/reference/cli/azldev_package.md b/docs/user/reference/cli/azldev_package.md index a4e882e35..678421bcc 100644 --- a/docs/user/reference/cli/azldev_package.md +++ b/docs/user/reference/cli/azldev_package.md @@ -38,6 +38,6 @@ publish channel assignments derived from package groups and component overrides. ### SEE ALSO -* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool 0.0.0-devel +* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool * [azldev package list](azldev_package_list.md) - List resolved configuration for packages (RPMs and SRPMs) diff --git a/docs/user/reference/cli/azldev_project.md b/docs/user/reference/cli/azldev_project.md index d9c40b6c7..fef53ace7 100644 --- a/docs/user/reference/cli/azldev_project.md +++ b/docs/user/reference/cli/azldev_project.md @@ -37,7 +37,7 @@ as an Azure Linux project with a basic configuration. ### SEE ALSO -* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool 0.0.0-devel +* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool * [azldev project init](azldev_project_init.md) - Initialize the current working directory with a basic Azure Linux project config * [azldev project new](azldev_project_new.md) - Create a new Azure Linux project with basic config diff --git a/docs/user/reference/cli/azldev_repo.md b/docs/user/reference/cli/azldev_repo.md index 024cbdae6..ccbc3f5ee 100644 --- a/docs/user/reference/cli/azldev_repo.md +++ b/docs/user/reference/cli/azldev_repo.md @@ -38,7 +38,7 @@ under one or more URL prefixes. ### SEE ALSO -* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool 0.0.0-devel +* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool * [azldev repo compare](azldev_repo_compare.md) - Compare package inventories in two RPM repo sets * [azldev repo query](azldev_repo_query.md) - Run dnf against auto-discovered RPM repos diff --git a/docs/user/reference/cli/azldev_version.md b/docs/user/reference/cli/azldev_version.md index a59c7968e..5ebddbcdd 100644 --- a/docs/user/reference/cli/azldev_version.md +++ b/docs/user/reference/cli/azldev_version.md @@ -42,5 +42,5 @@ azldev version -O json ### SEE ALSO -* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool 0.0.0-devel +* [azldev](azldev.md) - 🐧 Azure Linux Dev Tool diff --git a/docs/user/reference/config/components.md b/docs/user/reference/config/components.md index a30019ea2..ce06e6f60 100644 --- a/docs/user/reference/config/components.md +++ b/docs/user/reference/config/components.md @@ -15,7 +15,6 @@ A component definition tells azldev where to find the spec file, how to customiz | Build config | `build` | [BuildConfig](#build-configuration) | No | Build-time options (macros, conditionals, check config) | | Render config | `render` | [RenderConfig](#render-configuration) | No | Options controlling spec rendering behavior | | Source files | `source-files` | array of [SourceFileReference](#source-file-references) | No | Additional source files to download for this component | -| Go vendoring | `go-vendor` | [GoVendorConfig](#go-vendoring) | No | Convert a supported Go application spec in place and generate bundled dependencies | | Package overrides | `packages` | map of string → [PackageConfig](package-groups.md#package-config) | No | Exact per-package configuration overrides; highest priority in the resolution order | | Tests | `tests` | [ComponentTests](#component-tests) | No | Test references that apply to this component (see [Tests and Test Groups](tests.md)) | @@ -166,79 +165,6 @@ skip-file-filter = true > **Note:** This should only be used for specs with macros that `spectool` cannot resolve. For most components, the default filtering behavior is correct and keeps the rendered output clean. -## Go Vendoring - -Go vendoring is opt-in and preserves the upstream spec rather than replacing it -with a generated spec. See [Vendor a Go application](../../how-to/vendor-go-application.md) -for the workflow and supported spec patterns. - -```toml -[components.example.go-vendor] -enabled = true -``` - -| TOML Key | Type | Default | Description | -|----------|------|---------|-------------| -| `enabled` | boolean | `false` | Enable conversion and vendor archive generation. An explicit `false` overrides inherited enablement. | -| `module-dir` | string | `""` | Relative directory containing `go.mod`, resolved from the working directory at the end of the upstream `%prep` section. Empty uses that directory itself. No absolute paths, traversal, or RPM macros. | -| `prep-packages` | array of string | `[]` | Additional RPM packages needed by upstream `%prep` commands or the selected license detector. Installed only in the isolated generation chroot. | -| `config-file` | string | `""` | Path to a separate [go-vendor-tools TOML file](https://fedora.gitlab.io/sigs/go/go-vendor-tools/config/), relative to the configuration file that declares it. Its contents replace upstream tool settings; they are not merged. When no file is configured, reuse an already-vendored spec's upstream settings or use tool defaults for a new conversion. | - -Custom vendor settings must live in a separate file, typically -`go-vendor-tools.toml` beside the component definition. Its contents participate -in the component fingerprint; absolute checkout paths do not. Inherited paths -retain their original declaration directory. Editing only this file makes the -lock fingerprint stale and requires the normal update/render workflow. - -```toml -# example.comp.toml -[components.example.go-vendor] -enabled = true -config-file = "go-vendor-tools.toml" -``` - -```toml -# go-vendor-tools.toml -[archive.dependency_overrides] -"example.com/dependency" = "v1.2.3" -``` - -The configured file must exist and contain valid TOML. An explicitly selected -empty file is an empty replacement, not a request to fall back to upstream. -For a new conversion, set the module location with component `module-dir`, not -`general.go_mod_dir` in the selected file. Already-vendored specs retain the -upstream module layout, honoring native `general.go_mod_dir`; non-root -`module-dir` overrides are rejected. -Configured command hooks execute in the generation chroot; treat this file as -trusted build code. The old inline `tool-config` string/table is no longer supported. - -For previously unbundled specs, preparation emits `-vendor.tar.bz2` and `azldev-go-vendor.toml`, -allocating unused `Source` numbers automatically. These names are reserved for -generated output; do not also declare them in `source-files` or supply them through -overlays. The archive's SHA-512 digest is recorded in the prepared `sources` file. -Generation runs afresh on every preparation; there is no filename-based cache. -The recorded digest identifies that output, not a separately pinned vendor lock. - -For supported specs already using go-vendor-tools, preparation instead regenerates -the existing vendor source, retaining its Source number, RPM-expanded filename, -and configuration sidecar. The Source tag is pinned to the generated filename -before release/history updates, and extraction moves after prep's module edits -to avoid applying patches twice. Ambiguous secondary-source setup and -post-extraction directory changes require a prep overlay. -It updates that archive's `sources` entry in place and -verifies the existing `License:` expression without rewriting it. -These generated archive/config filenames must not also appear in `source-files`, -including entries with `replace-upstream = true`. -When `config-file` is set, its contents are staged under the configuration filename -referenced by the prepared spec, retaining the existing Source number. Replacing -a configuration listed in upstream `sources` is unsupported and fails before generation. - -All archive/spec/loose-file overlays run before conversion. Source preparation, -builds, rendering (including `--check-only`), and source diffs use the same -conversion. Enabled components require downloads even with `--skip-sources`, -because preparation and license detection need the effective upstream sources. -`--skip-overlays` also skips conversion, leaving the upstream packaging unchanged. - ## Build Configuration The `[components..build]` section controls build-time options for a component. diff --git a/internal/app/azldev/agentskill/agentskill_test.go b/internal/app/azldev/agentskill/agentskill_test.go index ac0f49949..a263a100f 100644 --- a/internal/app/azldev/agentskill/agentskill_test.go +++ b/internal/app/azldev/agentskill/agentskill_test.go @@ -160,23 +160,6 @@ func TestComponentTomlSkillDocumentsRPMDevBumpspecPreview(t *testing.T) { assert.Contains(t, doc, "no bumpspec runtime discovery occurs") } -func TestComponentTomlSkillDocumentsGoVendoring(t *testing.T) { - for _, withoutLockfile := range []bool{false, true} { - doc, err := agentskill.NewCatalog(withoutLockfile).SkillDocument("azldev-comp-toml", testParams()) - require.NoError(t, err) - assert.Contains(t, doc, "go-vendor.enabled") - assert.Contains(t, doc, "does\nnot run `go2rpm`") - assert.Contains(t, doc, "Rendering and source diffs also generate") - assert.Contains(t, doc, "reviewed license exceptions") - assert.Contains(t, doc, `config-file = "go-vendor-tools.toml"`) - assert.Contains(t, doc, "Inline `tool-config` is not supported.") - assert.Contains(t, doc, "Upstream `general.go_mod_dir` is honored") - assert.Contains(t, doc, "non-root `module-dir` overrides fail") - assert.Contains(t, doc, "Replacing a config listed in upstream `sources` is unsupported.") - assert.Contains(t, doc, "Source filename is pinned before") - } -} - 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 d6a1de295..0def4bf59 100644 --- a/internal/app/azldev/agentskill/content/comp-toml.md.tmpl +++ b/internal/app/azldev/agentskill/content/comp-toml.md.tmpl @@ -32,35 +32,6 @@ Add sub-tables only for what you change. The fields you will reach for most: | `build.defines` / `build.with` / `build.without` | RPM macro and bcond build tweaks | | `release.calculation` | how the `Release` tag is managed | | `render.skip-file-filter` | rendering edge-case escape hatch | -| `go-vendor.enabled` | opt-in Go application spec conversion and vendor archive generation | - -## Go application vendoring - -Set `[components..go-vendor]` with `enabled = true` to preserve the upstream -spec while converting supported application packaging to bundled modules. -Preparation runs the patched upstream `%prep` before `go_vendor_archive`; it does -not run `go2rpm`. Rendering and source diffs also generate the vendor archive and -require downloads. Review the generated cumulative `License:` expression. - -Use `module-dir` for a module below the final prep working directory, -`prep-packages` for additional chroot tools, and `config-file = "go-vendor-tools.toml"` -for custom settings in a separate native TOML file beside the component definition. -Keep reviewed license exceptions in that file. -The path is relative to the declaring config, and file contents are fingerprinted. -It replaces upstream settings without merging; an explicit empty file is still a -replacement, and a missing file is an error. Inline `tool-config` is not supported. -Generated `-vendor.tar.bz2` and `azldev-go-vendor.toml` must not also be -declared as `source-files`. For supported already-vendored specs, regenerate the -existing vendor Source instead, reuse upstream tool configuration unless overridden, -and verify rather than replace the reviewed `License:` expression. -The regenerated archive and configuration must not also be `source-files` entries. -Upstream `general.go_mod_dir` is honored; non-root `module-dir` overrides fail -for already-vendored specs. Replacing a config listed in upstream `sources` is unsupported. -Vendor extraction runs after prep edits, and its Source filename is pinned before -release/history updates. Ambiguous secondary-source setup requires an overlay. -Unsupported constructs (notably automatic Go devel -subpackages, flagged `%gocheck`, or ambiguous sections) require explicit overlays; -never replace the upstream spec wholesale to bypass a conversion error. ## Spec source 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 7a884e086..0e33a9e6d 100644 --- a/internal/app/azldev/agentskill/content/withoutlockfile/comp-toml.md.tmpl +++ b/internal/app/azldev/agentskill/content/withoutlockfile/comp-toml.md.tmpl @@ -32,35 +32,6 @@ Add sub-tables only for what you change. The fields you will reach for most: | `build.defines` / `build.with` / `build.without` | RPM macro and bcond build tweaks | | `release.calculation` | how the `Release` tag is managed | | `render.skip-file-filter` | rendering edge-case escape hatch | -| `go-vendor.enabled` | opt-in Go application spec conversion and vendor archive generation | - -## Go application vendoring - -Set `[components..go-vendor]` with `enabled = true` to preserve the upstream -spec while converting supported application packaging to bundled modules. -Preparation runs the patched upstream `%prep` before `go_vendor_archive`; it does -not run `go2rpm`. Rendering and source diffs also generate the vendor archive and -require downloads. Review the generated cumulative `License:` expression. - -Use `module-dir` for a module below the final prep working directory, -`prep-packages` for additional chroot tools, and `config-file = "go-vendor-tools.toml"` -for custom settings in a separate native TOML file beside the component definition. -Keep reviewed license exceptions in that file. -The path is relative to the declaring config, and file contents are fingerprinted. -It replaces upstream settings without merging; an explicit empty file is still a -replacement, and a missing file is an error. Inline `tool-config` is not supported. -Generated `-vendor.tar.bz2` and `azldev-go-vendor.toml` must not also be -declared as `source-files`. For supported already-vendored specs, regenerate the -existing vendor Source instead, reuse upstream tool configuration unless overridden, -and verify rather than replace the reviewed `License:` expression. -The regenerated archive and configuration must not also be `source-files` entries. -Upstream `general.go_mod_dir` is honored; non-root `module-dir` overrides fail -for already-vendored specs. Replacing a config listed in upstream `sources` is unsupported. -Vendor extraction runs after prep edits, and its Source filename is pinned before -release/history updates. Ambiguous secondary-source setup requires an overlay. -Unsupported constructs (notably automatic Go devel -subpackages, flagged `%gocheck`, or ambiguous sections) require explicit overlays; -never replace the upstream spec wholesale to bypass a conversion error. ## Spec source diff --git a/internal/app/azldev/cmds/component/build.go b/internal/app/azldev/cmds/component/build.go index f2d955277..2c9f99171 100644 --- a/internal/app/azldev/cmds/component/build.go +++ b/internal/app/azldev/cmds/component/build.go @@ -288,7 +288,7 @@ func buildComponent( preparerOpts = append(preparerOpts, sources.WithMockProcessor(mockProcessor)) - sourcePreparer, err := newComponentSourcePreparer(env, component, sourceManager, options.MockConfigOpts, append( + sourcePreparer, err := newSourcePreparer(sourceManager, env.FS(), env, env, append( preparerOpts, sources.WithSpecEditor(options.specEditorMode()), )...) diff --git a/internal/app/azldev/cmds/component/changed_upstreamcommit.go b/internal/app/azldev/cmds/component/changed_upstreamcommit.go index ce18e0d5e..ce8e19ebc 100644 --- a/internal/app/azldev/cmds/component/changed_upstreamcommit.go +++ b/internal/app/azldev/cmds/component/changed_upstreamcommit.go @@ -118,7 +118,6 @@ type componentComparisonInputs struct { Config projectconfig.ComponentConfig `json:"config"` SourceIdentity string `json:"sourceIdentity,omitempty"` OverlaySourceHashes map[string]string `json:"overlaySourceHashes,omitempty"` - GoVendorConfigHash string `json:"goVendorConfigHash,omitempty"` ReleaseVer string `json:"releaseVer,omitempty"` } @@ -253,13 +252,6 @@ func buildComponentComparisonInputs( SourceIdentity: component.EffectiveUpstreamCommit(), } - var err error - - inputs.GoVendorConfigHash, err = component.GoVendor.SourceContentIdentity(fs) - if err != nil { - return inputs, fmt.Errorf("hashing Go vendor configuration:\n%w", err) - } - if component.Spec.SourceType == projectconfig.SpecSourceTypeLocal { identity, err := sourceproviders.ResolveLocalSourceIdentity( fs, filepath.Dir(component.Spec.Path), @@ -322,13 +314,7 @@ func normalizeComponentForComparison(component projectconfig.ComponentConfig) pr normalized.Build.Hints = projectconfig.ComponentBuildHints{} normalized.OverlayFiles = nil normalized.Publish = projectconfig.ComponentPublishConfig{} - normalized.Tests = nil - if component.GoVendor != nil { - vendor := *component.GoVendor - vendor.ConfigFile = "" - normalized.GoVendor = &vendor - } normalized.Overlays = slices.Clone(component.Overlays) for idx := range normalized.Overlays { diff --git a/internal/app/azldev/cmds/component/changed_upstreamcommit_internal_test.go b/internal/app/azldev/cmds/component/changed_upstreamcommit_internal_test.go index 1680f2088..357f3321b 100644 --- a/internal/app/azldev/cmds/component/changed_upstreamcommit_internal_test.go +++ b/internal/app/azldev/cmds/component/changed_upstreamcommit_internal_test.go @@ -209,28 +209,6 @@ func TestBuildComponentComparisonInputs_ContentIdentities(t *testing.T) { assert.NotEqual(t, second.OverlaySourceHashes, third.OverlaySourceHashes) } -func TestBuildComponentComparisonInputs_GoVendorFile(t *testing.T) { - env := testutils.NewTestEnvWithoutLockfile(t) - enabled := true - component := projectconfig.ComponentConfig{GoVendor: &projectconfig.GoVendorConfig{ - Enabled: &enabled, ConfigFile: "/project/vendor.toml", - }} - require.NoError(t, fileutils.WriteFile(env.FS(), component.GoVendor.ConfigFile, - []byte("[archive]\ntidy = false\n"), fileperms.PublicFile)) - first, err := buildComponentComparisonInputs(env.FS(), env.Env, &component) - require.NoError(t, err) - assert.Empty(t, first.Config.GoVendor.ConfigFile) - assert.Equal(t, "/project/vendor.toml", component.GoVendor.ConfigFile) - require.NotEmpty(t, first.GoVendorConfigHash) - - require.NoError(t, fileutils.WriteFile(env.FS(), component.GoVendor.ConfigFile, - []byte("[archive]\ntidy = true\n"), fileperms.PublicFile)) - second, err := buildComponentComparisonInputs(env.FS(), env.Env, &component) - require.NoError(t, err) - assert.NotEqual(t, first.GoVendorConfigHash, second.GoVendorConfigHash) - assert.Equal(t, first.Config, second.Config) -} - func TestLoadHistoricalProject_UsesNormalIncludesAndMerging(t *testing.T) { rootConfig := []byte(`includes = [ "config/components.toml", diff --git a/internal/app/azldev/cmds/component/diffsources.go b/internal/app/azldev/cmds/component/diffsources.go index 24a2dd370..7fd728050 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 := newComponentSourcePreparer(env, component, sourceManager, nil, + preparer, err := newSourcePreparer(sourceManager, env.FS(), env, env, 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 8a051a54d..2e90e7eb3 100644 --- a/internal/app/azldev/cmds/component/history_customizations.go +++ b/internal/app/azldev/cmds/component/history_customizations.go @@ -29,31 +29,6 @@ func collectCustomizations(name string, config *projectconfig.ComponentConfig) [ items = appendRenderItems(items, config.Render) items = appendPackageItems(items, config.Packages) items = appendSourceFileItems(items, config.SourceFiles) - items = appendGoVendorItems(items, config.GoVendor) - - return items -} - -func appendGoVendorItems(items []CustomizationItem, config *projectconfig.GoVendorConfig) []CustomizationItem { - if config == nil { - return items - } - - if config.Enabled != nil { - items = append(items, CustomizationItem{Kind: "go-vendor.enabled", Value: strconv.FormatBool(*config.Enabled)}) - } - - if config.ModuleDir != "" { - items = append(items, CustomizationItem{Kind: "go-vendor.module-dir", Value: config.ModuleDir}) - } - - if config.ConfigFile != "" { - items = append(items, CustomizationItem{Kind: "go-vendor.config-file", Value: config.ConfigFile}) - } - - for _, name := range config.PrepPackages { - items = append(items, CustomizationItem{Kind: "go-vendor.prep-packages", Value: name}) - } return items } diff --git a/internal/app/azldev/cmds/component/history_internal_test.go b/internal/app/azldev/cmds/component/history_internal_test.go index 858d509f3..242094194 100644 --- a/internal/app/azldev/cmds/component/history_internal_test.go +++ b/internal/app/azldev/cmds/component/history_internal_test.go @@ -88,7 +88,6 @@ func TestCustomizationCollectorsCoverEveryFingerprintableField(t *testing.T) { reflect.TypeFor[projectconfig.ComponentRenderConfig](), reflect.TypeFor[projectconfig.SourceFileReference](), reflect.TypeFor[projectconfig.Origin](), - reflect.TypeFor[projectconfig.GoVendorConfig](), } // Maps "StructName.FieldName" -> short note describing how the field @@ -104,10 +103,6 @@ func TestCustomizationCollectorsCoverEveryFingerprintableField(t *testing.T) { "ComponentConfig.Render": "appendRenderItems (per-field via ComponentRenderConfig walk)", "ComponentConfig.SourceFiles": "appendSourceFileItems (opaque unit per source file)", "ComponentConfig.Packages": "appendPackageItems (opaque unit per package override)", - "ComponentConfig.GoVendor": "appendGoVendorItems", - "GoVendorConfig.Enabled": "go-vendor.enabled", - "GoVendorConfig.ModuleDir": "go-vendor.module-dir", - "GoVendorConfig.PrepPackages": "go-vendor.prep-packages", // ComponentBuildConfig. "ComponentBuildConfig.With": "build.with", diff --git a/internal/app/azldev/cmds/component/preparerctx.go b/internal/app/azldev/cmds/component/preparerctx.go index 777ff4c73..f98f7b671 100644 --- a/internal/app/azldev/cmds/component/preparerctx.go +++ b/internal/app/azldev/cmds/component/preparerctx.go @@ -4,37 +4,11 @@ package component import ( - "errors" - "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" - "github.com/microsoft/azure-linux-dev-tools/internal/rpm/mock" ) -func goVendorPreparerOptions( - env *azldev.Env, component components.Component, mockConfigOpts map[string]string, -) ([]sources.PreparerOption, error) { - if !component.GetConfig().GoVendor.IsEnabled() || env.DryRun() { - return nil, nil - } - - _, distro, err := env.Distro() - if err != nil { - return nil, fmt.Errorf("resolving Go vendor build distro:\n%w", err) - } - - if distro.MockConfigPath == "" { - return nil, errors.New("go vendoring requires a project distro with a mock configuration") - } - - runner := mock.NewRunner(env, distro.MockConfigPath).WithConfigOpts(mockConfigOpts) - - return []sources.PreparerOption{sources.WithGoVendorRunner(runner)}, 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/preparerctx_internal_test.go b/internal/app/azldev/cmds/component/preparerctx_internal_test.go deleted file mode 100644 index 715286b8f..000000000 --- a/internal/app/azldev/cmds/component/preparerctx_internal_test.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -package component - -import ( - "testing" - - "github.com/microsoft/azure-linux-dev-tools/internal/app/azldev/core/components/components_testutils" - "github.com/microsoft/azure-linux-dev-tools/internal/app/azldev/core/testutils" - "github.com/microsoft/azure-linux-dev-tools/internal/projectconfig" - "github.com/samber/lo" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "go.uber.org/mock/gomock" -) - -func TestGoVendorPreparerOptions(t *testing.T) { - const disabled = "disabled" - for _, mode := range []string{"enabled", disabled, "missing-mock", "missing-distro"} { - t.Run(mode, func(t *testing.T) { - env := testutils.NewTestEnv(t) - component := components_testutils.NewMockComponent(gomock.NewController(t)) - component.EXPECT().GetConfig().AnyTimes().Return(&projectconfig.ComponentConfig{ - GoVendor: &projectconfig.GoVendorConfig{Enabled: lo.ToPtr(mode != disabled)}, - }) - - switch mode { - case "missing-mock", disabled: - clearProjectMockConfig(env.Env.Config()) - case "missing-distro": - env.Env.Config().Project.DefaultDistro.Name = "absent" - } - - options, err := goVendorPreparerOptions(env.Env, component, nil) - - switch mode { - case "enabled": - require.NoError(t, err) - require.Len(t, options, 1) - case disabled: - require.NoError(t, err) - assert.Empty(t, options) - default: - require.Error(t, err) - assert.Empty(t, options) - } - }) - } -} - -func TestGoVendorHistoryCustomizations(t *testing.T) { - config := &projectconfig.GoVendorConfig{ - Enabled: lo.ToPtr(true), ModuleDir: "cmd/app", - ConfigFile: "/project/go-vendor-tools.toml", PrepPackages: []string{"git"}, - } - assert.Equal(t, []CustomizationItem{ - {Kind: "go-vendor.enabled", Value: "true"}, - {Kind: "go-vendor.module-dir", Value: "cmd/app"}, - {Kind: "go-vendor.config-file", Value: config.ConfigFile}, - {Kind: "go-vendor.prep-packages", Value: "git"}, - }, collectCustomizations("app", &projectconfig.ComponentConfig{GoVendor: config})) - assert.Empty(t, appendGoVendorItems(nil, &projectconfig.GoVendorConfig{})) -} diff --git a/internal/app/azldev/cmds/component/preparesources.go b/internal/app/azldev/cmds/component/preparesources.go index 37b9668c8..317b7fb38 100644 --- a/internal/app/azldev/cmds/component/preparesources.go +++ b/internal/app/azldev/cmds/component/preparesources.go @@ -73,8 +73,7 @@ Only one component may be selected at a time.`, _ = cmd.MarkFlagRequired("output-dir") _ = cmd.MarkFlagDirname("output-dir") - cmd.Flags().BoolVar(&options.SkipOverlays, "skip-overlays", false, - "skip overlays and Go vendor conversion, preserving upstream packaging") + cmd.Flags().BoolVar(&options.SkipOverlays, "skip-overlays", false, "skip applying overlays to prepared sources") cmd.Flags().BoolVar(&options.WithoutGitRepo, "without-git", false, "Disable dist-git repository creation (enabled by default)") addRPMDevBumpspecFlag(cmd, &options.RPMDevBumpspec) @@ -83,7 +82,8 @@ Only one component may be selected at a time.`, cmd.Flags().BoolVar(&options.AllowNoHashes, "allow-no-hashes", false, "compute missing hashes by downloading source files from their origin") cmd.Flags().BoolVar(&options.SkipSources, "skip-sources", false, - "skip downloading sources unless Go vendor conversion requires them") + "skip downloading fetched sources when preparing the package (useful to extract "+ + "dist-git metadata when source files are not needed)") return cmd } @@ -142,14 +142,6 @@ func PrepareComponentSources(env *azldev.Env, options *PrepareSourcesOptions) er } preparerOpts := buildPreparerOptions(env, distro, options) - if !options.SkipOverlays { - vendorOpts, err := goVendorPreparerOptions(env, component, nil) - if err != nil { - return err - } - - preparerOpts = append(preparerOpts, vendorOpts...) - } preparer, err := newSourcePreparer(sourceManager, env.FS(), env, env, append( preparerOpts, diff --git a/internal/app/azldev/cmds/component/render.go b/internal/app/azldev/cmds/component/render.go index e9df2be13..ff99942bd 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). -Render normally skips source downloads. Go vendoring downloads and prepares sources for archive generation -and license checks, but excludes payloads from checked-in output. Only specs, patches, scripts, checksums, -and sidecar files are included. Multiple components can be rendered at once. +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. When rendering all components (-a), the --clean-stale flag prunes orphan rendered-spec directories (per-component dirs that no longer correspond to @@ -531,8 +531,8 @@ func prepareComponentSources( // Prepare sources with overlays, skipping lookaside downloads. // WithGitRepo preserves upstream .git and creates synthetic history so // rpmautospec can expand %autorelease and %autochangelog correctly. - // WithSkipLookaside avoids tarball downloads unless Go vendoring requires - // the prepared sources to generate the archive and cumulative license. + // WithSkipLookaside avoids expensive tarball downloads — only spec + + // sidecar files are needed for rendering. preparerOpts := append(gitRepoPreparerOptions(env, distro), sources.WithSkipLookaside(), sources.WithUpstreamProvenance(sources.FedoraDistTag(distro.Ref.Name, distro.Version.ReleaseVer)), @@ -542,7 +542,7 @@ func prepareComponentSources( preparerOpts = append(preparerOpts, sources.WithRPMDevBumpspec(env, env.WorkDir(), "")) } - preparer, err := newComponentSourcePreparer(env, comp, sourceManager, nil, append( + preparer, err := newSourcePreparer(sourceManager, env.FS(), env, env, append( preparerOpts, sources.WithSpecEditor(specEditor), )...) @@ -765,12 +765,6 @@ func finishComponentRender( return false, fmt.Errorf("filtering unreferenced files for %#q:\n%w", componentName, filterErr) } - if err := removeGoVendorRenderPayloads( - env.FS(), componentDir, prep.comp.GetConfig().GoVendor.IsEnabled(), - ); err != nil { - return false, fmt.Errorf("removing generated render payloads for %#q:\n%w", componentName, err) - } - // Remove .git directory — must not appear in rendered output. // rpmautospec already read it during the batch mock phase. gitDir := filepath.Join(componentDir, ".git") diff --git a/internal/app/azldev/cmds/component/render_govendor.go b/internal/app/azldev/cmds/component/render_govendor.go deleted file mode 100644 index bcfae2005..000000000 --- a/internal/app/azldev/cmds/component/render_govendor.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -package component - -import ( - "errors" - "fmt" - "os" - "path/filepath" - - "github.com/microsoft/azure-linux-dev-tools/internal/global/opctx" - "github.com/microsoft/azure-linux-dev-tools/internal/providers/sourceproviders/fedorasource" - "github.com/microsoft/azure-linux-dev-tools/internal/utils/fileutils" -) - -// Vendoring needs real payloads during preparation, but rendered dist-git output -// must contain their manifest rather than copying source archives into the repository. -func removeGoVendorRenderPayloads(fs opctx.FS, directory string, enabled bool) error { - if !enabled { - return nil - } - - contents, err := fileutils.ReadFile(fs, filepath.Join(directory, fedorasource.SourcesFileName)) - if errors.Is(err, os.ErrNotExist) { - return nil - } - - if err != nil { - return fmt.Errorf("reading render source manifest:\n%w", err) - } - - lines, err := fedorasource.ReadSourcesFile(string(contents)) - if err != nil { - return fmt.Errorf("parsing render source manifest:\n%w", err) - } - - for _, line := range lines { - if line.Entry == nil { - continue - } - - if err := fileutils.ValidateFilename(line.Entry.Filename); err != nil { - return fmt.Errorf("invalid render source filename:\n%w", err) - } - - if err := fs.Remove(filepath.Join(directory, line.Entry.Filename)); err != nil && !errors.Is(err, os.ErrNotExist) { - return fmt.Errorf("removing render source payload %#q:\n%w", line.Entry.Filename, err) - } - } - - return nil -} diff --git a/internal/app/azldev/cmds/component/render_govendor_internal_test.go b/internal/app/azldev/cmds/component/render_govendor_internal_test.go deleted file mode 100644 index e6b336335..000000000 --- a/internal/app/azldev/cmds/component/render_govendor_internal_test.go +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -package component - -import ( - "strings" - "testing" - - "github.com/microsoft/azure-linux-dev-tools/internal/global/testctx" - "github.com/microsoft/azure-linux-dev-tools/internal/providers/sourceproviders/fedorasource" - "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 TestRemoveGoVendorRenderPayloads(t *testing.T) { - for _, enabled := range []bool{false, true} { - ctx := testctx.NewCtx() - - manifest := "# keep manifest\n" + - fedorasource.FormatSourcesEntry("upstream.tar.gz", fileutils.HashTypeSHA512, strings.Repeat("a", 128)) + "\n" + - fedorasource.FormatSourcesEntry("vendor.tar.bz2", fileutils.HashTypeSHA512, strings.Repeat("b", 128)) + "\n" - for name, content := range map[string]string{ - "app.spec": "spec", "config.toml": "[archive]", "sources": manifest, - "upstream.tar.gz": "source", "vendor.tar.bz2": "vendor", - } { - require.NoError(t, fileutils.WriteFile(ctx.FS(), "/render/"+name, []byte(content), fileperms.PublicFile)) - } - - require.NoError(t, removeGoVendorRenderPayloads(ctx.FS(), "/render", enabled)) - - for _, name := range []string{"upstream.tar.gz", "vendor.tar.bz2"} { - exists, err := fileutils.Exists(ctx.FS(), "/render/"+name) - require.NoError(t, err) - assert.Equal(t, !enabled, exists) - } - - for _, name := range []string{"app.spec", "config.toml", "sources"} { - exists, err := fileutils.Exists(ctx.FS(), "/render/"+name) - require.NoError(t, err) - assert.True(t, exists) - } - - data, err := fileutils.ReadFile(ctx.FS(), "/render/sources") - require.NoError(t, err) - assert.Equal(t, manifest, string(data)) - require.NoError(t, removeGoVendorRenderPayloads(ctx.FS(), "/render", enabled)) - } -} diff --git a/internal/app/azldev/cmds/component/sourcepreparer.go b/internal/app/azldev/cmds/component/sourcepreparer.go index a13890267..a16e0a00c 100644 --- a/internal/app/azldev/cmds/component/sourcepreparer.go +++ b/internal/app/azldev/cmds/component/sourcepreparer.go @@ -3,24 +3,7 @@ package component -import ( - "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" -) +import "github.com/microsoft/azure-linux-dev-tools/internal/app/azldev/core/sources" //nolint:gochecknoglobals // Replaced by isolated command tests to observe constructed source preparers. var newSourcePreparer = sources.NewPreparer - -func newComponentSourcePreparer( - env *azldev.Env, component components.Component, manager sourceproviders.SourceManager, - mockConfigOpts map[string]string, options ...sources.PreparerOption, -) (sources.SourcePreparer, error) { - vendorOpts, err := goVendorPreparerOptions(env, component, mockConfigOpts) - if err != nil { - return nil, err - } - - return newSourcePreparer(manager, env.FS(), env, env, append(options, vendorOpts...)...) -} diff --git a/internal/app/azldev/core/sources/govendor.go b/internal/app/azldev/core/sources/govendor.go deleted file mode 100644 index 708c3d074..000000000 --- a/internal/app/azldev/core/sources/govendor.go +++ /dev/null @@ -1,267 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -package sources - -import ( - "context" - "errors" - "fmt" - "log/slog" - "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 provides a template for an isolated generation root. -func WithGoVendorRunner(runner *mock.Runner) PreparerOption { - return func(p *sourcePreparerImpl) { p.goVendorRunner = runner } -} - -func (p *sourcePreparerImpl) prepareGoVendor( - ctx context.Context, component components.Component, outputDir string, -) (err error) { - config := component.GetConfig().GoVendor - if !config.IsEnabled() { - return nil - } - - if err := config.Validate(); err != nil { - return fmt.Errorf("invalid Go vendor configuration:\n%w", err) - } - - if p.dryRunnable.DryRun() { - slog.Info("Dry run; skipping Go vendor generation", "component", component.GetName()) - - return nil - } - - if p.goVendorRunner == nil { - return errors.New("go vendoring requires a mock runner with the project's build distro configuration") - } - - specPath, err := p.resolveSpecPath(component, outputDir) - if err != nil { - return err - } - - data, err := fileutils.ReadFile(p.fs, specPath) - if err != nil { - return fmt.Errorf("reading Go spec:\n%w", err) - } - - plan, err := spec.ConvertGoVendor(data, spec.GoVendorOptions{ - ArchiveName: component.GetName() + "-vendor.tar.bz2", - ConfigName: govendor.ConfigFilename, ModuleDir: config.ModuleDir, - }) - if err != nil { - return fmt.Errorf("planning Go vendoring for %#q:\n%w", component.GetName(), err) - } - - toolConfig, err := p.resolveGoVendorConfig(outputDir, plan, config) - if err != nil { - return err - } - - scratch, err := fileutils.MkdirTempInTempDir(p.fs, "azldev-go-vendor-*") - if err != nil { - return fmt.Errorf("creating Go vendor scratch directory:\n%w", err) - } - defer fileutils.RemoveAllAndUpdateErrorIfNil(p.fs, scratch, &err) - - slog.Info("Generating Go vendor archive", "spec", filepath.Base(specPath), "regenerating", plan.AllowReplacement) - - artifact, err := govendor.Generate(ctx, p.fs, p.goVendorRunner, govendor.Request{ - SourceDir: outputDir, WorkDir: scratch, SpecName: filepath.Base(specPath), PrepSpec: plan.PrepSpec, - ArchiveFile: plan.ArchiveFile, ArchiveSuffix: plan.ArchiveSuffix, ModuleDir: config.ModuleDir, - ConfigContents: toolConfig, Packages: config.PrepPackages, ExpectedLicense: plan.ExpectedLicense, - }) - if err != nil { - return fmt.Errorf("generating Go vendor sources:\n%w", err) - } - - for _, ref := range component.GetConfig().SourceFiles { - if ref.Filename == artifact.Name || ref.Filename == plan.ConfigName { - return fmt.Errorf("'source-files' entry %#q conflicts with generated Go vendor sources", ref.Filename) - } - } - - return p.publishGoVendor(outputDir, filepath.Base(specPath), toolConfig, plan, artifact) -} - -func (p *sourcePreparerImpl) resolveGoVendorConfig( - outputDir string, plan *spec.GoVendorSpec, config *projectconfig.GoVendorConfig, -) (string, error) { - if !plan.AllowReplacement { - if err := p.checkGoVendorSourceCollision(outputDir, plan.ArchiveFile, plan.ConfigName); err != nil { - return "", err - } - } - - if config.ConfigFile != "" { - if plan.AllowReplacement { - if err := p.checkGoVendorManifestCollision(outputDir, plan.ConfigName); err != nil { - return "", err - } - } - - content, err := config.ReadConfigFile(p.fs) - if err != nil { - return "", fmt.Errorf("loading Go vendor configuration:\n%w", err) - } - - return content, nil - } - - if !plan.AllowReplacement { - return "", nil - } - - data, err := fileutils.ReadFile(p.fs, filepath.Join(outputDir, plan.ConfigName)) - if err != nil { - return "", fmt.Errorf("reading upstream Go vendor configuration:\n%w", err) - } - - return string(data), nil -} - -func (p *sourcePreparerImpl) publishGoVendor( - outputDir, specName, toolConfig string, plan *spec.GoVendorSpec, artifact govendor.Artifact, -) error { - if !plan.AllowReplacement && artifact.Name != plan.ArchiveFile { - return fmt.Errorf("generated Go archive %#q does not match planned name %#q", artifact.Name, plan.ArchiveFile) - } - - finalSpec, err := plan.Finalize(artifact.Name, artifact.License) - if err != nil { - return fmt.Errorf("finalizing Go vendor spec:\n%w", err) - } - - if err := fileutils.CopyFile(p.dryRunnable, p.fs, artifact.Path, - filepath.Join(outputDir, artifact.Name), fileutils.CopyFileOptions{}); err != nil { - return fmt.Errorf("publishing Go vendor archive:\n%w", err) - } - - for name, contents := range map[string][]byte{specName: finalSpec, plan.ConfigName: []byte(toolConfig)} { - if err := fileutils.WriteFile(p.fs, filepath.Join(outputDir, name), contents, fileperms.PublicFile); err != nil { - return fmt.Errorf("publishing Go vendor file %#q:\n%w", name, err) - } - } - - return p.recordGoVendorArchive(outputDir, artifact, plan.AllowReplacement) -} - -func (p *sourcePreparerImpl) checkGoVendorSourceCollision(outputDir string, names ...string) error { - for _, name := range names { - exists, err := fileutils.Exists(p.fs, filepath.Join(outputDir, name)) - if err != nil { - return fmt.Errorf("checking generated Go source path:\n%w", err) - } - - if exists { - return fmt.Errorf("generated Go vendor file %#q conflicts with an existing source", name) - } - } - - return p.checkGoVendorManifestCollision(outputDir, names...) -} - -func (p *sourcePreparerImpl) checkGoVendorManifestCollision(outputDir string, names ...string) error { - content, err := p.readSourcesFileIfExists(filepath.Join(outputDir, fedorasource.SourcesFileName)) - if err != nil { - return err - } - - lines, err := fedorasource.ReadSourcesFile(content) - if err != nil { - return fmt.Errorf("reading Go vendor 'sources' entries:\n%w", err) - } - - for _, line := range lines { - if line.Entry != nil && slices.Contains(names, line.Entry.Filename) { - return fmt.Errorf("generated Go vendor file %#q conflicts with an upstream 'sources' entry", line.Entry.Filename) - } - } - - return nil -} - -func (p *sourcePreparerImpl) recordGoVendorArchive(outputDir string, artifact govendor.Artifact, replace bool) error { - path := filepath.Join(outputDir, fedorasource.SourcesFileName) - - content, err := p.readSourcesFileIfExists(path) - if err != nil { - return err - } - - content, err = upsertGoVendorEntry(content, artifact, replace) - if err != nil { - return err - } - - if err := fileutils.WriteFile(p.fs, path, []byte(content), fileperms.PublicFile); err != nil { - return fmt.Errorf("recording Go vendor digest:\n%w", err) - } - - slog.Info("Recorded generated Go vendor archive", "filename", artifact.Name, - "hashType", fileutils.HashTypeSHA512, "hash", artifact.Digest) - - ignorePath := filepath.Join(outputDir, ".gitignore") - - ignore, err := p.readSourcesFileIfExists(ignorePath) - if err != nil { - return err - } - - for _, line := range strings.Split(ignore, "\n") { - if strings.TrimPrefix(line, "/") == artifact.Name { - return nil - } - } - - if err := fileutils.WriteFile(p.fs, ignorePath, - []byte(strings.TrimRight(ignore, "\n")+"\n/"+artifact.Name+"\n"), fileperms.PublicFile); err != nil { - return fmt.Errorf("ignoring generated Go archive in git:\n%w", err) - } - - return nil -} - -func upsertGoVendorEntry(content string, artifact govendor.Artifact, replace bool) (string, error) { - lines, err := fedorasource.ReadSourcesFile(strings.TrimRight(content, "\n")) - if err != nil { - return "", fmt.Errorf("parsing Go vendor source manifest:\n%w", err) - } - - entry := fedorasource.FormatSourcesEntry(artifact.Name, fileutils.HashTypeSHA512, artifact.Digest) - raw := make([]string, 0, len(lines)+1) - found := false - - for _, line := range lines { - value := line.Raw - if line.Entry != nil && line.Entry.Filename == artifact.Name { - if !replace { - return "", fmt.Errorf("go vendor source %#q already exists", artifact.Name) - } - - value, found = entry, true - } - - raw = append(raw, value) - } - - if !found { - raw = append(raw, entry) - } - - return strings.Join(raw, "\n") + "\n", nil -} diff --git a/internal/app/azldev/core/sources/govendor_config_internal_test.go b/internal/app/azldev/core/sources/govendor_config_internal_test.go deleted file mode 100644 index 0e74d02ea..000000000 --- a/internal/app/azldev/core/sources/govendor_config_internal_test.go +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -package sources - -import ( - "strings" - "testing" - - "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/providers/sourceproviders/fedorasource" - "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" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestGoVendorConfigFileSelection(t *testing.T) { - for _, local := range []string{"", "[archive]\ntidy = false\n"} { - ctx := testctx.NewCtx() - require.NoError(t, fileutils.WriteFile(ctx.FS(), "/prepared/upstream.toml", - []byte("[licensing]\ndetector = 'askalono'\n"), fileperms.PublicFile)) - require.NoError(t, fileutils.WriteFile(ctx.FS(), "/project/local.toml", []byte(local), fileperms.PublicFile)) - preparer := &sourcePreparerImpl{fs: ctx.FS()} - plan := &spec.GoVendorSpec{AllowReplacement: true, ConfigName: "upstream.toml"} - config := &projectconfig.GoVendorConfig{ConfigFile: "/project/local.toml"} - actual, err := preparer.resolveGoVendorConfig("/prepared", plan, config) - require.NoError(t, err) - assert.Equal(t, local, actual, "explicit file replaces rather than merges upstream settings") - - config.ConfigFile = "" - actual, err = preparer.resolveGoVendorConfig("/prepared", plan, config) - require.NoError(t, err) - assert.Contains(t, actual, "askalono") - - config.ConfigFile = "/project/missing.toml" - _, err = preparer.resolveGoVendorConfig("/prepared", plan, config) - require.Error(t, err, "missing explicit file must not fall back to upstream") - assert.Contains(t, err.Error(), config.ConfigFile) - } -} - -func TestGoVendorRejectsLookasideConfigReplacement(t *testing.T) { - ctx := testctx.NewCtx() - - const upstream = "[archive]\ntidy = true\n" - - entry := fedorasource.FormatSourcesEntry("upstream.toml", fileutils.HashTypeSHA512, strings.Repeat("a", 128)) - for path, content := range map[string]string{ - "/prepared/upstream.toml": upstream, - "/prepared/sources": entry + "\n", - "/project/local.toml": "[archive]\ntidy = false\n", - } { - require.NoError(t, fileutils.WriteFile(ctx.FS(), path, []byte(content), fileperms.PublicFile)) - } - - preparer := &sourcePreparerImpl{fs: ctx.FS()} - plan := &spec.GoVendorSpec{AllowReplacement: true, ConfigName: "upstream.toml"} - config := &projectconfig.GoVendorConfig{ConfigFile: "/project/local.toml"} - _, err := preparer.resolveGoVendorConfig("/prepared", plan, config) - require.ErrorContains(t, err, "'sources' entry") - data, err := fileutils.ReadFile(ctx.FS(), "/prepared/upstream.toml") - require.NoError(t, err) - assert.Equal(t, upstream, string(data)) - - config.ConfigFile = "" - actual, err := preparer.resolveGoVendorConfig("/prepared", plan, config) - require.NoError(t, err) - assert.Equal(t, upstream, actual, "unchanged upstream settings remain supported") -} diff --git a/internal/app/azldev/core/sources/govendor_existing_internal_test.go b/internal/app/azldev/core/sources/govendor_existing_internal_test.go deleted file mode 100644 index 3ab85fd8a..000000000 --- a/internal/app/azldev/core/sources/govendor_existing_internal_test.go +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -package sources - -import ( - "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/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/utils/fileperms" - "github.com/microsoft/azure-linux-dev-tools/internal/utils/fileutils" - "github.com/samber/lo" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "go.uber.org/mock/gomock" -) - -func TestPrepareExistingGoVendorReplacesPayload(t *testing.T) { - for _, conflict := range []string{"", "app-1.2-vendor.tar.bz2", "go-vendor-tools.toml"} { - t.Run("source-file-"+conflict, func(t *testing.T) { - testPrepareExistingGoVendor(t, conflict) - }) - } -} - -func testPrepareExistingGoVendor(t *testing.T, conflict string) { - t.Helper() - - ctx := newMockProcessorTestCtx() - component := components_testutils.NewMockComponent(gomock.NewController(t)) - component.EXPECT().GetName().AnyTimes().Return("app") - - config := &projectconfig.ComponentConfig{ - GoVendor: &projectconfig.GoVendorConfig{Enabled: lo.ToPtr(true)}, - } - if conflict != "" { - config.SourceFiles = []projectconfig.SourceFileReference{{ - Filename: conflict, ReplaceUpstream: true, Hash: strings.Repeat("a", 128), HashType: fileutils.HashTypeSHA512, - }} - } - - component.EXPECT().GetConfig().AnyTimes().Return(config) - - input := strings.Join([]string{ - "Name: app", "Version: 1.2", "Release: 1", "License: MIT AND Apache-2.0", - "Source0: app.tar.gz", "Source1: app-%{version}-vendor.tar.bz2", "Source2: go-vendor-tools.toml", - "%description", "app", "%prep", "%goprep", "tar -xf %{S:1}", - "%build", "%global gomodulesmode GO111MODULE=on", "%gobuild -o app .", - "%install", "%go_vendor_license_install -c %{S:2}", - "%files -f %{go_vendor_license_filelist}", "/usr/bin/app", "", - }, "\n") - - const ( - archiveName = "app-1.2-vendor.tar.bz2" - upstreamConfig = "[licensing]\ndetector = 'askalono'\n" - ) - - oldEntry := fedorasource.FormatSourcesEntry(archiveName, fileutils.HashTypeSHA512, strings.Repeat("a", 128)) - for name, data := range map[string]string{ - "app.spec": input, "app.tar.gz": "upstream source", archiveName: "old vendor", - "go-vendor-tools.toml": upstreamConfig, "sources": oldEntry + "\n", ".gitignore": "/" + archiveName + "\n", - } { - require.NoError(t, fileutils.WriteFile(ctx.FS(), "/output/"+name, []byte(data), fileperms.PublicFile)) - } - - ctx.CmdFactory.RunAndGetOutputHandler = func(command *exec.Cmd) (string, error) { - assert.Contains(t, strings.Join(command.Args, " "), "--verify") - assert.Contains(t, strings.Join(command.Args, " "), "MIT AND Apache-2.0") - staging := goVendorTestStaging(t, ctx) - data, err := fileutils.ReadFile(ctx.FS(), filepath.Join(staging, govendor.ConfigFilename)) - require.NoError(t, err) - assert.Equal(t, upstreamConfig, string(data)) - - prep, err := fileutils.ReadFile(ctx.FS(), filepath.Join(filepath.Dir(staging), "sources", "app.spec")) - require.NoError(t, err) - assert.NotContains(t, string(prep), "Source1:") - assert.NotContains(t, string(prep), "tar -xf %{S:1}") - - for name, data := range map[string]string{ - "azldev-generated-vendor.tar.bz2": "new vendor", "archive-name": archiveName + "\n", - "license": "Apache-2.0 AND MIT\n", "sources-list": "Source0: app.tar.gz\nSource2: go-vendor-tools.toml\n", - } { - require.NoError(t, fileutils.WriteFile(ctx.FS(), filepath.Join(staging, name), []byte(data), fileperms.PublicFile)) - } - - return "", nil - } - preparer := &sourcePreparerImpl{fs: ctx.FS(), dryRunnable: ctx, goVendorRunner: mock.NewRunner(ctx, "/mock.cfg")} - - err := preparer.prepareGoVendor(ctx, component, "/output") - if conflict != "" { - require.ErrorContains(t, err, "'source-files'") - - unchanged, readErr := fileutils.ReadFile(ctx.FS(), "/output/app.spec") - require.NoError(t, readErr) - assert.Equal(t, input, string(unchanged)) - - payload, readErr := fileutils.ReadFile(ctx.FS(), "/output/"+archiveName) - require.NoError(t, readErr) - assert.Equal(t, "old vendor", string(payload)) - - manifest, readErr := fileutils.ReadFile(ctx.FS(), "/output/sources") - require.NoError(t, readErr) - assert.Equal(t, oldEntry+"\n", string(manifest)) - - return - } - - require.NoError(t, err) - payload, err := fileutils.ReadFile(ctx.FS(), "/output/"+archiveName) - require.NoError(t, err) - assert.Equal(t, "new vendor", string(payload)) - - finalSpec, err := fileutils.ReadFile(ctx.FS(), "/output/app.spec") - require.NoError(t, err) - assert.Contains(t, string(finalSpec), "Source1: "+archiveName) - assert.Contains(t, string(finalSpec), "License: MIT AND Apache-2.0") - assert.NotContains(t, string(finalSpec), "azldev-go-vendor.toml") - - sources, err := fileutils.ReadFile(ctx.FS(), "/output/sources") - require.NoError(t, err) - digest, err := fileutils.ComputeFileHash(ctx.FS(), fileutils.HashTypeSHA512, "/output/"+archiveName) - require.NoError(t, err) - assert.Equal(t, fedorasource.FormatSourcesEntry(archiveName, fileutils.HashTypeSHA512, digest)+"\n", string(sources)) - ignore, err := fileutils.ReadFile(ctx.FS(), "/output/.gitignore") - require.NoError(t, err) - assert.Equal(t, "/"+archiveName+"\n", string(ignore)) -} diff --git a/internal/app/azldev/core/sources/govendor_internal_test.go b/internal/app/azldev/core/sources/govendor_internal_test.go deleted file mode 100644 index dc4f0a61d..000000000 --- a/internal/app/azldev/core/sources/govendor_internal_test.go +++ /dev/null @@ -1,285 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -package sources - -import ( - "context" - "errors" - "os/exec" - "path/filepath" - "slices" - "strings" - "testing" - - "github.com/microsoft/azure-linux-dev-tools/internal/app/azldev/core/components/components_testutils" - "github.com/microsoft/azure-linux-dev-tools/internal/global/testctx" - "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" - "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/samber/lo" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "go.uber.org/mock/gomock" -) - -func goVendorTestSpec() string { - return strings.Join([]string{ - "Name: app", "Version: 1", "Release: 1", "Summary: app", "License: MIT", - "Source0: app.tar.gz", "Patch0: fix.patch", "BuildRequires: golang(example.com/dep)", - "%description", "app", "%prep", "%goprep -p1", "%build", "%gobuild -o app .", - "%install", "install -D app %{buildroot}%{_bindir}/app", "%files", "%{_bindir}/app", "", - }, "\n") -} - -func TestPrepareSourcesGoVendor(t *testing.T) { - for _, mode := range []string{"prepare", "render", "diff"} { - t.Run(mode, func(t *testing.T) { - ctx := newMockProcessorTestCtx() - ctrl := gomock.NewController(t) - component := components_testutils.NewMockComponent(ctrl) - manager := sourceproviders_test.NewMockSourceManager(ctrl) - config := &projectconfig.ComponentConfig{ - GoVendor: &projectconfig.GoVendorConfig{ - Enabled: lo.ToPtr(true), PrepPackages: []string{"git"}, ConfigFile: "/project/vendor.toml", - }, - Overlays: []projectconfig.ComponentOverlay{{ - Type: "spec-set-tag", Tag: "Summary", Value: "overlaid", - }}, - } - - const settings = "# reviewed settings\n[archive]\nuse_module_proxy = true\n" - require.NoError(t, fileutils.WriteFile(ctx.FS(), config.GoVendor.ConfigFile, - []byte(settings), fileperms.PublicFile)) - - component.EXPECT().GetName().AnyTimes().Return("app") - component.EXPECT().GetConfig().AnyTimes().Return(config) - manager.EXPECT().FetchComponent(gomock.Any(), component, gomock.Any(), gomock.Any()).DoAndReturn( - func(_ context.Context, _ any, outputDir string, opts ...sourceproviders.FetchComponentOption) error { - var fetch sourceproviders.FetchComponentOptions - for _, option := range opts { - option(&fetch) - } - - require.True(t, fetch.PreserveGitDir, "rpmautospec needs upstream history even without output git") - - for name, content := range map[string]string{ - "app.spec": strings.ReplaceAll(goVendorTestSpec(), "Release: 1", "Release: %autorelease"), - "app.tar.gz": "upstream", "fix.patch": "patch", ".git/HEAD": "upstream-history", - "sources": "# upstream\n", ".gitignore": "/app.tar.gz\n", - } { - require.NoError(t, fileutils.MkdirAll(ctx.FS(), filepath.Dir(filepath.Join(outputDir, name)))) - require.NoError(t, fileutils.WriteFile(ctx.FS(), filepath.Join(outputDir, name), - []byte(content), fileperms.PublicFile)) - } - - return nil - }) - manager.EXPECT().FetchFiles(gomock.Any(), component, gomock.Any()).Return(nil) - - var calls []string - - ctx.CmdFactory.RunHandler = func(cmd *exec.Cmd) error { - calls = append(calls, strings.Join(cmd.Args, " ")) - - return nil - } - ctx.CmdFactory.RunAndGetOutputHandler = func(cmd *exec.Cmd) (string, error) { - assert.Contains(t, cmd.Args, "--unpriv") - assert.Contains(t, cmd.Args, "--enable-network") - assert.Contains(t, strings.Join(cmd.Args, " "), "go_vendor_archive") - staging := goVendorTestStaging(t, ctx) - stagedConfig, err := fileutils.ReadFile(ctx.FS(), filepath.Join(staging, govendor.ConfigFilename)) - require.NoError(t, err) - assert.Equal(t, settings, string(stagedConfig)) - - prep, err := fileutils.ReadFile(ctx.FS(), filepath.Join(filepath.Dir(staging), "sources", "app.spec")) - require.NoError(t, err) - assert.Contains(t, string(prep), "Summary: overlaid", "overlays must run before generation") - - history, err := fileutils.ReadFile(ctx.FS(), filepath.Join(filepath.Dir(staging), "sources", ".git", "HEAD")) - require.NoError(t, err) - assert.Equal(t, "upstream-history", string(history)) - - for name, content := range map[string]string{ - "app-vendor.tar.bz2": "generated archive", - "archive-name": "app-vendor.tar.bz2\n", - "license": "Apache-2.0 AND MIT\n", - "sources-list": "Source0: app.tar.gz\nPatch0: fix.patch\n", - } { - require.NoError(t, fileutils.WriteFile(ctx.FS(), - filepath.Join(staging, name), []byte(content), fileperms.PublicFile)) - } - - return "", nil - } - - options := []PreparerOption{WithGoVendorRunner(mock.NewRunner(ctx, "/mock.cfg"))} - if mode == "render" { - options = append(options, WithSkipLookaside()) - } - - preparer, err := NewPreparer(manager, ctx.FS(), ctx, ctx, options...) - require.NoError(t, err) - - if mode == "diff" { - require.NoError(t, fileutils.MkdirAll(ctx.FS(), "/output")) - diff, err := preparer.DiffSources(ctx, component, "/output") - require.NoError(t, err) - assert.Contains(t, diff.String(), "app-vendor.tar.bz2") - - for _, file := range diff.Files { - assert.NotContains(t, file.Path, ".git/") - } - - return - } - - require.NoError(t, preparer.PrepareSources(ctx, component, "/output", true)) - exists, err := fileutils.Exists(ctx.FS(), "/output/.git") - require.NoError(t, err) - assert.False(t, exists, "private generation history must not leak into --without-git output") - - output, err := fileutils.ReadFile(ctx.FS(), "/output/app.spec") - require.NoError(t, err) - assert.Contains(t, string(output), "License: Apache-2.0 AND MIT") - assert.Contains(t, string(output), "tar -xf %{SOURCE1}") - assert.NotContains(t, string(output), "BuildRequires: golang(") - - publishedConfig, err := fileutils.ReadFile(ctx.FS(), "/output/"+govendor.ConfigFilename) - require.NoError(t, err) - assert.Equal(t, settings, string(publishedConfig)) - - digest, err := fileutils.ComputeFileHash(ctx.FS(), fileutils.HashTypeSHA512, "/output/app-vendor.tar.bz2") - require.NoError(t, err) - sources, err := fileutils.ReadFile(ctx.FS(), "/output/sources") - require.NoError(t, err) - assert.Contains(t, string(sources), "# upstream\n") - assert.Contains(t, string(sources), - fedorasource.FormatSourcesEntry("app-vendor.tar.bz2", fileutils.HashTypeSHA512, digest)) - ignored, err := fileutils.ReadFile(ctx.FS(), "/output/.gitignore") - require.NoError(t, err) - assert.Equal(t, "/app.tar.gz\n/app-vendor.tar.bz2\n", string(ignored)) - assert.Contains(t, strings.Join(calls, "\n"), "--install go-vendor-tools askalono-cli") - assert.Contains(t, strings.Join(calls, "\n"), " git") - assert.Contains(t, strings.Join(calls, "\n"), "--scrub all") - assert.NotContains(t, strings.Join(calls, "\n"), "go2rpm") - - matches, err := fileutils.Glob(ctx.FS(), "/tmp/azldev-go-vendor-*") - require.NoError(t, err) - assert.Empty(t, matches) - }) - } -} - -func goVendorTestStaging(t *testing.T, ctx *testctx.TestCtx) string { - t.Helper() - - matches, err := fileutils.Glob(ctx.FS(), "/tmp/azldev-go-vendor-*/work/azldev-go-vendor.toml") - require.NoError(t, err) - require.Len(t, matches, 1) - - return filepath.Dir(matches[0]) -} - -func TestGoVendorFailuresDoNotPublishSpec(t *testing.T) { - failure := errors.New("tool failed") - - for _, stage := range []string{ - "init", "install", "generate", "missing-archive", "empty-archive", - "license", "missing-source", "source-list", "scrub", "archive-name", "unexpected-name", - } { - t.Run(stage, func(t *testing.T) { - ctx := newMockProcessorTestCtx() - ctrl := gomock.NewController(t) - component := components_testutils.NewMockComponent(ctrl) - component.EXPECT().GetName().AnyTimes().Return("app") - component.EXPECT().GetConfig().AnyTimes().Return(&projectconfig.ComponentConfig{ - GoVendor: &projectconfig.GoVendorConfig{Enabled: lo.ToPtr(true)}, - }) - require.NoError(t, fileutils.WriteFile(ctx.FS(), - "/output/app.spec", []byte(goVendorTestSpec()), fileperms.PublicFile)) - require.NoError(t, fileutils.WriteFile(ctx.FS(), "/output/app.tar.gz", []byte("source"), fileperms.PublicFile)) - ctx.CmdFactory.RunHandler = func(cmd *exec.Cmd) error { - if slices.Contains(cmd.Args, "--"+stage) { - return failure - } - - return nil - } - ctx.CmdFactory.RunAndGetOutputHandler = func(_ *exec.Cmd) (string, error) { - if stage == "generate" { - return "license failure details", failure - } - - staging := goVendorTestStaging(t, ctx) - files := map[string]string{ - "app-vendor.tar.bz2": "archive", "license": "MIT\n", "sources-list": "Source0: app.tar.gz\n", - "archive-name": "app-vendor.tar.bz2\n", - } - - switch stage { - case "missing-archive": - delete(files, "app-vendor.tar.bz2") - case "empty-archive": - files["app-vendor.tar.bz2"] = "" - case "license": - files["license"] = "bad\nLicense" - case "missing-source": - files["sources-list"] += "Patch0: absent.patch\n" - case "source-list": - files["sources-list"] = "Source0: /etc/passwd\n" - case "archive-name": - files["archive-name"] = "../outside.tar.bz2\n" - case "unexpected-name": - files["archive-name"] = "other.tar.bz2\n" - } - - for name, data := range files { - require.NoError(t, fileutils.WriteFile(ctx.FS(), filepath.Join(staging, name), []byte(data), fileperms.PublicFile)) - } - - return "", nil - } - p := &sourcePreparerImpl{fs: ctx.FS(), dryRunnable: ctx, goVendorRunner: mock.NewRunner(ctx, "/mock.cfg")} - err := p.prepareGoVendor(ctx, component, "/output") - require.Error(t, err) - - unchanged, readErr := fileutils.ReadFile(ctx.FS(), "/output/app.spec") - require.NoError(t, readErr) - assert.Equal(t, goVendorTestSpec(), string(unchanged)) - - exists, readErr := fileutils.Exists(ctx.FS(), "/output/app-vendor.tar.bz2") - require.NoError(t, readErr) - assert.False(t, exists) - }) - } -} - -func TestGoVendorSourceCollisions(t *testing.T) { - for _, name := range []string{"app-vendor.tar.bz2", govendor.ConfigFilename, "sources", "invalid-sources"} { - t.Run(name, func(t *testing.T) { - ctx := testctx.NewCtx() - preparer := &sourcePreparerImpl{fs: ctx.FS()} - content := "existing" - - filename := name - switch name { - case "sources": - content = fedorasource.FormatSourcesEntry( - "app-vendor.tar.bz2", fileutils.HashTypeSHA512, strings.Repeat("a", 128)) + "\n" - case "invalid-sources": - filename = "sources" - content = "SHA512 (broken" - } - - require.NoError(t, fileutils.WriteFile(ctx.FS(), "/output/"+filename, []byte(content), fileperms.PublicFile)) - require.Error(t, preparer.checkGoVendorSourceCollision("/output", "app-vendor.tar.bz2", govendor.ConfigFilename)) - }) - } -} diff --git a/internal/app/azldev/core/sources/sourceprep.go b/internal/app/azldev/core/sources/sourceprep.go index d4977c5a5..4edeb30b6 100644 --- a/internal/app/azldev/core/sources/sourceprep.go +++ b/internal/app/azldev/core/sources/sourceprep.go @@ -24,7 +24,6 @@ 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" @@ -134,8 +133,7 @@ func WithSpecEditor(mode spec.EditorMode) PreparerOption { // component fetching ([FedoraSourceDownloader.ExtractSourcesFromRepo]). // Git-tracked files (spec, patches, scripts, configs) are still fetched from // the upstream clone. This is useful for rendering, where only the spec and -// sidecar files are normally needed. Enabled Go vendor conversion overrides this -// optimization because its archive and license expression require prepared sources. +// sidecar files are needed and downloading large source tarballs is unnecessary. func WithSkipLookaside() PreparerOption { return func(p *sourcePreparerImpl) { p.skipLookaside = true @@ -186,12 +184,11 @@ func WithAllowNoHashes() PreparerOption { // Standard implementation of the [SourcePreparer] interface. type sourcePreparerImpl struct { - sourceManager sourceproviders.SourceManager - specEditor spec.EditorMode - fs opctx.FS - eventListener opctx.EventListener - dryRunnable opctx.DryRunnable - goVendorRunner *mock.Runner + sourceManager sourceproviders.SourceManager + specEditor spec.EditorMode + fs opctx.FS + eventListener opctx.EventListener + dryRunnable opctx.DryRunnable // withGitRepo, when true, enables dist-git creation by preserving the // upstream .git directory and generating synthetic commit history. @@ -201,9 +198,6 @@ type sourcePreparerImpl struct { // source preparation. Git-tracked files are still fetched. skipLookaside bool - // Preserve upstream history for rpmautospec during private Go vendor generation. - preserveGoVendorHistory bool - // cmdFactory is used to shell out to git for fingerprint change detection // in the project repository. Set via [WithGitRepo]. cmdFactory opctx.CmdFactory @@ -309,11 +303,11 @@ func (p *sourcePreparerImpl) PrepareSources( } } - p = p.withGoVendorInputs(component, applyOverlays) - - // Go vendor prep needs history for rpmautospec even without output dist-git. + // 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) || p.preserveGoVendorHistory { + if applyOverlays && p.withGitRepo { fetchOpts = append(fetchOpts, sourceproviders.WithPreserveGitDir()) } @@ -363,36 +357,6 @@ func (p *sourcePreparerImpl) PrepareSources( } } - return p.removePrivateGoVendorHistory(outputDir, applyOverlays) -} - -func (p *sourcePreparerImpl) withGoVendorInputs( - component components.Component, applyConversion bool, -) *sourcePreparerImpl { - if applyConversion && component.GetConfig().GoVendor.IsEnabled() { - effective := *p - effective.skipLookaside = false - effective.preserveGoVendorHistory = true - - if p.skipLookaside { - slog.Info("Go vendoring requires source downloads, including during rendering", "component", component.GetName()) - } - - return &effective - } - - return p -} - -func (p *sourcePreparerImpl) removePrivateGoVendorHistory(outputDir string, applyConversion bool) error { - if !applyConversion || !p.preserveGoVendorHistory || p.withGitRepo || p.dryRunnable.DryRun() { - return nil - } - - if err := p.fs.RemoveAll(filepath.Join(outputDir, ".git")); err != nil { - return fmt.Errorf("removing private Go vendor history:\n%w", err) - } - return nil } @@ -430,10 +394,6 @@ func (p *sourcePreparerImpl) applyOverlaysToSources( component.GetName(), err) } - if err := p.prepareGoVendor(ctx, component, outputDir); err != nil { - return nil, fmt.Errorf("preparing Go vendor sources for component %#q:\n%w", component.GetName(), err) - } - return repackedArchives, nil } @@ -780,8 +740,6 @@ func removeSubmoduleEntries(fs opctx.FS, repo *gogit.Repository, repoDir string) func (p *sourcePreparerImpl) DiffSources( ctx context.Context, component components.Component, baseDir string, ) (result *dirdiff.DiffResult, err error) { - p = p.withGoVendorInputs(component, true) - event := p.eventListener.StartEvent("Computing overlay diff", "component", component.GetName()) defer event.End() diff --git a/internal/fingerprint/doc.go b/internal/fingerprint/doc.go index 5ad05185b..fc655afa2 100644 --- a/internal/fingerprint/doc.go +++ b/internal/fingerprint/doc.go @@ -3,7 +3,7 @@ // Package fingerprint computes deterministic identity fingerprints for components. // A fingerprint captures all resolved build inputs so that changes to any input -// (config fields, spec content, overlay/vendor config files, distro context, upstream refs, or +// (config fields, spec content, overlay files, distro context, upstream refs, or // ManualBump) produce a different fingerprint. // // The primary entry point is [ComputeIdentity], which takes a resolved diff --git a/internal/fingerprint/fingerprint.go b/internal/fingerprint/fingerprint.go index 6ab13bb14..391559d66 100644 --- a/internal/fingerprint/fingerprint.go +++ b/internal/fingerprint/fingerprint.go @@ -42,9 +42,6 @@ type ComponentInputs struct { // source file's basename and content. Keyed by index rather than path to avoid // checkout-location dependence. OverlayFileHashes map[string]string `json:"overlayFileHashes,omitempty"` - // GoVendorConfigHash records the contents of an explicitly selected vendor - // configuration without depending on its checkout-specific path. - GoVendorConfigHash string `json:"goVendorConfigHash,omitempty"` // ManualBump is the manual rebuild counter from the lock file. Almost always 0; // used for mass-rebuild scenarios. ManualBump int `json:"manualBump"` @@ -65,13 +62,13 @@ type IdentityOptions struct { // // This is caller-provided because resolving it requires network access (upstream clone) or // filesystem traversal (local content hash). [ComputeIdentity] is a pure combiner — it does - // not perform I/O beyond reading declared input files. Callers should resolve source identity via + // not perform I/O beyond reading overlay files. Callers should resolve source identity via // SourceManager.ResolveSourceIdentity before calling [ComputeIdentity]. SourceIdentity string } // ComputeIdentity computes the fingerprint for a component from its resolved config -// and additional context. The fs parameter is used to read declared input file +// and additional context. The fs parameter is used to read overlay source file // contents for hashing; spec content identity is provided via [IdentityOptions.SourceIdentity]. // // This function is a deterministic combiner: given the same resolved inputs it always @@ -144,11 +141,6 @@ func ComputeIdentity( inputs.OverlayFileHashes = overlayHashes - inputs.GoVendorConfigHash, err = component.GoVendor.SourceContentIdentity(fs) - if err != nil { - return nil, fmt.Errorf("hashing Go vendor configuration:\n%w", err) - } - // 5. Combine all inputs into the overall fingerprint. return &ComponentIdentity{ Fingerprint: combineInputs(inputs), @@ -166,10 +158,6 @@ func combineInputs(inputs ComponentInputs) string { writeField(hasher, "manual_bump", strconv.Itoa(inputs.ManualBump)) writeField(hasher, "release_ver", inputs.ReleaseVer) - if inputs.GoVendorConfigHash != "" { - writeField(hasher, "go_vendor_config", inputs.GoVendorConfigHash) - } - // Overlay file hashes in sorted key order for determinism. if len(inputs.OverlayFileHashes) > 0 { keys := make([]string, 0, len(inputs.OverlayFileHashes)) diff --git a/internal/fingerprint/govendor_test.go b/internal/fingerprint/govendor_test.go deleted file mode 100644 index cd47c3838..000000000 --- a/internal/fingerprint/govendor_test.go +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -package fingerprint_test - -import ( - "testing" - - "github.com/microsoft/azure-linux-dev-tools/internal/fingerprint" - "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/samber/lo" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestGoVendorConfigFileFingerprint(t *testing.T) { - ctx := newTestFS(t, map[string]string{ - "/checkout-one/vendor.toml": "[archive]\ntidy = false\n", - "/checkout-two/vendor.toml": "[archive]\ntidy = false\n", - "/empty.toml": "", - }) - component := projectconfig.ComponentConfig{GoVendor: &projectconfig.GoVendorConfig{ - Enabled: lo.ToPtr(true), ConfigFile: "/checkout-one/vendor.toml", - }} - compute := func(config projectconfig.ComponentConfig) *fingerprint.ComponentIdentity { - t.Helper() - - result, err := fingerprint.ComputeIdentity(ctx.FS(), config, testReleaseVer, fingerprint.IdentityOptions{}) - require.NoError(t, err) - - return result - } - initial := compute(component) - require.NotEmpty(t, initial.Inputs.GoVendorConfigHash) - assert.Equal(t, "/checkout-one/vendor.toml", component.GoVendor.ConfigFile) - component.GoVendor.ConfigFile = "/checkout-two/vendor.toml" - assert.Equal(t, initial.Fingerprint, compute(component).Fingerprint, "checkout location must not affect identity") - - require.NoError(t, fileutils.WriteFile(ctx.FS(), component.GoVendor.ConfigFile, - []byte("[archive]\ntidy = true\n"), fileperms.PublicFile)) - assert.NotEqual(t, initial.Fingerprint, compute(component).Fingerprint, - "file-only edits must invalidate the fingerprint") - component.GoVendor.ConfigFile = "/empty.toml" - emptyFile := compute(component) - component.GoVendor.ConfigFile = "" - noFile := compute(component) - assert.Empty(t, noFile.Inputs.GoVendorConfigHash) - assert.NotEqual(t, emptyFile.Fingerprint, noFile.Fingerprint, "an empty override is not upstream fallback") -} - -func TestGoVendorConfigFileFingerprintErrors(t *testing.T) { - ctx := newTestFS(t, map[string]string{"/bad.toml": "["}) - for _, path := range []string{"/missing.toml", "/bad.toml"} { - _, err := fingerprint.ComputeIdentity(ctx.FS(), projectconfig.ComponentConfig{ - GoVendor: &projectconfig.GoVendorConfig{Enabled: lo.ToPtr(true), ConfigFile: path}, - }, testReleaseVer, fingerprint.IdentityOptions{}) - require.Error(t, err) - assert.Contains(t, err.Error(), path) - } -} diff --git a/internal/govendor/generate.go b/internal/govendor/generate.go deleted file mode 100644 index 3d8fa4a02..000000000 --- a/internal/govendor/generate.go +++ /dev/null @@ -1,325 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -// Package govendor generates vendor artifacts without resolving components or editing specs. -package govendor - -import ( - "cmp" - "context" - "errors" - "fmt" - "log/slog" - "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/rpm/spectool" - "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" -) - -const ( - // ConfigFilename is the tool configuration filename inside generation staging. - ConfigFilename = "azldev-go-vendor.toml" - sourceMount = "/azldev-go-vendor" - outputMount = "/azldev-go-scratch" - topDir = "/tmp/azldev-go-rpm" - cleanupTimeout = 5 * time.Minute -) - -// Request supplies prepared spec bytes and input files. WorkDir must be a private -// scratch directory outside SourceDir; the caller owns its cleanup and dry-run policy. -// PrepSpec must record 'azldev-go-module-root' and 'azldev-go-archive-name' in RPM's topdir. -type Request struct { - SourceDir, WorkDir, SpecName string - ArchiveFile, ArchiveSuffix string - ModuleDir, ConfigContents string - ExpectedLicense string - PrepSpec []byte - Packages []string - configModuleDir string -} - -// Artifact is validated generation output, ready for publication by the caller. -type Artifact struct { - Path, Name, License, Digest string -} - -// Generate prepares inputs and generates an archive in one isolated mock root. -// It never changes SourceDir or publishes a spec or source manifest. -func Generate(ctx context.Context, fs opctx.FS, base *mock.Runner, request Request) (Artifact, error) { - request, err := resolveModuleDir(request) - if err != nil { - return Artifact{}, err - } - - staging := filepath.Join(request.WorkDir, "work") - - sourceCopy := filepath.Join(request.WorkDir, "sources") - if err := stage(fs, request, sourceCopy, staging); err != nil { - return Artifact{}, err - } - - runner := base.Clone().WithBaseDir(filepath.Join(request.WorkDir, "mock")).EnableNetwork().WithUnprivileged() - runner.AddBindMount(sourceCopy, sourceMount).AddBindMount(staging, outputMount) - - if err := execute(ctx, runner, request); err != nil { - return Artifact{}, err - } - - // Snapshot only regular outputs into a host-only directory. Subsequent - // validation, hashing and publication never reopen chroot-writable paths. - trusted := filepath.Join(request.WorkDir, "artifacts") - if err := fileutils.MkdirAll(fs, trusted); err != nil { - return Artifact{}, fmt.Errorf("creating trusted Go vendor output directory:\n%w", err) - } - - for _, name := range []string{request.ArchiveFile, "archive-name", "license", "sources-list"} { - if err := fileutils.CopyFileCrossFS(nilDryRun{}, fs, filepath.Join(staging, name), - fs, filepath.Join(trusted, name), fileutils.CopyFileOptions{NoFollow: true}); err != nil { - return Artifact{}, fmt.Errorf("collecting Go vendor output %#q:\n%w", name, err) - } - } - - if err := validateInputs(fs, trusted, request.SourceDir); err != nil { - return Artifact{}, err - } - - return readArtifact(fs, trusted, request) -} - -type nilDryRun struct{} - -func (nilDryRun) DryRun() bool { return false } - -func resolveModuleDir(request Request) (Request, error) { - var settings map[string]any - if err := toml.Unmarshal([]byte(request.ConfigContents), &settings); err != nil { - return request, fmt.Errorf("parsing Go vendor tool configuration:\n%w", err) - } - - general, _ := settings["general"].(map[string]any) - if raw, exists := general["go_mod_dir"]; exists { - directory, ok := raw.(string) - if !ok { - return request, errors.New("go vendor 'general.go_mod_dir' must be a string") - } - - request.configModuleDir = directory - } - - for _, directory := range []string{request.ModuleDir, request.configModuleDir} { - if directory == "" || directory == "." { - continue - } - - if err := fileutils.ValidateRelPath(directory); err != nil { - return request, fmt.Errorf("invalid Go vendor module directory:\n%w", err) - } - - if strings.ContainsAny(directory, "%\r\n") { - return request, errors.New("go vendor module directory must not contain RPM macros or newlines") - } - } - - if request.configModuleDir != "" { - if request.ModuleDir != "" && request.ModuleDir != request.configModuleDir { - return request, errors.New("'module-dir' conflicts with upstream 'general.go_mod_dir'; " + - "use 'config-file' to replace the upstream settings") - } - - // Native tools preserve this subdirectory in the archive and use it for - // licensing. Keep their root and config intact, without descending twice. - request.ModuleDir = "" - } - - return request, nil -} - -func stage(fs opctx.FS, request Request, sourceCopy, staging string) error { - for _, name := range []string{request.SpecName, request.ArchiveFile} { - if err := fileutils.ValidateFilename(name); err != nil { - return fmt.Errorf("invalid Go vendor staging filename:\n%w", err) - } - } - - if err := fileutils.MkdirAll(fs, staging); err != nil { - return fmt.Errorf("creating Go vendor staging directory:\n%w", err) - } - - if err := fileutils.CopyDirRecursiveCrossFS(fs, request.SourceDir, fs, sourceCopy, - fileutils.CopyDirOptions{CopyFileOptions: fileutils.CopyFileOptions{PreserveFileMode: true}}); err != nil { - return fmt.Errorf("copying Go sources for isolated prep:\n%w", err) - } - - for path, data := range map[string][]byte{ - filepath.Join(sourceCopy, request.SpecName): request.PrepSpec, - filepath.Join(staging, ConfigFilename): []byte(request.ConfigContents), - } { - if err := fileutils.WriteFile(fs, path, data, fileperms.PublicFile); err != nil { - return fmt.Errorf("staging Go vendor input %#q:\n%w", path, err) - } - } - - return nil -} - -func execute(ctx context.Context, runner *mock.Runner, request Request) (err error) { - defer func() { - cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), cleanupTimeout) - defer cancel() - - if cleanupErr := runner.ScrubRoot(cleanupCtx); cleanupErr != nil { - slog.Error("Failed to clean Go vendor mock root", "error", cleanupErr) - - if err == nil { - err = cleanupErr - } - } - }() - - if err := runner.InitRoot(ctx); err != nil { - return fmt.Errorf("initializing Go vendor mock root:\n%w", err) - } - - packages := append([]string{ - "go-vendor-tools", "askalono-cli", "golang", "go-rpm-macros", "rpm-build", "rpmdevtools", - "rpmautospec", "git", "python3-click", - }, request.Packages...) - if err := runner.InstallPackages(ctx, packages); err != nil { - return fmt.Errorf("installing Go vendor prerequisites:\n%w", err) - } - - cmd, err := runner.CmdInChroot(ctx, generationCommand(request, runner.ConfigOpts()["target_arch"]), false) - if err != nil { - return fmt.Errorf("constructing Go vendor command:\n%w", err) - } - - output, err := cmd.RunAndGetOutput(ctx) - if err != nil { - return fmt.Errorf("go vendor generation or license detection failed; use 'prep-packages' for missing prep tools "+ - "and 'config-file' for reviewed license exceptions:\n%s\n%w", output, err) - } - - return nil -} - -func generationCommand(request Request, targetArch string) []string { - quote := shellquote.Join - - prepArgs := []string{ - "rpmbuild", "-bp", "--nodeps", "--define", "_topdir " + topDir, - "--define", "_builddir " + topDir + "/BUILD", "--define", "_sourcedir " + sourceMount, - } - if targetArch != "" { - prepArgs = append(prepArgs, "--target", targetArch) - } - - licenseArgs := []string{ - "go_vendor_license", "--config", outputMount + "/" + ConfigFilename, "--path", ".", - "report", "--no-prompt", "--autofill", "off", "expression", - } - if request.ExpectedLicense != "" { - licenseArgs = append(licenseArgs, "--verify", request.ExpectedLicense) - } - - commands := []string{ - "cd " + sourceMount, - "mkdir -p " + topDir + "/BUILD", - quote("git", "config", "--global", "--add", "safe.directory", sourceMount), - quote("rpmautospec", "process-distgit", request.SpecName, request.SpecName), - quote(append(prepArgs, sourceMount+"/"+request.SpecName)...), - quote("cp", topDir+"/azldev-go-archive-name", outputMount+"/archive-name"), - `IFS= read -r module_root < ` + topDir + "/azldev-go-module-root", - `cd "$module_root"`, - "cd " + quote(cmp.Or(request.ModuleDir, ".")), - quote("test", "-f", filepath.Join(request.configModuleDir, "go.mod")), - `module_root=$(pwd -P)`, - "export GOTOOLCHAIN=local", - "cd " + sourceMount, - quote("go_vendor_archive", "create", "--config", outputMount+"/"+ConfigFilename, - "--output", outputMount+"/"+request.ArchiveFile) + ` "$module_root"`, - `cd "$module_root"`, - quote("tar", "-xf", outputMount+"/"+request.ArchiveFile), - quote(licenseArgs...) + " > " + outputMount + "/license", - "cd " + sourceMount, - quote("spectool", "--define", "_sourcedir "+sourceMount, "-l", "-a", request.SpecName) + - " > " + outputMount + "/sources-list", - } - - return []string{"bash", "-euo", "pipefail", "-c", strings.Join(commands, "\n")} -} - -func readArtifact(fs opctx.FS, staging string, request Request) (Artifact, error) { - result := Artifact{Path: filepath.Join(staging, request.ArchiveFile)} - - info, err := fs.Stat(result.Path) - if err != nil { - return result, fmt.Errorf("missing generated Go vendor archive:\n%w", err) - } - - if !info.Mode().IsRegular() || info.Size() == 0 { - return result, errors.New("generated Go vendor archive must be a nonempty regular file") - } - - for name, destination := range map[string]*string{"archive-name": &result.Name, "license": &result.License} { - data, err := fileutils.ReadFile(fs, filepath.Join(staging, name)) - if err != nil { - return result, fmt.Errorf("reading Go vendor output %#q:\n%w", name, err) - } - - *destination = strings.TrimSpace(string(data)) - if *destination == "" || strings.ContainsAny(*destination, "%\r\n") { - return result, fmt.Errorf("invalid Go vendor output %#q: %#q", name, *destination) - } - } - - if err := fileutils.ValidateFilename(result.Name); err != nil { - return result, fmt.Errorf("invalid expanded Go vendor archive name:\n%w", err) - } - - if !strings.HasSuffix(result.Name, request.ArchiveSuffix) { - return result, fmt.Errorf("unexpected expanded Go vendor archive name %#q", result.Name) - } - - result.Digest, err = fileutils.ComputeFileHash(fs, fileutils.HashTypeSHA512, result.Path) - if err != nil { - return result, fmt.Errorf("hashing generated Go vendor archive:\n%w", err) - } - - return result, nil -} - -func validateInputs(fs opctx.FS, staging, sourceDir string) error { - data, err := fileutils.ReadFile(fs, filepath.Join(staging, "sources-list")) - if err != nil { - return fmt.Errorf("reading prepared Go source list:\n%w", err) - } - - for _, line := range strings.Split(strings.TrimSpace(string(data)), "\n") { - if line == "" { - continue - } - - files := spectool.ParseSpectoolOutput(line) - if len(files) != 1 || strings.Contains(files[0], "%") { - return fmt.Errorf("cannot resolve Go source/patch reference %#q", line) - } - - info, err := fs.Stat(filepath.Join(sourceDir, files[0])) - if err != nil { - return fmt.Errorf("missing prepared Go source/patch %#q:\n%w", files[0], err) - } - - if !info.Mode().IsRegular() { - return fmt.Errorf("go source/patch %#q is not a regular file", files[0]) - } - } - - return nil -} diff --git a/internal/govendor/generate_internal_test.go b/internal/govendor/generate_internal_test.go deleted file mode 100644 index 1d3f7b49e..000000000 --- a/internal/govendor/generate_internal_test.go +++ /dev/null @@ -1,211 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -package govendor - -import ( - "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/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestGenerateArtifact(t *testing.T) { - for _, invalid := range []string{"", "archive-name", "license", "sources-list"} { - t.Run("invalid-"+invalid, func(t *testing.T) { - ctx := testctx.NewCtx() - ctx.CmdFactory.RegisterCommandInSearchPath(mock.MockBinary) - require.NoError(t, fileutils.WriteFile(ctx.FS(), "/input/app.spec", []byte("original"), fileperms.PublicFile)) - request := Request{ - SourceDir: "/input", WorkDir: "/scratch", SpecName: "app.spec", - ArchiveFile: "vendor.tar.bz2", ArchiveSuffix: ".tar.bz2", PrepSpec: []byte("prepared"), - } - ctx.CmdFactory.RunAndGetOutputHandler = func(command *exec.Cmd) (string, error) { - assert.Contains(t, command.Args, "--unpriv") - assert.Contains(t, command.Args, "--enable-network") - - for name, content := range map[string]string{ - request.ArchiveFile: "archive", "archive-name": "app-vendor.tar.bz2\n", - "license": "MIT\n", "sources-list": "Source0: app.spec\n", - } { - if name == invalid { - content = "%{unexpanded}" - } - - require.NoError(t, fileutils.WriteFile(ctx.FS(), - filepath.Join("/scratch/work", name), []byte(content), fileperms.PublicFile)) - } - - return "", nil - } - - artifact, err := Generate(ctx, ctx.FS(), mock.NewRunner(ctx, "/mock.cfg"), request) - if invalid != "" { - require.Error(t, err) - - return - } - - require.NoError(t, err) - assert.Equal(t, "/scratch/artifacts/vendor.tar.bz2", artifact.Path, - "published artifacts must come from the host-only snapshot") - assert.Equal(t, "app-vendor.tar.bz2", artifact.Name) - assert.Equal(t, "MIT", artifact.License) - digest, err := fileutils.ComputeFileHash(ctx.FS(), fileutils.HashTypeSHA512, artifact.Path) - require.NoError(t, err) - assert.Equal(t, digest, artifact.Digest) - - original, err := fileutils.ReadFile(ctx.FS(), "/input/app.spec") - require.NoError(t, err) - assert.Equal(t, "original", string(original)) - }) - } -} - -func TestGenerationCommand(t *testing.T) { - for _, expected := range []string{"", "MIT AND Apache-2.0"} { - command := generationCommand(Request{ - ArchiveFile: "app-vendor.tar.bz2", ModuleDir: "cmd/app", SpecName: "app.spec", ExpectedLicense: expected, - }, "aarch64") - assert.Equal(t, []string{"bash", "-euo", "pipefail", "-c"}, command[:4]) - script := command[4] - assert.Less(t, strings.Index(script, "rpmautospec"), strings.Index(script, "rpmbuild")) - assert.Less(t, strings.Index(script, "rpmbuild"), strings.Index(script, "go_vendor_archive")) - assert.Less(t, strings.Index(script, "go_vendor_archive"), strings.Index(script, "go_vendor_license")) - assert.Contains(t, script, "cd cmd/app") - assert.Contains(t, script, - "cd "+sourceMount+"\ngo_vendor_archive create --config "+outputMount+"/"+ConfigFilename+ - " --output "+outputMount+`/app-vendor.tar.bz2 "$module_root"`+"\n"+`cd "$module_root"`) - assert.Contains(t, script, "--target aarch64") - assert.Contains(t, script, "--no-prompt") - assert.Contains(t, script, "--autofill off") - assert.NotContains(t, script, "--idempotent") - assert.Contains(t, script, "cp "+topDir+"/azldev-go-archive-name "+outputMount+"/archive-name") - assert.Equal(t, expected != "", strings.Contains(script, "--verify")) - } -} - -func TestResolveModuleDir(t *testing.T) { - for _, testCase := range []struct { - name, config, module, want string - wantErr bool - }{ - {name: "default"}, - {name: "upstream", config: "[general]\ngo_mod_dir = 'cmd/app'\n[archive]\ntidy = false"}, - {name: "matching", config: "[general]\ngo_mod_dir = 'cmd/app'", module: "cmd/app"}, - {name: "conflicting", config: "[general]\ngo_mod_dir = 'upstream'", module: "cmd/app", wantErr: true}, - {name: "explicit", module: "cmd/app", want: "cmd/app"}, - {name: "root", config: "[general]\ngo_mod_dir = '.'"}, - {name: "absolute", config: "[general]\ngo_mod_dir = '/etc'", wantErr: true}, - {name: "traversal", config: "[general]\ngo_mod_dir = '../outside'", wantErr: true}, - {name: "macro", config: "[general]\ngo_mod_dir = '%{bad}'", wantErr: true}, - {name: "type", config: "[general]\ngo_mod_dir = 42", wantErr: true}, - {name: "toml", config: "[broken", wantErr: true}, - } { - t.Run(testCase.name, func(t *testing.T) { - original := Request{ModuleDir: testCase.module, ConfigContents: testCase.config} - - actual, err := resolveModuleDir(original) - if testCase.wantErr { - require.Error(t, err) - - return - } - - require.NoError(t, err) - assert.Equal(t, testCase.want, actual.ModuleDir) - assert.Equal(t, testCase.config, actual.ConfigContents) - assert.Equal(t, testCase.config, original.ConfigContents) - }) - } -} - -// Kernel-enforced O_NOFOLLOW cannot be exercised by the in-memory filesystem. -func TestGenerateRejectsSymlinkOutputs(t *testing.T) { - for _, name := range []string{"vendor.tar.bz2", "archive-name", "license", "sources-list"} { - t.Run(name, func(t *testing.T) { - ctx := testctx.NewCtx(testctx.WithHostFS()) - ctx.CmdFactory.RegisterCommandInSearchPath(mock.MockBinary) - - root := t.TempDir() - request := Request{ - SourceDir: filepath.Join(root, "input"), WorkDir: filepath.Join(root, "scratch"), SpecName: "app.spec", - ArchiveFile: "vendor.tar.bz2", ArchiveSuffix: ".tar.bz2", PrepSpec: []byte("prepared"), - } - require.NoError(t, fileutils.MkdirAll(ctx.FS(), request.SourceDir)) - require.NoError(t, fileutils.WriteFile(ctx.FS(), filepath.Join(request.SourceDir, "app.spec"), - []byte("original"), fileperms.PublicFile)) - target := filepath.Join(root, "host-only") - require.NoError(t, fileutils.WriteFile(ctx.FS(), target, []byte("host-only contents"), fileperms.PublicFile)) - ctx.CmdFactory.RunAndGetOutputHandler = func(_ *exec.Cmd) (string, error) { - for filename, content := range map[string]string{ - request.ArchiveFile: "archive", "archive-name": "app-vendor.tar.bz2\n", - "license": "MIT\n", "sources-list": "Source0: app.spec\n", - } { - path := filepath.Join(request.WorkDir, "work", filename) - if filename == name { - require.NoError(t, os.Symlink(target, path)) - } else { - require.NoError(t, fileutils.WriteFile(ctx.FS(), path, []byte(content), fileperms.PublicFile)) - } - } - - return "", nil - } - artifact, err := Generate(ctx, ctx.FS(), mock.NewRunner(ctx, "/mock.cfg"), request) - require.ErrorContains(t, err, "without following symlinks") - assert.Empty(t, artifact.Path) - }) - } -} - -func TestCollectOutputRejectsNonRegularFile(t *testing.T) { - ctx := testctx.NewCtx() - require.NoError(t, fileutils.MkdirAll(ctx.FS(), "/input/directory")) - err := fileutils.CopyFile(ctx, ctx.FS(), "/input/directory", "/output/file", - fileutils.CopyFileOptions{NoFollow: true}) - require.ErrorContains(t, err, "not a regular file") -} - -func TestGenerateUsesUpstreamModuleWithoutChangingInputs(t *testing.T) { - ctx := testctx.NewCtx() - ctx.CmdFactory.RegisterCommandInSearchPath(mock.MockBinary) - require.NoError(t, fileutils.WriteFile(ctx.FS(), "/input/app.spec", []byte("original"), fileperms.PublicFile)) - - settings := "[general]\ngo_mod_dir = 'cmd/app'\n" - ctx.CmdFactory.RunAndGetOutputHandler = func(command *exec.Cmd) (string, error) { - script := strings.Join(command.Args, " ") - assert.Contains(t, script, "test -f cmd/app/go.mod") - assert.NotContains(t, script, "cd cmd/app") - - config, err := fileutils.ReadFile(ctx.FS(), "/scratch/work/"+ConfigFilename) - require.NoError(t, err) - assert.Equal(t, settings, string(config)) - - for name, content := range map[string]string{ - "vendor.tar.bz2": "archive", "archive-name": "app-vendor.tar.bz2\n", - "license": "MIT\n", "sources-list": "Source0: app.spec\n", - } { - require.NoError(t, fileutils.WriteFile(ctx.FS(), filepath.Join("/scratch/work", name), - []byte(content), fileperms.PublicFile)) - } - - return "", nil - } - request := Request{ - SourceDir: "/input", WorkDir: "/scratch", SpecName: "app.spec", - ArchiveFile: "vendor.tar.bz2", ConfigContents: settings, - } - _, err := Generate(ctx, ctx.FS(), mock.NewRunner(ctx, "/mock.cfg"), request) - require.NoError(t, err) - assert.Equal(t, settings, request.ConfigContents) - assert.Empty(t, request.ModuleDir) -} diff --git a/internal/projectconfig/component.go b/internal/projectconfig/component.go index 67e4f6295..6b56f9d8e 100644 --- a/internal/projectconfig/component.go +++ b/internal/projectconfig/component.go @@ -374,8 +374,6 @@ type ComponentLockData struct { } // Defines a component. -// -//nolint:recvcheck // HashInclude must also support configs passed to hashstructure by value. type ComponentConfig struct { // The component's name; not actually present in serialized files. Name string `toml:"-" json:"name" table:",sortkey" fingerprint:"-"` @@ -434,9 +432,6 @@ type ComponentConfig struct { // Source file references for this component. SourceFiles []SourceFileReference `toml:"source-files,omitempty" json:"sourceFiles,omitempty" table:"-" jsonschema:"title=Source files,description=Source files to download for this component"` - // GoVendor converts supported Go application specs and generates their vendored sources. - GoVendor *GoVendorConfig `toml:"go-vendor,omitempty" json:"goVendor,omitempty" table:"-" jsonschema:"title=Go vendoring,description=Convert a Go application spec and generate its vendor archive during source preparation"` - // Per-package configuration overrides, keyed by exact binary package name. // Takes precedence over package-group defaults. Packages map[string]PackageConfig `toml:"packages,omitempty" json:"packages,omitempty" table:"-" validate:"dive" jsonschema:"title=Package overrides,description=Per-package configuration overrides keyed by exact binary package name"` @@ -455,11 +450,6 @@ type ComponentConfig struct { Tests *ComponentTestsConfig `toml:"tests,omitempty" json:"tests,omitempty" table:"-" jsonschema:"title=Tests,description=Per-component test or test-group references" fingerprint:"-"` } -// HashInclude preserves existing fingerprints when Go vendoring is not configured. -func (c ComponentConfig) HashInclude(field string, _ any) (bool, error) { - return field != "GoVendor" || c.GoVendor != nil, nil -} - // AllowedSourceFilesHashTypes defines the set of hash types that are supported // for use in [SourceFileReference] entries in component configs. // MD5 is excluded by design. @@ -472,12 +462,10 @@ var AllowedSourceFilesHashTypes = map[fileutils.HashType]bool{ // Mutates the component config, updating it with overrides present in other. func (c *ComponentConfig) MergeUpdatesFrom(other *ComponentConfig) error { - c.GoVendor = deep.MustCopy(c.GoVendor) otherOverlayFiles := slices.Clone(other.OverlayFiles) otherSourceConfigFile := other.SourceConfigFile otherWithoutSourceConfigFile := *other otherWithoutSourceConfigFile.SourceConfigFile = nil - otherWithoutSourceConfigFile.GoVendor = deep.MustCopy(other.GoVendor) err := mergo.Merge(c, &otherWithoutSourceConfigFile, mergo.WithOverride, mergo.WithAppendSlice) if err != nil { @@ -492,18 +480,9 @@ func (c *ComponentConfig) MergeUpdatesFrom(other *ComponentConfig) error { c.OverlayFiles = otherOverlayFiles } - c.overrideGoVendorEnabled(other) - return nil } -func (c *ComponentConfig) overrideGoVendorEnabled(other *ComponentConfig) { - if other.GoVendor != nil && other.GoVendor.Enabled != nil { - enabled := *other.GoVendor.Enabled - c.GoVendor.Enabled = &enabled - } -} - func (c *ComponentConfig) resolveLocalCustomScriptPaths() { if c.Spec.SourceType != SpecSourceTypeLocal || c.Spec.Path == "" { return @@ -526,13 +505,11 @@ func (c *ComponentConfig) resolveLocalCustomScriptPaths() { // primary definition rather than merge with it. Slices in the build config are // still appended, matching [ComponentConfig.MergeUpdatesFrom]. func (c *ComponentConfig) MergeOverridesFrom(other *ComponentConfig) error { - c.GoVendor = deep.MustCopy(c.GoVendor) otherOverlayFiles := slices.Clone(other.OverlayFiles) // Merge the nested config blocks separately so that mergo does not descend // into them with slice-appending semantics. otherTopLevel := *other - otherTopLevel.GoVendor = deep.MustCopy(other.GoVendor) otherTopLevel.Spec = SpecSource{} otherTopLevel.Release = ReleaseConfig{} otherTopLevel.Build = ComponentBuildConfig{} @@ -572,8 +549,6 @@ func (c *ComponentConfig) MergeOverridesFrom(other *ComponentConfig) error { c.OverlayFiles = otherOverlayFiles } - c.overrideGoVendorEnabled(other) - return nil } @@ -646,18 +621,31 @@ func ResolveComponentConfig( // Returns a copy of the component config with relative file paths converted to absolute // file paths (relative to referenceDir, not the current working directory). func (c *ComponentConfig) WithAbsolutePaths(referenceDir string) *ComponentConfig { - // Copy all configuration fields, excluding shared back-references which can - // point back into the component map and must retain their identity. - input := *c - input.SourceConfigFile, input.upstreamCommitConfigFile = nil, nil - result := deep.MustCopy(&input) - result.SourceConfigFile, result.upstreamCommitConfigFile = c.SourceConfigFile, c.upstreamCommitConfigFile + // Deep copy the input to avoid unexpected sharing. Make sure *not* to deep-copy + // the SourceConfigFile, as we *do* want to alias that pointer, sharing it across + // all configs that came from that source config file. + result := &ComponentConfig{ + Name: c.Name, + SourceConfigFile: c.SourceConfigFile, + upstreamCommitConfigFile: c.upstreamCommitConfigFile, + RenderedSpecDir: c.RenderedSpecDir, + Locked: deep.MustCopy(c.Locked), + Release: c.Release, + Spec: deep.MustCopy(c.Spec), + Build: deep.MustCopy(c.Build), + Render: c.Render, + SourceFiles: deep.MustCopy(c.SourceFiles), + Packages: deep.MustCopy(c.Packages), + Publish: deep.MustCopy(c.Publish), + // OverlayFiles is consumed after component config resolution; preserve it verbatim + // here so inherited patterns can be interpreted relative to the concrete component + // config file. + OverlayFiles: slices.Clone(c.OverlayFiles), + Tests: deep.MustCopy(c.Tests), + } // Fix up paths. result.Spec.Path = makeAbsolute(referenceDir, result.Spec.Path) - if result.GoVendor != nil { - result.GoVendor.ConfigFile = makeAbsolute(referenceDir, result.GoVendor.ConfigFile) - } for i := range result.SourceFiles { origin := &result.SourceFiles[i].Origin @@ -666,8 +654,13 @@ func (c *ComponentConfig) WithAbsolutePaths(referenceDir string) *ComponentConfi } } - for i := range result.Overlays { - result.Overlays[i] = *result.Overlays[i].WithAbsolutePaths(referenceDir) + // Copy and fix up overlays. + if c.Overlays != nil { + result.Overlays = make([]ComponentOverlay, len(c.Overlays)) + + for i := range result.Overlays { + result.Overlays[i] = *c.Overlays[i].WithAbsolutePaths(referenceDir) + } } return result diff --git a/internal/projectconfig/component_clone_internal_test.go b/internal/projectconfig/component_clone_internal_test.go deleted file mode 100644 index 2f6e43388..000000000 --- a/internal/projectconfig/component_clone_internal_test.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -package projectconfig - -import ( - "testing" - - "github.com/samber/lo" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestComponentClonePreservesBackReferences(t *testing.T) { - source, pinSource := &ConfigFile{}, &ConfigFile{} - config := ComponentConfig{ - SourceConfigFile: source, upstreamCommitConfigFile: pinSource, - GoVendor: &GoVendorConfig{Enabled: lo.ToPtr(true), PrepPackages: []string{"git"}}, - Build: ComponentBuildConfig{Defines: map[string]string{"feature": "1"}}, - } - source.Components = map[string]ComponentConfig{"app": config} - pinSource.Components = source.Components - - resolved := config.WithAbsolutePaths("/project") - require.Same(t, source, resolved.SourceConfigFile) - require.Same(t, pinSource, resolved.upstreamCommitConfigFile) - require.NotSame(t, config.GoVendor, resolved.GoVendor) - require.Equal(t, config.GoVendor, resolved.GoVendor) - resolved.Build.Defines["feature"] = "2" - *resolved.GoVendor.Enabled = false - resolved.GoVendor.PrepPackages[0] = "changed" - assert.True(t, config.GoVendor.IsEnabled()) - - assert.Equal(t, "1", config.Build.Defines["feature"]) - assert.Equal(t, []string{"git"}, config.GoVendor.PrepPackages) -} diff --git a/internal/projectconfig/configfile.go b/internal/projectconfig/configfile.go index aee4be162..ee6f07c73 100644 --- a/internal/projectconfig/configfile.go +++ b/internal/projectconfig/configfile.go @@ -171,10 +171,6 @@ func validateComponentConfigs( } // Validate build configuration. - if err := component.GoVendor.Validate(); err != nil { - return fmt.Errorf("invalid 'go-vendor' config for component %#q:\n%w", componentName, err) - } - err := component.Build.Validate() if err != nil { return fmt.Errorf("invalid build config for component %#q:\n%w", componentName, err) diff --git a/internal/projectconfig/fingerprint_test.go b/internal/projectconfig/fingerprint_test.go index 881ea95fb..836eee6f3 100644 --- a/internal/projectconfig/fingerprint_test.go +++ b/internal/projectconfig/fingerprint_test.go @@ -36,7 +36,6 @@ func TestAllFingerprintedFieldsHaveDecision(t *testing.T) { reflect.TypeFor[projectconfig.Origin](), reflect.TypeFor[projectconfig.ReleaseConfig](), reflect.TypeFor[projectconfig.ComponentRenderConfig](), - reflect.TypeFor[projectconfig.GoVendorConfig](), } // Maps "StructName.FieldName" for every field that should carry a @@ -106,9 +105,6 @@ func TestAllFingerprintedFieldsHaveDecision(t *testing.T) { // SpecSource.Path — absolute path that varies by checkout location. // Spec content identity is captured separately via SourceIdentity. "SpecSource.Path": true, - - // GoVendorConfig.ConfigFile — absolute declaration path; contents are hashed separately. - "GoVendorConfig.ConfigFile": true, } // Collect all actual exclusions found via reflection, and flag invalid tag values. diff --git a/internal/projectconfig/govendor.go b/internal/projectconfig/govendor.go deleted file mode 100644 index 415a2a7c7..000000000 --- a/internal/projectconfig/govendor.go +++ /dev/null @@ -1,102 +0,0 @@ -// 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" -) - -// GoVendorConfig describes a repeatable conversion, not a replacement spec. -type GoVendorConfig struct { - // Enabled is a pointer so an explicit false overrides inherited settings. - Enabled *bool `toml:"enabled,omitempty" json:"enabled,omitempty" jsonschema:"title=Enabled,description=Enable Go application vendoring"` - // ModuleDir is relative to the directory left by the spec's prep section. - ModuleDir string `toml:"module-dir,omitempty" json:"moduleDir,omitempty" jsonschema:"title=Module directory,description=Relative module directory within the prepared source tree; defaults to its root"` - // ConfigFile identifies a native go-vendor-tools TOML file, relative to the declaring - // config file. Resolved to an absolute path; its contents are fingerprinted separately. - ConfigFile string `toml:"config-file,omitempty" json:"configFile,omitempty" jsonschema:"title=Vendor configuration file,description=Path to a go-vendor-tools TOML file relative to the declaring component configuration. Replaces upstream settings when specified,example=go-vendor-tools.toml" fingerprint:"-"` - // PrepPackages supplies additional tools used by upstream prep commands. - PrepPackages []string `toml:"prep-packages,omitempty" json:"prepPackages,omitempty" jsonschema:"title=Prep packages,description=Additional RPM packages needed to execute the upstream prep section in mock"` -} - -// IsEnabled reports whether vendoring was explicitly enabled. -func (c *GoVendorConfig) IsEnabled() bool { - return c != nil && c.Enabled != nil && *c.Enabled -} - -// Validate checks configuration values before any source processing. -func (c *GoVendorConfig) Validate() error { - if c == nil { - return nil - } - - if c.ModuleDir != "" { - if err := fileutils.ValidateRelPath(c.ModuleDir); err != nil { - return fmt.Errorf("invalid 'module-dir':\n%w", err) - } - - if strings.ContainsAny(c.ModuleDir, "%\n\r") { - return errors.New("'module-dir' must not contain RPM macros or newlines") - } - } - - if strings.ContainsAny(c.ConfigFile, "\x00\r\n") { - return errors.New("'config-file' must be a local file path without NUL or newlines") - } - - for _, name := range c.PrepPackages { - if name == "" || strings.HasPrefix(name, "-") || strings.ContainsAny(name, "\r\n") { - return fmt.Errorf("invalid 'prep-packages' entry %#q", name) - } - } - - return nil -} - -// SourceContentIdentity hashes the selected configuration independently of its path. -// No configured file yields no identity; an explicitly empty file still has a hash. -func (c *GoVendorConfig) SourceContentIdentity(fs opctx.FS) (string, error) { - if c == nil || c.ConfigFile == "" { - return "", nil - } - - content, err := c.ReadConfigFile(fs) - if err != nil { - return "", err - } - - digest := sha256.Sum256([]byte(content)) - - return hex.EncodeToString(digest[:]), nil -} - -// ReadConfigFile reads and validates the explicitly selected native configuration. -// An empty file is a valid, intentional replacement; callers must not fall back to upstream settings. -func (c *GoVendorConfig) ReadConfigFile(fs opctx.FS) (string, error) { - data, err := fileutils.ReadFile(fs, c.ConfigFile) - if err != nil { - return "", fmt.Errorf("reading 'go-vendor.config-file' %#q:\n%w", c.ConfigFile, err) - } - - var settings map[string]any - if err := toml.Unmarshal(data, &settings); err != nil { - return "", fmt.Errorf("invalid TOML in 'go-vendor.config-file' %#q:\n%w", c.ConfigFile, err) - } - - if general, ok := settings["general"].(map[string]any); ok { - if _, exists := general["go_mod_dir"]; exists { - return "", fmt.Errorf("use 'module-dir' instead of 'general.go_mod_dir' in %#q", c.ConfigFile) - } - } - - return string(data), nil -} diff --git a/internal/projectconfig/govendor_loader_internal_test.go b/internal/projectconfig/govendor_loader_internal_test.go deleted file mode 100644 index a0af07a33..000000000 --- a/internal/projectconfig/govendor_loader_internal_test.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -package projectconfig - -import ( - "testing" - - "github.com/microsoft/azure-linux-dev-tools/internal/global/testctx" - "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 TestGoVendorConfigFileDeclarationAndInheritance(t *testing.T) { - ctx := testctx.NewCtx() - - files := map[string]string{ - "/project/azldev.toml": `includes = ["defaults/group.toml", "components/app.comp.toml"]`, - "/project/defaults/group.toml": ` -[component-groups.base] -components = ["app"] -[component-groups.base.default-component-config.go-vendor] -enabled = true -config-file = "go-vendor-tools.toml" -`, - "/project/components/app.comp.toml": `[components.app]`, - } - for path, content := range files { - require.NoError(t, fileutils.WriteFile(ctx.FS(), path, []byte(content), fileperms.PublicFile)) - } - - for _, withoutLockfile := range []bool{false, true} { - config, err := loadAndResolveProjectConfig(ctx.FS(), loadOptions{withoutLockfile: withoutLockfile}, - "/project/azldev.toml") - require.NoError(t, err) - resolved, err := ResolveComponentConfig(config.Components["app"], config.DefaultComponentConfig, - ComponentConfig{}, config.ComponentGroups, []string{"base"}) - require.NoError(t, err) - assert.Equal(t, "/project/defaults/go-vendor-tools.toml", resolved.GoVendor.ConfigFile) - assert.True(t, resolved.GoVendor.IsEnabled()) - } -} - -func TestGoVendorInlineConfigurationIsRejected(t *testing.T) { - for _, contents := range []string{ - "[components.app.go-vendor]\nenabled = true\ntool-config = '[archive]'", - "[components.app.go-vendor.tool-config.archive]\nuse_module_proxy = true", - } { - ctx := testctx.NewCtx() - require.NoError(t, fileutils.WriteFile(ctx.FS(), "/project/azldev.toml", []byte(contents), fileperms.PublicFile)) - _, err := loadAndResolveProjectConfig(ctx.FS(), loadOptions{}, "/project/azldev.toml") - require.Error(t, err) - } -} diff --git a/internal/projectconfig/govendor_test.go b/internal/projectconfig/govendor_test.go deleted file mode 100644 index 44a656321..000000000 --- a/internal/projectconfig/govendor_test.go +++ /dev/null @@ -1,163 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -package projectconfig_test - -import ( - "os" - "path/filepath" - "testing" - - "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/mitchellh/hashstructure/v2" - "github.com/pelletier/go-toml/v2" - "github.com/samber/lo" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestGoVendorConfig(t *testing.T) { - var config projectconfig.ComponentConfig - require.NoError(t, toml.Unmarshal([]byte(` -[go-vendor] -enabled = true -module-dir = "cmd/app" -prep-packages = ["git"] -config-file = "go-vendor-tools.toml" -`), &config)) - require.True(t, config.GoVendor.IsEnabled()) - require.NoError(t, config.GoVendor.Validate()) - resolved := config.WithAbsolutePaths("/project") - assert.Equal(t, filepath.Join("/project", "go-vendor-tools.toml"), resolved.GoVendor.ConfigFile) - assert.Equal(t, "go-vendor-tools.toml", config.GoVendor.ConfigFile) - assert.Equal(t, resolved.GoVendor, resolved.WithAbsolutePaths("/elsewhere").GoVendor) - require.NoError(t, config.MergeUpdatesFrom(&projectconfig.ComponentConfig{ - GoVendor: &projectconfig.GoVendorConfig{Enabled: lo.ToPtr(false)}, - })) - assert.False(t, config.GoVendor.IsEnabled(), "explicit false must override an inherited true") -} - -func TestGoVendorMergeDoesNotMutateDefaults(t *testing.T) { - for name, merge := range map[string]func(*projectconfig.ComponentConfig, *projectconfig.ComponentConfig) error{ - "updates": (*projectconfig.ComponentConfig).MergeUpdatesFrom, - "overrides": (*projectconfig.ComponentConfig).MergeOverridesFrom, - } { - t.Run(name, func(t *testing.T) { - defaults := projectconfig.ComponentConfig{GoVendor: &projectconfig.GoVendorConfig{ - ConfigFile: "defaults.toml", ModuleDir: "default-module", PrepPackages: []string{"patch"}, - }} - - var first projectconfig.ComponentConfig - require.NoError(t, merge(&first, &defaults)) - second := first - overrides := projectconfig.ComponentConfig{GoVendor: &projectconfig.GoVendorConfig{ - Enabled: lo.ToPtr(true), ModuleDir: "custom-module", - }} - require.NoError(t, merge(&first, &overrides)) - first.GoVendor.PrepPackages[0] = "changed" - - for _, unchanged := range []*projectconfig.ComponentConfig{&defaults, &second} { - assert.Nil(t, unchanged.GoVendor.Enabled) - assert.Equal(t, "default-module", unchanged.GoVendor.ModuleDir) - assert.Equal(t, "defaults.toml", unchanged.GoVendor.ConfigFile) - assert.Equal(t, []string{"patch"}, unchanged.GoVendor.PrepPackages) - } - - assert.True(t, first.GoVendor.IsEnabled()) - assert.Equal(t, "custom-module", first.GoVendor.ModuleDir) - assert.Equal(t, "custom-module", overrides.GoVendor.ModuleDir) - assert.True(t, overrides.GoVendor.IsEnabled()) - }) - } -} - -func TestGoVendorConfigValidation(t *testing.T) { - for _, config := range []*projectconfig.GoVendorConfig{ - {ModuleDir: "../outside"}, - {ModuleDir: "/absolute"}, - {ModuleDir: "%{macro}"}, - {ConfigFile: "bad\x00path"}, - {ConfigFile: "bad\npath"}, - {PrepPackages: []string{"--bad"}}, - {PrepPackages: []string{""}}, - } { - require.Error(t, config.Validate()) - } - - var absent *projectconfig.GoVendorConfig - assert.False(t, absent.IsEnabled()) - require.NoError(t, absent.Validate()) -} - -func TestGoVendorFingerprint(t *testing.T) { - empty := projectconfig.ComponentConfig{} - included, err := empty.HashInclude("GoVendor", nil) - require.NoError(t, err) - assert.False(t, included, "absent vendoring must not invalidate existing component fingerprints") - included, err = empty.HashInclude("Build", nil) - require.NoError(t, err) - assert.True(t, included) - - base := projectconfig.ComponentConfig{GoVendor: &projectconfig.GoVendorConfig{Enabled: lo.ToPtr(true)}} - original, err := hashstructure.Hash(base, hashstructure.FormatV2, &hashstructure.HashOptions{TagName: "fingerprint"}) - require.NoError(t, err) - - for _, config := range []*projectconfig.GoVendorConfig{ - {Enabled: lo.ToPtr(false)}, - {Enabled: lo.ToPtr(true), ModuleDir: "sub"}, - {Enabled: lo.ToPtr(true), PrepPackages: []string{"git"}}, - } { - changed := base - changed.GoVendor = config - hash, err := hashstructure.Hash(changed, hashstructure.FormatV2, &hashstructure.HashOptions{TagName: "fingerprint"}) - require.NoError(t, err) - assert.NotEqual(t, original, hash) - } -} - -func TestGoVendorConfigFileContentIdentity(t *testing.T) { - ctx := testctx.NewCtx() - - var absent *projectconfig.GoVendorConfig - - identity, err := absent.SourceContentIdentity(ctx.FS()) - require.NoError(t, err) - assert.Empty(t, identity) - - config := &projectconfig.GoVendorConfig{} - identity, err = config.SourceContentIdentity(ctx.FS()) - require.NoError(t, err) - assert.Empty(t, identity) - - config.ConfigFile = "/project/vendor.toml" - _, err = config.SourceContentIdentity(ctx.FS()) - require.ErrorIs(t, err, os.ErrNotExist) - - for _, contents := range []string{"", "# reviewed\n[archive]\nuse_module_proxy = true\n"} { - require.NoError(t, fileutils.WriteFile(ctx.FS(), config.ConfigFile, []byte(contents), fileperms.PublicFile)) - actual, err := config.ReadConfigFile(ctx.FS()) - require.NoError(t, err) - assert.Equal(t, contents, actual) - - identity, err = config.SourceContentIdentity(ctx.FS()) - require.NoError(t, err) - expected, err := fileutils.ComputeFileHash(ctx.FS(), fileutils.HashTypeSHA256, config.ConfigFile) - require.NoError(t, err) - assert.Equal(t, expected, identity) - } -} - -func TestGoVendorConfigFileValidation(t *testing.T) { - for _, contents := range []string{"[", "[general]\ngo_mod_dir = 'subdir'"} { - ctx := testctx.NewCtx() - require.NoError(t, fileutils.WriteFile(ctx.FS(), "/project/vendor.toml", []byte(contents), fileperms.PublicFile)) - - config := projectconfig.GoVendorConfig{ConfigFile: "/project/vendor.toml"} - _, err := config.ReadConfigFile(ctx.FS()) - require.Error(t, err) - assert.Contains(t, err.Error(), config.ConfigFile) - } -} diff --git a/internal/rpm/spec/govendor.go b/internal/rpm/spec/govendor.go deleted file mode 100644 index 050e87ff9..000000000 --- a/internal/rpm/spec/govendor.go +++ /dev/null @@ -1,384 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -package spec - -import ( - "errors" - "fmt" - "regexp" - "slices" - "strconv" - "strings" - - "github.com/kballard/go-shellquote" - "github.com/microsoft/azure-linux-dev-tools/internal/utils/fileutils" -) - -// GoVendorOptions names generated artifacts. All paths except ModuleDir are basenames. -type GoVendorOptions struct { - ArchiveName string - ConfigName string - ModuleDir string -} - -// GoVendorSpec is the common plan for converting or refreshing Go vendoring. -type GoVendorSpec struct { - Spec []byte - PrepSpec []byte - ArchiveFile string // Filename used inside generation staging. - ArchiveSuffix string // Required suffix of the RPM-expanded destination name, if any. - ConfigName string - ArchiveSource string // Existing Source tag to pin to the generated filename. - ExpectedLicense string // Empty: detect and update. Otherwise: verify and preserve. - AllowReplacement bool // Permit replacing the existing vendor payload and configuration. -} - -const goVendorEnvironment = `export GO111MODULE=on GOPROXY=off GOSUMDB=off GOTOOLCHAIN=local -export GOFLAGS="${GOFLAGS:+$GOFLAGS }-mod=vendor"` - -var goBuildRequirement = regexp.MustCompile(`^golang\([^)]+\)(\s*(>=|<=|=|>|<)\s*[^\s,]+)?$`) - -var ( - goVendorUnsupportedMacro = regexp.MustCompile( - `%(?:\{[!?]*)?(?:gopkg\w*|goinstall|gofiles?\w*|go_vendor_\w*|include)\b`) - goVendorRequiresMacro = regexp.MustCompile(`%(?:\{[!?]*)?go_generate_buildrequires\b`) - goVendorCheckMacro = regexp.MustCompile(`%(?:\{[!?]*)?gocheck\b`) -) - -// ConvertGoVendor changes only recognized Go application packaging constructs. -// It always uses the lossless tree, independently of the selected overlay editor. -// Unsupported Go macros and ambiguous section ownership fail before returning output. -func ConvertGoVendor(data []byte, options GoVendorOptions) (*GoVendorSpec, error) { - if err := options.validate(); err != nil { - return nil, err - } - - root, err := parseTree(strings.Split(strings.TrimSuffix(string(data), "\n"), "\n")) - if err != nil { - return nil, err - } - - tree := &specTree{root: root} - - configSource, err := existingVendorConfigSource(tree) - if err != nil { - return nil, err - } - - if configSource != "" { - if options.ModuleDir != "" && options.ModuleDir != "." { - return nil, errors.New("'module-dir' overrides are unsupported for already-vendored specs; " + - "retain the upstream module layout") - } - - return prepareExistingGoVendor(tree, configSource) - } - - if err := validateGoVendorTree(tree); err != nil { - return nil, err - } - - if err := convertGoVendorLines(tree, options.ModuleDir); err != nil { - return nil, err - } - - // Do not replace upstream prep or build scripts: capture the directory after - // their existing prep commands, including patches and module-file edits. - prep := tree.Section("%prep", "") - prep.PrependLines([]string{"export GOTOOLCHAIN=local"}) - prep.AppendLines([]string{"", `pwd -P > "%{_topdir}/azldev-go-module-root"`}) - - prepSpec := goVendorPrepSpec(tree, options.ArchiveName) - - sourceNumber, err := freeGoVendorSources(tree, options) - if err != nil { - return nil, err - } - - configRef := fmt.Sprintf("%%{SOURCE%d}", sourceNumber+1) - - extract := fmt.Sprintf("tar -xf %%{SOURCE%d}", sourceNumber) - if options.ModuleDir != "" { - extract += " -C " + shellquote.Join(options.ModuleDir) - } - - prep.AppendLines([]string{"", extract}) - tree.Section("", "").AppendLines([]string{ - fmt.Sprintf("Source%d: %s", sourceNumber, options.ArchiveName), - fmt.Sprintf("Source%d: %s", sourceNumber+1, options.ConfigName), - "BuildRequires: go-vendor-tools", - "BuildRequires: go-rpm-macros", - "BuildRequires: golang", - "%global gomodulesmode GO111MODULE=on", - "%global go_vendor_license_filelist() %{_topdir}/azldev-go-vendor-licenses.list", - "", - }) - - addGoVendorBuildSections(tree, options, configRef) - - return &GoVendorSpec{ - Spec: serializeGoVendorTree(tree), PrepSpec: prepSpec, - ArchiveFile: options.ArchiveName, ConfigName: options.ConfigName, - }, nil -} - -func addGoVendorBuildSections(tree *specTree, options GoVendorOptions, configRef string) { - requires := tree.Section("%generate_buildrequires", "") - if requires == nil { - blk := &block{Kind: sectionBlock, Name: "%generate_buildrequires", Header: "%generate_buildrequires"} - buildIndex := slices.Index(tree.root.Children, tree.Section("%build", "").block) - tree.root.Children = slices.Insert(tree.root.Children, buildIndex, blk) - requires = §ionHandle{block: blk, tree: tree} - } - - requires.PrependLines([]string{"%go_vendor_license_buildrequires -c " + configRef}) - - addGoVendorEnvironment(tree) - - tree.Section("%install", "").AppendLines([]string{ - "", goVendorInModule(options.ModuleDir, "%go_vendor_license_install -c "+configRef), - }) - // Licensing is a build invariant, even when the component disables %check. - tree.Section("%build", "").PrependLines([]string{ - goVendorInModule(options.ModuleDir, "%go_vendor_license_check -c "+configRef), - }) - files := tree.Section("%files", "") - files.block.Header += " -f %{go_vendor_license_filelist}" -} - -func (o GoVendorOptions) validate() error { - for _, name := range []string{o.ArchiveName, o.ConfigName} { - if err := fileutils.ValidateFilename(name); err != nil { - return fmt.Errorf("invalid Go vendor artifact name:\n%w", err) - } - - if strings.ContainsAny(name, "%\r\n") { - return errors.New("go vendor artifact name must not contain macros or newlines") - } - } - - if o.ModuleDir != "" { - if err := fileutils.ValidateRelPath(o.ModuleDir); err != nil { - return fmt.Errorf("invalid Go module directory:\n%w", err) - } - - if strings.ContainsAny(o.ModuleDir, "%\r\n") { - return errors.New("go module directory must not contain macros or newlines") - } - } - - return nil -} - -func serializeGoVendorTree(tree *specTree) []byte { - return []byte(strings.Join(serializeTree(tree.root), "\n") + "\n") -} - -func addGoVendorEnvironment(tree *specTree) { - for _, name := range []string{"%build", "%install", "%check", "%generate_buildrequires"} { - if section := tree.Section(name, ""); section != nil { - section.PrependLines([]string{goVendorEnvironment}) - } - } -} - -func goVendorPrepSpec(tree *specTree, archiveValue string) []byte { - prep := tree.Section("%prep", "") - prep.AppendLines([]string{ - "printf '%%s\\n' %{shescape:" + archiveValue + `} > "%{_topdir}/azldev-go-archive-name"`, - }) - - result := serializeGoVendorTree(tree) - prep.block.Children = prep.block.Children[:len(prep.block.Children)-1] - - return result -} - -// Finalize pins an existing archive reference before release/history processing, -// and updates the license only for newly converted specs. It does not mutate the plan. -func (p *GoVendorSpec) Finalize(archiveName, expression string) ([]byte, error) { - editor, err := openStructuralSpec(strings.NewReader(string(p.Spec))) - if err != nil { - return nil, err - } - - if p.ArchiveSource != "" { - if err := editor.UpdateExistingTag("", p.ArchiveSource, archiveName); err != nil { - return nil, err - } - } - - if p.ExpectedLicense == "" { - if err := editor.UpdateExistingTag("", "License", expression); err != nil { - return nil, err - } - } - - return []byte(strings.Join(editor.rawLines, "\n") + "\n"), nil -} - -func goVendorInModule(moduleDir, command string) string { - lines := []string{`( cd "$(cat "%{_topdir}/azldev-go-module-root")"`} - if moduleDir != "" { - lines = append(lines, "cd "+shellquote.Join(moduleDir)) - } - - lines = append(lines, command, ")") - - return strings.Join(lines, "\n") -} - -func validateGoVendorTree(tree *specTree) error { - if tree.HasSection("%sourcelist") { - return errors.New("go vendoring requires explicit Source tags instead of '%sourcelist'") - } - - for _, name := range []string{"", "%prep", "%build", "%install", "%files"} { - if err := validateGoVendorSection(tree, name, true); err != nil { - return err - } - } - - for _, name := range []string{"%check", "%generate_buildrequires"} { - if err := validateGoVendorSection(tree, name, false); err != nil { - return err - } - } - - var invalid error - - walkBlocks(tree.root, func(blk *block) bool { - if invalid != nil { - return false - } - - invalid = validateGoVendorBlock(blk) - - return true - }) - - return invalid -} - -func validateGoVendorSection(tree *specTree, name string, required bool) error { - sections := tree.Sections(name, "") - if len(sections) == 0 && !required { - return nil - } - - if len(sections) != 1 { - return fmt.Errorf("go vendoring requires one main-package %#q section; use overlays to disambiguate", name) - } - - if !slices.Contains(tree.root.Children, sections[0].block) { - return fmt.Errorf("go vendoring does not support conditional %#q sections; use an overlay", name) - } - - return nil -} - -func validateGoVendorBlock(blk *block) error { - if blk.Kind == macroDefBlock && (blk.Name == "gomodulesmode" || strings.HasPrefix(blk.Name, "go_vendor_")) { - return fmt.Errorf("explicit %#q conflicts with Go vendoring; remove it with an overlay", blk.Name) - } - - for _, line := range append([]string{blk.Header}, blk.Lines...) { - if strings.HasPrefix(strings.TrimSpace(line), "#") { - continue - } - - if macro := goVendorUnsupportedMacro.FindString(line); macro != "" { - return fmt.Errorf("unsupported Go vendoring macro %#q in %#q; adapt it with an overlay", macro, line) - } - - if blk.Kind == macroDefBlock && - (goVendorRequiresMacro.MatchString(line) || goVendorCheckMacro.MatchString(line) || - strings.Contains(line, "golang(")) { - return fmt.Errorf("go dependency or check logic inside a macro definition requires an explicit overlay: %#q", line) - } - - for _, macro := range []string{"-mod=mod", "GO111MODULE=off"} { - if strings.Contains(line, macro) { - return fmt.Errorf("unsupported Go vendoring construct %#q in %#q; adapt it with an overlay", macro, line) - } - } - } - - return nil -} - -func convertGoVendorLines(tree *specTree, moduleDir string) error { - return tree.VisitAllLines(func(section, _ string, line *lineHandle) error { - text := strings.TrimSpace(line.Text) - if strings.HasPrefix(text, "#") { - return nil - } - - if tag, value, ok := parseTagLine(text); ok && isTagBearingSection(section) && - strings.EqualFold(tag, "BuildRequires") && strings.Contains(value, "golang(") { - if !goBuildRequirement.MatchString(value) { - return fmt.Errorf("ambiguous Go BuildRequires %#q; split it into individual tags with an overlay", line.Text) - } - - line.Remove() - } - - switch { - case goVendorRequiresMacro.MatchString(text): - if text != "%go_generate_buildrequires" || section != "%generate_buildrequires" { - return fmt.Errorf("unsupported Go dependency generator %#q; adapt it with an overlay", text) - } - - line.Remove() - case goVendorCheckMacro.MatchString(text): - if text != "%gocheck" || section != "%check" { - return fmt.Errorf("unsupported Go check command %#q; use a module-aware check overlay", text) - } - - line.Replace(goVendorInModule(moduleDir, "%gotest ./...")) - } - - return nil - }) -} - -func freeGoVendorSources(tree *specTree, options GoVendorOptions) (int, error) { - used := make(map[int]bool) - - err := tree.VisitAllLines(func(section, _ string, line *lineHandle) error { - tag, value, ok := parseTagLine(line.Text) - if !ok || !isTagBearingSection(section) || !strings.HasPrefix(strings.ToLower(tag), "source") { - return nil - } - - suffix := tag[len("source"):] - number := 0 - - if suffix != "" { - var err error - - number, err = strconv.Atoi(suffix) - if err != nil || number < 0 { - return fmt.Errorf("cannot allocate vendor Source tags alongside %#q", tag) - } - } - - used[number] = true - - if value == options.ArchiveName || value == options.ConfigName { - return fmt.Errorf("generated Go vendor source collides with existing Source tag %#q", line.Text) - } - - return nil - }) - if err != nil { - return 0, err - } - - for number := 0; ; number++ { - if !used[number] && !used[number+1] { - return number, nil - } - } -} diff --git a/internal/rpm/spec/govendor_existing.go b/internal/rpm/spec/govendor_existing.go deleted file mode 100644 index 3013eacb7..000000000 --- a/internal/rpm/spec/govendor_existing.go +++ /dev/null @@ -1,232 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -package spec - -import ( - "errors" - "fmt" - "path/filepath" - "regexp" - "slices" - "strings" - - "github.com/microsoft/azure-linux-dev-tools/internal/utils/fileutils" -) - -var ( - existingVendorLicense = regexp.MustCompile( - `^%go_vendor_license_(?:buildrequires|install|check)\s+-c\s+%\{(?:S:|SOURCE)([0-9]+)\}\s*$`) - existingVendorExtract = regexp.MustCompile(`^tar\s+-xf\s+%\{(?:S:|SOURCE)([0-9]+)\}\s*$`) - existingVendorSetup = regexp.MustCompile(`%(?:\{[!?]*)?(?:(?:auto)?setup|goprep)\b.*\s-[a-zA-Z]*[ab]`) - existingVendorChdir = regexp.MustCompile(`^(?:cd|pushd|popd|%(?:auto)?setup|%goprep)\b`) -) - -func prepareExistingGoVendor(tree *specTree, configSource string) (*GoVendorSpec, error) { - if err := validateGoVendorSection(tree, "%prep", true); err != nil { - return nil, err - } - - configName, err := existingVendorTagValue(tree, "Source"+configSource) - if err != nil { - return nil, err - } - - if err := fileutils.ValidateFilename(configName); err != nil || strings.Contains(configName, "%") { - return nil, fmt.Errorf("existing Go vendor config Source%s must name a plain file, got %#q", configSource, configName) - } - - extraction, sourceNumber, err := takeExistingVendorExtraction(tree) - if err != nil { - return nil, err - } - - if sourceNumber == configSource { - return nil, errors.New("go vendor archive and tool configuration cannot use the same Source tag") - } - - archiveValue, err := existingVendorTagValue(tree, "Source"+sourceNumber) - if err != nil { - return nil, err - } - - suffix, err := existingVendorArchiveSuffix(archiveValue) - if err != nil { - return nil, err - } - - license, err := existingVendorLicenseExpression(tree) - if err != nil { - return nil, err - } - - // Keep upstream's Source numbers, macro settings, file lists, and custom commands. - for _, sectionName := range []string{"%build", "%install", "%check", "%generate_buildrequires"} { - if err := validateGoVendorSection(tree, sectionName, false); err != nil { - return nil, err - } - } - - // Regeneration already includes prep's module edits. Extract the resulting - // module files after those edits so the RPM build cannot apply them twice. - tree.Section("%prep", "").AppendLines([]string{extraction}) - addGoVendorEnvironment(tree) - finalSpec := serializeGoVendorTree(tree) - - if err := removeExistingVendorInput(tree, sourceNumber, extraction); err != nil { - return nil, err - } - - tree.Section("%prep", "").AppendLines([]string{ - `pwd -P > "%{_topdir}/azldev-go-module-root"`, - }) - - return &GoVendorSpec{ - Spec: finalSpec, PrepSpec: goVendorPrepSpec(tree, archiveValue), - ArchiveFile: "azldev-generated-vendor" + suffix, ArchiveSuffix: suffix, ConfigName: configName, - ArchiveSource: "Source" + sourceNumber, ExpectedLicense: license, AllowReplacement: true, - }, nil -} - -func existingVendorLicenseExpression(tree *specTree) (string, error) { - license, err := existingVendorTagValue(tree, "License") - if err != nil { - return "", err - } - - if strings.ContainsAny(license, "%\r\n") || license == "" { - return "", errors.New("regenerating an existing Go vendor archive requires an explicit main-package 'License' tag") - } - - return license, nil -} - -// An empty result means the spec has no existing vendor license commands. -func existingVendorConfigSource(tree *specTree) (string, error) { - source := "" - - err := tree.VisitAllLines(func(_, _ string, line *lineHandle) error { - text := strings.TrimSpace(line.Text) - if !strings.HasPrefix(text, "%go_vendor_license_") { - return nil - } - - matches := existingVendorLicense.FindStringSubmatch(text) - if len(matches) == 0 { - return fmt.Errorf("unsupported existing Go vendor license command %#q", text) - } - - if source != "" && source != matches[1] { - return errors.New("existing Go vendor license commands reference different configuration sources") - } - - source = matches[1] - - return nil - }) - if err != nil { - return "", err - } - - return source, nil -} - -func takeExistingVendorExtraction(tree *specTree) (line, source string, err error) { - count := 0 - - err = tree.Section("%prep", "").VisitLines(func(candidate *lineHandle) error { - text := strings.TrimSpace(candidate.Text) - if existingVendorSetup.MatchString(text) { - return errors.New("secondary-source extraction in '%setup' or '%autosetup' makes Go vendoring ambiguous") - } - - if count > 0 && existingVendorChdir.MatchString(text) { - return errors.New("directory changes after Go vendor extraction require an explicit prep overlay") - } - - matches := existingVendorExtract.FindStringSubmatch(text) - if strings.HasPrefix(text, "tar ") && strings.Contains(text, "%{S") && len(matches) == 0 { - return fmt.Errorf("unsupported secondary-source extraction %#q", text) - } - - if len(matches) != 0 { - if !slices.Contains(tree.Section("%prep", "").block.Children, candidate.block) { - return errors.New("conditional Go vendor extraction requires an explicit preparation strategy") - } - - count++ - line = text - source = matches[1] - - candidate.Remove() - } - - return nil - }) - if err != nil { - return "", "", err - } - - if count != 1 { - return "", "", errors.New("existing Go vendoring requires one unambiguous 'tar -xf %{S:N}' prep command") - } - - return line, source, nil -} - -func existingVendorTagValue(tree *specTree, name string) (string, error) { - var values []string - - err := tree.VisitAllLines(func(section, pkg string, line *lineHandle) error { - tag, value, ok := parseTagLine(line.Text) - if ok && section == "" && pkg == "" && strings.EqualFold(tag, name) { - if !slices.Contains(tree.Section("", "").block.Children, line.block) { - return fmt.Errorf("existing Go vendoring requires an unconditional %#q tag", name) - } - - values = append(values, value) - } - - return nil - }) - if err != nil { - return "", err - } - - if len(values) != 1 { - return "", fmt.Errorf("expected exactly one %#q declaration for existing Go vendoring", name) - } - - return values[0], nil -} - -func existingVendorArchiveSuffix(value string) (string, error) { - if strings.Contains(value, "://") { - return "", errors.New("existing Go vendor archive must use a local source filename") - } - - extension := filepath.Ext(value) - switch extension { - case ".bz2", ".gz", ".xz", ".zst", ".zstd": - return ".tar" + extension, nil - case ".tar": - return ".tar", nil - default: - return "", fmt.Errorf("unsupported existing Go vendor archive format %#q", value) - } -} - -func removeExistingVendorInput(tree *specTree, sourceNumber, extraction string) error { - return tree.VisitAllLines(func(section, pkg string, line *lineHandle) error { - tag, _, ok := parseTagLine(line.Text) - if ok && section == "" && pkg == "" && strings.EqualFold(tag, "Source"+sourceNumber) { - line.Remove() - } - - if section == "%prep" && strings.TrimSpace(line.Text) == extraction { - line.Remove() - } - - return nil - }) -} diff --git a/internal/rpm/spec/govendor_existing_test.go b/internal/rpm/spec/govendor_existing_test.go deleted file mode 100644 index 35c1ada1a..000000000 --- a/internal/rpm/spec/govendor_existing_test.go +++ /dev/null @@ -1,137 +0,0 @@ -// 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 existingVendorSpec() string { - return strings.Join([]string{ - "Name: app", "Version: 1.2", "Release: %autorelease", "Summary: Application", - "License: MIT AND Apache-2.0", - "Source0: app-%{version}.tar.gz", - "Source5: app-%{version}-vendor.tar.bz2", - "Source8: go-vendor-tools.toml", - "Source9: app.conf", - "BuildRequires: go-vendor-tools", "Requires: runtime-helper", - "%description", "Application", "%prep", "%goprep -p1", - "tar -xf %{S:5}", "sed -i 's/old/new/' go.mod", "cp %{S:9} .", - "%generate_buildrequires", "%go_vendor_license_buildrequires -c %{S:8}", - "%build", "%global gomodulesmode GO111MODULE=on", "%gobuild -o app .", - "%install", "%go_vendor_license_install -c %{S:8}", - "install -D app %{buildroot}%{_bindir}/app", - "%check", "%go_vendor_license_check -c %{S:8}", "%gocheck2 -t integration", - "%files -f %{go_vendor_license_filelist}", "%{_bindir}/app", "%changelog", "%autochangelog", "", - }, "\n") -} - -func TestExistingGoVendoringPreservesPackaging(t *testing.T) { - for _, version := range []string{"1.2", "2.4"} { - input := strings.ReplaceAll(existingVendorSpec(), "Version: 1.2", "Version: "+version) - result, err := spec.ConvertGoVendor([]byte(input), spec.GoVendorOptions{ - ArchiveName: "app-vendor.tar.bz2", ConfigName: "azldev-go-vendor.toml", - }) - require.NoError(t, err) - assert.True(t, result.AllowReplacement) - assert.Equal(t, "go-vendor-tools.toml", result.ConfigName) - assert.Equal(t, ".tar.bz2", result.ArchiveSuffix) - assert.Equal(t, "MIT AND Apache-2.0", result.ExpectedLicense) - - for _, line := range strings.Split(input, "\n") { - assert.Contains(t, string(result.Spec), line) - } - - assert.NotContains(t, string(result.Spec), "azldev-go-vendor.toml") - assert.NotContains(t, string(result.Spec), "azldev-go-module-root") - assert.Contains(t, string(result.Spec), "GOPROXY=off") - assert.NotContains(t, string(result.PrepSpec), "Source5:") - assert.NotContains(t, string(result.PrepSpec), "tar -xf %{S:5}") - assert.Contains(t, string(result.PrepSpec), "sed -i 's/old/new/' go.mod") - assert.Contains(t, string(result.PrepSpec), "%{shescape:app-%{version}-vendor.tar.bz2}") - assert.Contains(t, string(result.PrepSpec), `pwd -P > "%{_topdir}/azldev-go-module-root"`) - } -} - -func TestExistingGoVendoringRejectsModuleOverride(t *testing.T) { - result, err := spec.ConvertGoVendor([]byte(existingVendorSpec()), spec.GoVendorOptions{ - ArchiveName: "app-vendor.tar.bz2", ConfigName: "vendor.toml", ModuleDir: "cmd/app", - }) - require.ErrorContains(t, err, "'module-dir' overrides") - assert.Nil(t, result) -} - -func TestExistingGoVendoringRejectsAmbiguousInputs(t *testing.T) { - for name, input := range map[string]string{ - "multiple extractions": strings.ReplaceAll(existingVendorSpec(), "%goprep -p1", "%goprep -p1\ntar -xf %{S:9}"), - "autosetup secondary": strings.ReplaceAll(existingVendorSpec(), "%goprep -p1", "%autosetup -a 1"), - "setup secondary": strings.ReplaceAll(existingVendorSpec(), "%goprep -p1", "%setup -qb1"), - "braced autosetup secondary": strings.ReplaceAll(existingVendorSpec(), "%goprep -p1", "%{autosetup -a 1}"), - "other tar flags": strings.ReplaceAll(existingVendorSpec(), "%goprep -p1", "%goprep -p1\ntar -xjf %{S:9}"), - "directory after extraction": strings.ReplaceAll(existingVendorSpec(), "sed -i 's/old/new/' go.mod", "cd submodule"), - "no extraction": strings.ReplaceAll(existingVendorSpec(), "tar -xf %{S:5}", ""), - "mismatched config": strings.ReplaceAll(existingVendorSpec(), - "%go_vendor_license_check -c %{S:8}", "%go_vendor_license_check -c %{S:9}"), - "dynamic config": strings.ReplaceAll(existingVendorSpec(), "go-vendor-tools.toml", "%{name}.toml"), - "unknown compression": strings.ReplaceAll(existingVendorSpec(), "-vendor.tar.bz2", "-vendor.zip"), - "macro license": strings.ReplaceAll(existingVendorSpec(), "License: MIT AND Apache-2.0", "License: %{license}"), - "missing source": strings.ReplaceAll(existingVendorSpec(), "Source5:", "Source6:"), - "conditional extraction": strings.ReplaceAll(existingVendorSpec(), - "tar -xf %{S:5}", "%if 1\ntar -xf %{S:5}\n%endif"), - "conditional source": strings.ReplaceAll(existingVendorSpec(), - "Source5: app-%{version}-vendor.tar.bz2", "%if 1\nSource5: app-%{version}-vendor.tar.bz2\n%endif"), - "conditional license": strings.ReplaceAll(existingVendorSpec(), - "License: MIT AND Apache-2.0", "%if 1\nLicense: MIT AND Apache-2.0\n%endif"), - } { - t.Run(name, func(t *testing.T) { - result, err := spec.ConvertGoVendor([]byte(input), spec.GoVendorOptions{ - ArchiveName: "app-vendor.tar.bz2", ConfigName: "azldev-go-vendor.toml", - }) - require.Error(t, err) - assert.Nil(t, result) - }) - } -} - -func TestExistingGoVendorExtractsAfterModulePatches(t *testing.T) { - input := strings.ReplaceAll(existingVendorSpec(), "%goprep -p1", "%setup -q") - input = strings.ReplaceAll(input, "sed -i 's/old/new/' go.mod", "%autopatch -p1\nsed -i 's/old/new/' go.mod") - result, err := spec.ConvertGoVendor([]byte(input), spec.GoVendorOptions{ - ArchiveName: "app-vendor.tar.bz2", ConfigName: "vendor.toml", - }) - require.NoError(t, err) - - output := string(result.Spec) - assert.Less(t, strings.Index(output, "%autopatch -p1"), strings.Index(output, "tar -xf %{S:5}")) - assert.Less(t, strings.Index(output, "sed -i"), strings.Index(output, "tar -xf %{S:5}")) - assert.Less(t, strings.Index(output, "cp %{S:9} ."), strings.Index(output, "tar -xf %{S:5}")) - assert.Contains(t, string(result.PrepSpec), "%autopatch -p1") - assert.NotContains(t, string(result.PrepSpec), "tar -xf %{S:5}") -} - -func TestExistingGoVendorPinsExpandedArchiveBeforeReleaseChanges(t *testing.T) { - input := strings.ReplaceAll(existingVendorSpec(), "app-%{version}-vendor", "app-%{version}-%{release}-vendor") - result, err := spec.ConvertGoVendor([]byte(input), spec.GoVendorOptions{ - ArchiveName: "app-vendor.tar.bz2", ConfigName: "vendor.toml", - }) - require.NoError(t, err) - final, err := result.Finalize("app-1.2-7-vendor.tar.bz2", "MIT AND Apache-2.0") - require.NoError(t, err) - assert.Contains(t, string(final), "Source5: app-1.2-7-vendor.tar.bz2") - assert.NotContains(t, string(final), "app-%{version}-%{release}-vendor") - assert.Contains(t, string(result.Spec), "Source5: app-%{version}-%{release}-vendor.tar.bz2", - "finalization must not mutate the plan") - editor, err := spec.OpenSpec(strings.NewReader(string(final)), spec.WithEditor(spec.EditorStructural)) - require.NoError(t, err) - require.NoError(t, editor.UpdateExistingTag("", "Release", "8")) - - var output strings.Builder - require.NoError(t, editor.Serialize(&output)) - assert.Contains(t, output.String(), "Source5: app-1.2-7-vendor.tar.bz2") -} diff --git a/internal/rpm/spec/govendor_test.go b/internal/rpm/spec/govendor_test.go deleted file mode 100644 index a29a44a3f..000000000 --- a/internal/rpm/spec/govendor_test.go +++ /dev/null @@ -1,203 +0,0 @@ -// 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 vendorInput() string { - return strings.Join([]string{ - "# Upstream customization", - "%global goipath example.com/app", - "Name: app", - "Version: 1.2", - "Release: %autorelease", - "Summary: App", - "License: MIT", - "Source0: app-%{version}.tar.gz", - "Source1: app.service", - "Source9999: app.macros", - "Patch0: fix.patch", - "BuildRequires: golang(example.com/dep) >= 1.0", - "BuildRequires: gcc", - "Requires: systemd", - "", - "%description", - "App description", - "%package tools", - "Summary: Tools", - "Requires: app = %{version}-%{release}", - "%description tools", - "Tool description", - "%prep", - "%goprep -p1", - "sed -i 's/old/new/' go.mod", - "%generate_buildrequires", - "%go_generate_buildrequires", - "echo custom-build-dependency", - "%build", - "%gobuild -o app %{goipath}", - "%install", - "install -D app %{buildroot}%{_bindir}/app", - "%check", - "%if %{with check}", - "%gocheck", - "./custom-test", - "%endif", - "%files", - "%{_bindir}/app", - "%files tools", - "%{_bindir}/tool", - "%changelog", - "%autochangelog", - "", - }, "\n") -} - -func TestConvertGoVendorPreservesUpstream(t *testing.T) { - for _, version := range []string{"1.2", "2.7"} { - t.Run(version, func(t *testing.T) { - input := strings.ReplaceAll(vendorInput(), "Version: 1.2", "Version: "+version) - result, err := spec.ConvertGoVendor([]byte(input), spec.GoVendorOptions{ - ArchiveName: "app-vendor.tar.bz2", ConfigName: "vendor.toml", - }) - require.NoError(t, err) - - output := string(result.Spec) - for _, line := range []string{ - "# Upstream customization", "Version: " + version, "Release: %autorelease", - "Source0: app-%{version}.tar.gz", "Source1: app.service", "Source9999: app.macros", - "Patch0: fix.patch", "BuildRequires: gcc", "Requires: systemd", - "%package tools", "Requires: app = %{version}-%{release}", - "%goprep -p1", "sed -i 's/old/new/' go.mod", "echo custom-build-dependency", - "%gobuild -o app %{goipath}", "install -D app %{buildroot}%{_bindir}/app", - "%if %{with check}\n" + - `( cd "$(cat "%{_topdir}/azldev-go-module-root")"` + "\n%gotest ./...\n)\n./custom-test\n%endif", - "%files tools\n%{_bindir}/tool", "%autochangelog", - "Source2: app-vendor.tar.bz2", "Source3: vendor.toml", "tar -xf %{SOURCE2}", - "%go_vendor_license_buildrequires -c %{SOURCE3}", - "%go_vendor_license_check -c %{SOURCE3}", - "%go_vendor_license_install -c %{SOURCE3}", - "%files -f %{go_vendor_license_filelist}", - "GOPROXY=off", "-mod=vendor", "%global gomodulesmode GO111MODULE=on", - } { - assert.Contains(t, output, line) - } - - assert.NotContains(t, output, "BuildRequires: golang(") - assert.NotContains(t, output, "%go_generate_buildrequires") - assert.Contains(t, output, `pwd -P > "%{_topdir}/azldev-go-module-root"`) - assert.Contains(t, output, `%global go_vendor_license_filelist() %{_topdir}/azldev-go-vendor-licenses.list`) - assert.Contains(t, string(result.PrepSpec), "Release: %autorelease") - assert.Contains(t, string(result.PrepSpec), `pwd -P > "%{_topdir}/azldev-go-module-root"`) - assert.Contains(t, string(result.PrepSpec), "sed -i 's/old/new/' go.mod") - assert.NotContains(t, string(result.PrepSpec), "Source2: app-vendor.tar.bz2") - assert.Contains(t, string(result.PrepSpec), "%{shescape:app-vendor.tar.bz2}") - assert.False(t, result.AllowReplacement) - assert.Empty(t, result.ExpectedLicense) - assert.Contains(t, string(result.PrepSpec), "%autochangelog") - - _, err = spec.OpenSpec(strings.NewReader(output), spec.WithEditor(spec.EditorStructural)) - require.NoError(t, err) - }) - } -} - -func TestConvertGoVendorRejectsAmbiguity(t *testing.T) { - for name, input := range map[string]string{ - "development subpackages": strings.ReplaceAll(vendorInput(), "%package tools", "%gopkg\n%package tools"), - "mixed requirements": strings.ReplaceAll(vendorInput(), - "golang(example.com/dep) >= 1.0", "gcc, golang(example.com/dep)"), - "check flags": strings.ReplaceAll(vendorInput(), "%gocheck", "%gocheck -z foo"), - "generator shell": strings.ReplaceAll(vendorInput(), - "%go_generate_buildrequires", "%go_generate_buildrequires | cat"), - "conditional prep": strings.ReplaceAll(vendorInput(), - "%prep\n%goprep -p1", "%if 1\n%prep\n%goprep -p1\n%endif"), - "module mode conflict": "%global gomodulesmode GO111MODULE=off\n" + vendorInput(), - "module mode override": "%global gomodulesmode GO111MODULE=on\n" + vendorInput(), - "license check override": "%global go_vendor_license_check_disable 1\n" + vendorInput(), - "existing vendor config": strings.ReplaceAll(vendorInput(), "app.service", "vendor.toml"), - "missing install": strings.ReplaceAll(vendorInput(), "%install", "# install"), - "macro source index": strings.ReplaceAll(vendorInput(), "Source1:", "Source%{number}:"), - "already vendored": strings.ReplaceAll(vendorInput(), "%gocheck", "%go_vendor_license_check"), - "braced generator": strings.ReplaceAll(vendorInput(), - "%go_generate_buildrequires", "%{go_generate_buildrequires}"), - "braced devel macro": strings.ReplaceAll(vendorInput(), "%package tools", "%{gopkg}\n%package tools"), - "hidden generator": "%global dependencies %{go_generate_buildrequires}\n" + vendorInput(), - "go filelist": strings.ReplaceAll(vendorInput(), "%files\n", "%files -f %{gofilelist}\n"), - "unsupported after comment": "# unrelated comment\n%gopkg\n" + vendorInput(), - } { - t.Run(name, func(t *testing.T) { - result, err := spec.ConvertGoVendor([]byte(input), spec.GoVendorOptions{ - ArchiveName: "app-vendor.tar.bz2", ConfigName: "vendor.toml", - }) - require.Error(t, err) - assert.Nil(t, result) - }) - } -} - -func TestConvertGoVendorModuleDirAndStaticRequires(t *testing.T) { - input := strings.ReplaceAll(vendorInput(), - "%generate_buildrequires\n%go_generate_buildrequires\necho custom-build-dependency\n", "") - input = strings.ReplaceAll(input, "%changelog\n%autochangelog\n", "") - result, err := spec.ConvertGoVendor([]byte(input), spec.GoVendorOptions{ - ArchiveName: "app-vendor.tar.bz2", ConfigName: "vendor.toml", ModuleDir: "cmd/app", - }) - require.NoError(t, err) - assert.Contains(t, string(result.Spec), "tar -xf %{SOURCE2} -C cmd/app") - assert.Contains(t, string(result.Spec), "cd cmd/app\n%go_vendor_license_install") - assert.Contains(t, string(result.Spec), - `( cd "$(cat "%{_topdir}/azldev-go-module-root")"`+"\ncd cmd/app\n%gotest ./...\n)") - assert.Contains(t, string(result.Spec), `( cd "$(cat "%{_topdir}/azldev-go-module-root")"`) - assert.Contains(t, string(result.Spec), "%generate_buildrequires\n") -} - -func TestConvertGoVendorRejectsUnsafeOptions(t *testing.T) { - for _, options := range []spec.GoVendorOptions{ - {ArchiveName: "../vendor.tar.bz2", ConfigName: "config"}, - {ArchiveName: "vendor", ConfigName: "%{name}"}, - {ArchiveName: "vendor", ConfigName: "config", ModuleDir: "../escape"}, - {ArchiveName: "vendor", ConfigName: "config", ModuleDir: "%{bad}"}, - } { - _, err := spec.ConvertGoVendor([]byte(vendorInput()), options) - require.Error(t, err) - } -} - -func TestConvertGoVendorPreservesStaticReleaseAndCustomDirectories(t *testing.T) { - input := strings.ReplaceAll(vendorInput(), "Release: %autorelease", "Release: 42%{?dist}") - input = strings.ReplaceAll(input, "%check", "cd assets\n%check") - result, err := spec.ConvertGoVendor([]byte(input), spec.GoVendorOptions{ - ArchiveName: "app-vendor.tar.bz2", ConfigName: "vendor.toml", - }) - require.NoError(t, err) - assert.Contains(t, string(result.PrepSpec), "Release: 42%{?dist}") - assert.Contains(t, string(result.Spec), "cd assets") - assert.Contains(t, string(result.Spec), - `( cd "$(cat "%{_topdir}/azldev-go-module-root")"`+"\n%go_vendor_license_install") - assert.Contains(t, string(result.Spec), - "%global go_vendor_license_filelist() %{_topdir}/azldev-go-vendor-licenses.list") -} - -func TestConvertGoVendorPreservesNonTagsAndComments(t *testing.T) { - script := "cat <<'EOF' > metadata\nBuildRequires: golang(not-a-dependency)\nSource2: not-a-source\nEOF\n" - input := strings.ReplaceAll(vendorInput(), "%gobuild", script+"%gobuild") - input = "# %gopkg is intentionally not invoked\n" + input - input = strings.ReplaceAll(input, "%files\n", "%files\n# app files\n") - result, err := spec.ConvertGoVendor([]byte(input), spec.GoVendorOptions{ - ArchiveName: "app-vendor.tar.bz2", ConfigName: "vendor.toml", - }) - require.NoError(t, err) - assert.Contains(t, string(result.Spec), script) - assert.Contains(t, string(result.Spec), "Source2: app-vendor.tar.bz2") - assert.Contains(t, string(result.Spec), "# %gopkg is intentionally not invoked") - assert.Contains(t, string(result.Spec), "%files -f %{go_vendor_license_filelist}\n# app files") -} diff --git a/internal/utils/fileutils/copy.go b/internal/utils/fileutils/copy.go index d0002e7c0..790822976 100644 --- a/internal/utils/fileutils/copy.go +++ b/internal/utils/fileutils/copy.go @@ -18,14 +18,11 @@ import ( type CopyFileOptions struct { // Whether or not to preserve POSIX mode bits on files. Does *not* apply to directories. PreserveFileMode bool - // NoFollow requires a regular source file and rejects final-component symlinks. - NoFollow bool } // Copies the contents of an existing file to a new file at the given destination path. // May preserve mode bits if "options" says so but does *not* preserve ownership, timestamps, -// or other metadata. Follows source symlinks unless [CopyFileOptions.NoFollow] is set. -// Is enlightened to skip copying in dry-run mode. +// or other metadata. *Does* follow symlinks. Is enlightened to skip copying in dry-run mode. func CopyFile(dryRunnable opctx.DryRunnable, fs opctx.FS, sourcePath, destPath string, options CopyFileOptions) error { return CopyFileCrossFS(dryRunnable, fs, sourcePath, fs, destPath, options) } @@ -33,8 +30,7 @@ func CopyFile(dryRunnable opctx.DryRunnable, fs opctx.FS, sourcePath, destPath s // Copies the contents of an existing file to a new file at the given destination path, // potentially across two [opctx.FS] filesystem instances. May preserve mode bits if // "options" says so but does *not* preserve ownership, timestamps, or other metadata. -// Follows source symlinks unless [CopyFileOptions.NoFollow] is set. -// Is enlightened to skip copying in dry-run mode. +// *Does* follow symlinks. Is enlightened to skip copying in dry-run mode. func CopyFileCrossFS( dryRunnable opctx.DryRunnable, sourceFS opctx.FS, sourcePath string, @@ -71,14 +67,7 @@ func copyFileCrossFS( destFileMode = stat.Mode() } - var sourceFile opctx.File - - if options.NoFollow { - sourceFile, err = OpenRegularFileNoFollow(sourceFS, sourcePath) - } else { - sourceFile, err = sourceFS.Open(sourcePath) - } - + sourceFile, err := sourceFS.Open(sourcePath) if err != nil { err = fmt.Errorf("failed to open copy source '%s':\n%w", sourcePath, err) diff --git a/internal/utils/fileutils/file.go b/internal/utils/fileutils/file.go index 50e9d5dd3..52fbcbd3e 100644 --- a/internal/utils/fileutils/file.go +++ b/internal/utils/fileutils/file.go @@ -14,7 +14,6 @@ import ( "github.com/bmatcuk/doublestar/v4" "github.com/microsoft/azure-linux-dev-tools/internal/global/opctx" "github.com/spf13/afero" - "golang.org/x/sys/unix" ) // Adaptation of [os.WriteFile] that works with [opctx.FS]. @@ -29,31 +28,6 @@ func ReadFile(fs opctx.FS, filename string) ([]byte, error) { return afero.ReadFile(fs, filename) } -// OpenRegularFileNoFollow atomically rejects final-component symlinks and checks -// the opened descriptor rather than a path that could change before reading. -// The parent directory must be trusted. Nonblocking mode avoids opening a FIFO indefinitely. -func OpenRegularFileNoFollow(fs opctx.FS, filename string) (opctx.File, error) { - file, err := fs.OpenFile(filename, os.O_RDONLY|unix.O_NOFOLLOW|unix.O_NONBLOCK, 0) - if err != nil { - return nil, fmt.Errorf("opening regular file %#q without following symlinks:\n%w", filename, err) - } - - info, err := file.Stat() - if err != nil { - file.Close() - - return nil, fmt.Errorf("checking opened file %#q:\n%w", filename, err) - } - - if !info.Mode().IsRegular() { - file.Close() - - return nil, fmt.Errorf("%#q is not a regular file", filename) - } - - return file, nil -} - // Adaptation of [filepath.Glob] that works with [opctx.FS] and also uses the // [doublestar] package to supports standard double-star globs ('**'). func Glob(fs opctx.FS, pattern string, opts ...doublestar.GlobOption) ([]string, error) { diff --git a/internal/utils/fileutils/nofollow_test.go b/internal/utils/fileutils/nofollow_test.go deleted file mode 100644 index 9e87e3afc..000000000 --- a/internal/utils/fileutils/nofollow_test.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -package fileutils_test - -import ( - "io" - "os" - "path/filepath" - "testing" - - "github.com/microsoft/azure-linux-dev-tools/internal/global/opctx/opctx_test" - "github.com/microsoft/azure-linux-dev-tools/internal/global/testctx" - "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" - "golang.org/x/sys/unix" -) - -func TestOpenRegularFileNoFollow(t *testing.T) { - ctx := testctx.NewCtx() - require.NoError(t, fileutils.WriteFile(ctx.FS(), "/regular", []byte("contents"), fileperms.PublicFile)) - file, err := fileutils.OpenRegularFileNoFollow(ctx.FS(), "/regular") - require.NoError(t, err) - - defer file.Close() - - data, err := io.ReadAll(file) - require.NoError(t, err) - assert.Equal(t, "contents", string(data)) - - missing, err := fileutils.OpenRegularFileNoFollow(ctx.FS(), "/missing") - require.ErrorIs(t, err, os.ErrNotExist) - assert.Nil(t, missing) - require.NoError(t, fileutils.MkdirAll(ctx.FS(), "/directory")) - directory, err := fileutils.OpenRegularFileNoFollow(ctx.FS(), "/directory") - require.ErrorContains(t, err, "not a regular file") - assert.Nil(t, directory) -} - -func TestOpenRegularFileNoFollowFlagsAndStatErrors(t *testing.T) { - ctrl := gomock.NewController(t) - mockFS := opctx_test.NewMockFS(ctrl) - flags := os.O_RDONLY | unix.O_NOFOLLOW | unix.O_NONBLOCK - mockFS.EXPECT().OpenFile("/denied", flags, os.FileMode(0)).Return(nil, os.ErrPermission) - file, err := fileutils.OpenRegularFileNoFollow(mockFS, "/denied") - require.ErrorIs(t, err, os.ErrPermission) - assert.Nil(t, file) - - opened := opctx_test.NewMockFile(ctrl) - mockFS.EXPECT().OpenFile("/bad-stat", flags, os.FileMode(0)).Return(opened, nil) - opened.EXPECT().Stat().Return(nil, os.ErrPermission) - opened.EXPECT().Close().Return(nil) - - file, err = fileutils.OpenRegularFileNoFollow(mockFS, "/bad-stat") - require.ErrorIs(t, err, os.ErrPermission) - assert.Nil(t, file) -} - -// Kernel-enforced symlink rejection requires a real filesystem. -func TestCopyFileNoFollowRejectsSymlinks(t *testing.T) { - ctx := testctx.NewCtx(testctx.WithHostFS()) - root := t.TempDir() - target, link, output := filepath.Join(root, "target"), filepath.Join(root, "link"), filepath.Join(root, "output") - require.NoError(t, fileutils.WriteFile(ctx.FS(), target, []byte("host-only contents"), fileperms.PublicFile)) - require.NoError(t, os.Symlink(target, link)) - err := fileutils.CopyFile(ctx, ctx.FS(), link, output, fileutils.CopyFileOptions{NoFollow: true}) - require.ErrorContains(t, err, "without following symlinks") - exists, err := fileutils.Exists(ctx.FS(), output) - require.NoError(t, err) - assert.False(t, exists) -} diff --git a/scenario/__snapshots__/TestSnapshotsContainer_config_generate-schema_stdout_1.snap b/scenario/__snapshots__/TestSnapshotsContainer_config_generate-schema_stdout_1.snap index 9259ce684..9cf47bd35 100755 --- a/scenario/__snapshots__/TestSnapshotsContainer_config_generate-schema_stdout_1.snap +++ b/scenario/__snapshots__/TestSnapshotsContainer_config_generate-schema_stdout_1.snap @@ -150,11 +150,6 @@ "title": "Source files", "description": "Source files to download for this component" }, - "go-vendor": { - "$ref": "#/$defs/GoVendorConfig", - "title": "Go vendoring", - "description": "Convert a Go application spec and generate its vendor archive during source preparation" - }, "packages": { "additionalProperties": { "$ref": "#/$defs/PackageConfig" @@ -687,38 +682,6 @@ "additionalProperties": false, "type": "object" }, - "GoVendorConfig": { - "properties": { - "enabled": { - "type": "boolean", - "title": "Enabled", - "description": "Enable Go application vendoring" - }, - "module-dir": { - "type": "string", - "title": "Module directory", - "description": "Relative module directory within the prepared source tree; defaults to its root" - }, - "config-file": { - "type": "string", - "title": "Vendor configuration file", - "description": "Path to a go-vendor-tools TOML file relative to the declaring component configuration. Replaces upstream settings when specified", - "examples": [ - "go-vendor-tools.toml" - ] - }, - "prep-packages": { - "items": { - "type": "string" - }, - "type": "array", - "title": "Prep packages", - "description": "Additional RPM packages needed to execute the upstream prep section in mock" - } - }, - "additionalProperties": false, - "type": "object" - }, "ImageCapabilities": { "properties": { "machine-bootable": { diff --git a/scenario/__snapshots__/TestSnapshots_config_generate-schema_stdout_1.snap b/scenario/__snapshots__/TestSnapshots_config_generate-schema_stdout_1.snap index 9259ce684..9cf47bd35 100755 --- a/scenario/__snapshots__/TestSnapshots_config_generate-schema_stdout_1.snap +++ b/scenario/__snapshots__/TestSnapshots_config_generate-schema_stdout_1.snap @@ -150,11 +150,6 @@ "title": "Source files", "description": "Source files to download for this component" }, - "go-vendor": { - "$ref": "#/$defs/GoVendorConfig", - "title": "Go vendoring", - "description": "Convert a Go application spec and generate its vendor archive during source preparation" - }, "packages": { "additionalProperties": { "$ref": "#/$defs/PackageConfig" @@ -687,38 +682,6 @@ "additionalProperties": false, "type": "object" }, - "GoVendorConfig": { - "properties": { - "enabled": { - "type": "boolean", - "title": "Enabled", - "description": "Enable Go application vendoring" - }, - "module-dir": { - "type": "string", - "title": "Module directory", - "description": "Relative module directory within the prepared source tree; defaults to its root" - }, - "config-file": { - "type": "string", - "title": "Vendor configuration file", - "description": "Path to a go-vendor-tools TOML file relative to the declaring component configuration. Replaces upstream settings when specified", - "examples": [ - "go-vendor-tools.toml" - ] - }, - "prep-packages": { - "items": { - "type": "string" - }, - "type": "array", - "title": "Prep packages", - "description": "Additional RPM packages needed to execute the upstream prep section in mock" - } - }, - "additionalProperties": false, - "type": "object" - }, "ImageCapabilities": { "properties": { "machine-bootable": { diff --git a/schemas/azldev.schema.json b/schemas/azldev.schema.json index 9259ce684..9cf47bd35 100644 --- a/schemas/azldev.schema.json +++ b/schemas/azldev.schema.json @@ -150,11 +150,6 @@ "title": "Source files", "description": "Source files to download for this component" }, - "go-vendor": { - "$ref": "#/$defs/GoVendorConfig", - "title": "Go vendoring", - "description": "Convert a Go application spec and generate its vendor archive during source preparation" - }, "packages": { "additionalProperties": { "$ref": "#/$defs/PackageConfig" @@ -687,38 +682,6 @@ "additionalProperties": false, "type": "object" }, - "GoVendorConfig": { - "properties": { - "enabled": { - "type": "boolean", - "title": "Enabled", - "description": "Enable Go application vendoring" - }, - "module-dir": { - "type": "string", - "title": "Module directory", - "description": "Relative module directory within the prepared source tree; defaults to its root" - }, - "config-file": { - "type": "string", - "title": "Vendor configuration file", - "description": "Path to a go-vendor-tools TOML file relative to the declaring component configuration. Replaces upstream settings when specified", - "examples": [ - "go-vendor-tools.toml" - ] - }, - "prep-packages": { - "items": { - "type": "string" - }, - "type": "array", - "title": "Prep packages", - "description": "Additional RPM packages needed to execute the upstream prep section in mock" - } - }, - "additionalProperties": false, - "type": "object" - }, "ImageCapabilities": { "properties": { "machine-bootable": { From 78677081ff9eb3db169363c5251295e17377bfd7 Mon Sep 17 00:00:00 2001 From: Antonio Salinas <173939267+Tonisal-byte@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:53:08 -0800 Subject: [PATCH 09/16] docs: align Go vendor design with manifest-first acquisition Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../reference/go-vendor-packaging-design.md | 121 ++++++------------ 1 file changed, 37 insertions(+), 84 deletions(-) diff --git a/docs/developer/reference/go-vendor-packaging-design.md b/docs/developer/reference/go-vendor-packaging-design.md index 28645c989..e6b473d9a 100644 --- a/docs/developer/reference/go-vendor-packaging-design.md +++ b/docs/developer/reference/go-vendor-packaging-design.md @@ -1,96 +1,49 @@ -# Go vendor packaging: one-page design +# Go vendor packaging: artifact acquisition -**Status:** Design comparison, not approval to replace the current implementation. -“Current” describes this branch, including pending review fixes. +**Decision:** TOML describes how to generate a vendor archive; the downstream +RPM `sources` manifest identifies the bytes to build with. A cached, verified +artifact does not have to be reproducible by today's Go toolchain to be usable. +azldev prepares the archive, not a replacement RPM spec. -## Goal and requirements +## Use cases and schema -Bundle application dependencies while preserving package-specific RPM behavior. -`prepare-sources` must produce all build inputs, including the vendor archive; -builds must consume those inputs without downloading Go modules. Configuration -should survive version upgrades without embedding versioned filenames, Source -numbers, import paths, or spec line numbers. Preserve unrelated dependencies, -patches, subpackages, and reviewed licensing. Generate in an isolated environment, -fail on ambiguous layouts, and record/verify archive hashes. Changes to source, -patches, native vendor settings, or toolchain must be accounted for when assessing -reproducibility; a generated checksum alone does not guarantee reproducibility. - -## Use cases and current gaps - -| Use case | Current behavior and gap | -|---|---| -| Fedora, already vendored: **containerd** | Regenerates a recognized vendor Source after patched `%prep`; preserves native configuration and verifies licensing. Containerd was exercised end-to-end. Recognition requires specific extraction/license macros; changing module layout or replacing a lookaside-backed config is rejected. Dependency overrides/hooks can regenerate patched content; directly patching the old vendor archive is not sufficient because regeneration replaces it. | -| Fedora, not vendored: **Go applications**; requested example **rust-uutils** | Converts supported Go application specs to vendor extraction, offline module builds, and license handling. Complex macros/subpackages require overlays. **rust-uutils is Rust:** it needs Cargo vendoring, Cargo build integration, and Rust license handling; neither this Go implementation nor a Go tarball provider covers it. | -| Downstream-only: **Telegraf** (assuming “telgraf”) | Local specs can use the same Go conversion pipeline when their layout is supported. A downstream-owned spec could instead consume a stable vendor Source directly. This particular package has not been validated; local-source, patch-order, and offline-build coverage remains necessary. | - -## Current design and schema - -```toml -[components.containerd.go-vendor] -enabled = true -config-file = "go-vendor-tools.toml" # optional; omission reuses upstream settings -``` - -Additional fields are `module-dir` and `prep-packages`. Custom native settings -live in a separate declaration-relative file, replace rather than merge upstream -settings, and participate in fingerprints. - -The pipeline fetches sources, applies overlays, plans a narrowly scoped spec -adaptation, runs private `%prep`, and invokes `go-vendor-tools` for generation and -licensing. It publishes the archive, spec/config, and `sources` digest. -`internal/govendor` separates execution from spec planning, but still requires a -prepared RPM spec. Render/diff also regenerate, so they require downloads. -Generated files cannot also be declared in `source-files`. - -## Alternative: automatic tarball through `source-files` - -**Proposed syntax and defaults only; this origin is not implemented:** +* **Already vendored (Fedora containerd):** reuse the archive name that the + effective spec expects, rather than pinning a versioned filename in TOML. +* **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]] -hash-type = "SHA512" -# filename = "vendor.tar.bz2" # optional override of automatic discovery -# hash = "" # optional output verification origin.type = "go-vendor" -origin.config-file = "go-vendor-tools.toml" +# origin.config-file = "go-vendor-tools.toml" ``` -Filename discovery is default behavior, not a separate field: resolve the unique -vendor Source from the effective spec and expand RPM macros. An explicit -`filename` overrides discovery; require it when no unique target can be resolved. -New/downstream specs can reference a stable `vendor.tar.bz2`. Regeneration owns -the discovered vendor output; an explicit filename that replaces another existing -source remains subject to existing collision/replacement safeguards. Native -settings stay in the sidecar; origin options reuse `module-dir`/`prep-packages`. +Discover the output name from a supported vendor Source or specify a basename. +Neither the recipe nor its filename override needs a duplicate manifest digest. +Optional generation inputs include declaration-relative native settings, the +module directory, and extra prep packages. These are not cache keys. -For this generated origin, `hash` is optional: azldev computes the archive digest -and records it in `sources`. A supplied hash must match; omission records output -identity but does not detect unexpected changes between regenerations. This is an -intentional exception to current `source-files` preparation, which generally -requires hashes unless bootstrapping with `--allow-no-hashes`. +## Acquisition contract -This needs more than a new provider switch: `FetchFiles` currently runs **before** -overlays. Defer vendor generation until patched inputs are prepared, excluding -its own output from fetching/prep to break the dependency cycle. Reuse the narrow -temporary-prep planner for recognized specs; reject unsupported extraction rather -than invent a general shell interpreter. Generate from patched module files, -apply vendor-specific changes through generation hooks, validate licensing and -regular-file outputs, then publish the final digest. Never silently refresh a -configured expected hash. Extend origin validation, schema, -fingerprints, deferred scheduling, and replacement/render handling together. - -## Trade-offs and recommendation - -| Current combined feature | Tarball-only alternative | +| Downstream state | Required behavior | |---|---| -| Low-effort opt-in for supported Go specs. | Smaller spec-mutation surface, reusable source artifact. | -| azldev maintains conversion and licensing rules. | Maintainers own extraction, dependency removal, offline flags, bundled-license installation, and spec updates through overlays/local specs. | -| Handles generation and consumption together. | Tarball existence does **not** prove the RPM consumes it; offline-build and licensing checks remain required. | - -**Recommendation:** retain the current bounded converter for now. If artifact-only -generation is prioritized, reuse its backend behind a deferred `go-vendor` origin, -with spec conversion remaining an optional adapter; reject simultaneous ownership -of one archive by both configurations. Validate containerd regeneration, a genuinely -unbundled Go application, and a downstream local package before migration. Treat -Cargo support as separate work. This reduces azldev's responsibilities only by -moving packaging work to maintainers, not by eliminating it. +| Manifest pin and valid cache hit | Use the verified archive. Do not run vendor generation. | +| Manifest pin, but no usable cached bytes | Generate from patched inputs in isolated mock and check the result against the same pin. A mismatch is an error, not permission to update the digest. | +| No downstream pin | Generate the archive and record its digest in prepared `sources` for review. Do not mistake a same-named upstream archive for a downstream pin. | + +Changing a recipe alone does not supersede a valid pin. To revendor, either +set a known desired digest or remove the old downstream entry, prepare, +review the resulting dependencies and licenses, and record the new digest. +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). From bd6ee5abeb6bba11a7578e9056cca5ef008859d1 Mon Sep 17 00:00:00 2001 From: Antonio Salinas <173939267+Tonisal-byte@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:38:06 -0800 Subject: [PATCH 10/16] docs: retain unconditional Go vendor generation Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../reference/go-vendor-packaging-design.md | 26 +++++++------------ 1 file changed, 10 insertions(+), 16 deletions(-) diff --git a/docs/developer/reference/go-vendor-packaging-design.md b/docs/developer/reference/go-vendor-packaging-design.md index e6b473d9a..3fa9d997d 100644 --- a/docs/developer/reference/go-vendor-packaging-design.md +++ b/docs/developer/reference/go-vendor-packaging-design.md @@ -1,9 +1,8 @@ # Go vendor packaging: artifact acquisition -**Decision:** TOML describes how to generate a vendor archive; the downstream -RPM `sources` manifest identifies the bytes to build with. A cached, verified -artifact does not have to be reproducible by today's Go toolchain to be usable. -azldev prepares the archive, not a replacement RPM spec. +**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 @@ -22,22 +21,17 @@ origin.type = "go-vendor" ``` Discover the output name from a supported vendor Source or specify a basename. -Neither the recipe nor its filename override needs a duplicate manifest digest. Optional generation inputs include declaration-relative native settings, the -module directory, and extra prep packages. These are not cache keys. +module directory, and extra prep packages. ## Acquisition contract -| Downstream state | Required behavior | -|---|---| -| Manifest pin and valid cache hit | Use the verified archive. Do not run vendor generation. | -| Manifest pin, but no usable cached bytes | Generate from patched inputs in isolated mock and check the result against the same pin. A mismatch is an error, not permission to update the digest. | -| No downstream pin | Generate the archive and record its digest in prepared `sources` for review. Do not mistake a same-named upstream archive for a downstream pin. | - -Changing a recipe alone does not supersede a valid pin. To revendor, either -set a known desired digest or remove the old downstream entry, prepare, -review the resulting dependencies and licenses, and record the new digest. -An explicit filename does not authorize replacing an unrelated source. +Source preparation, render, 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. +To revendor, change the generation inputs and prepare again. An explicit +filename does not authorize replacing an unrelated source. ## Trade-off From a117faf801911ec820ae6cb03e0dbe96f2c7a233 Mon Sep 17 00:00:00 2001 From: Antonio Salinas <173939267+Tonisal-byte@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:45:27 -0800 Subject: [PATCH 11/16] refactor: reuse vendor target manifest for archive replacement Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- internal/app/azldev/core/sources/govendor.go | 33 ++++++-------------- 1 file changed, 10 insertions(+), 23 deletions(-) diff --git a/internal/app/azldev/core/sources/govendor.go b/internal/app/azldev/core/sources/govendor.go index d788e96cc..491520f7b 100644 --- a/internal/app/azldev/core/sources/govendor.go +++ b/internal/app/azldev/core/sources/govendor.go @@ -150,27 +150,10 @@ func (p *sourcePreparerImpl) publishVendorSource( } ref.Hash = digest - if err := p.validateVendorTarget(component, directory, ref, automatic); err != nil { + if err := p.resolveVendorTarget(component, directory, &ref, automatic); err != nil { return ref, err } - manifest, err := p.readSourcesFileIfExists(filepath.Join(directory, fedorasource.SourcesFileName)) - if err != nil { - return ref, err - } - - lines, err := fedorasource.ReadSourcesFile(manifest) - if err != nil { - return ref, fmt.Errorf("reading vendor source manifest:\n%w", err) - } - - for _, line := range lines { - if automatic && line.Entry != nil && line.Entry.Filename == ref.Filename { - ref.ReplaceUpstream = true - ref.ReplaceReason = "Regenerate the discovered Go vendor Source" - } - } - return ref, p.copyVendorArchive(directory, ref.Filename, artifact.Path) } @@ -258,8 +241,8 @@ func (p *sourcePreparerImpl) vendorSettings( return string(data), nil } -func (p *sourcePreparerImpl) validateVendorTarget( - component components.Component, directory string, ref projectconfig.SourceFileReference, automatic bool, +func (p *sourcePreparerImpl) resolveVendorTarget( + component components.Component, directory string, ref *projectconfig.SourceFileReference, automatic bool, ) error { for _, other := range component.GetConfig().SourceFiles { if other.Origin.Type != projectconfig.OriginTypeGoVendor && other.Filename == ref.Filename { @@ -292,9 +275,13 @@ func (p *sourcePreparerImpl) validateVendorTarget( } if !automatic || ref.ReplaceUpstream { - _, _, _, err := p.processSourceRef(ref, existing, component.GetName(), directory) - - return err + if _, _, _, err := p.processSourceRef(*ref, existing, component.GetName(), directory); err != nil { + return err + } + } + if _, found := existing[ref.Filename]; automatic && found { + ref.ReplaceUpstream = true + ref.ReplaceReason = "Regenerate the discovered Go vendor Source" } return nil From 69b1310b90ccd1695f8b5b259f3686d0e5b04b63 Mon Sep 17 00:00:00 2001 From: Antonio Salinas <173939267+Tonisal-byte@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:49:46 -0800 Subject: [PATCH 12/16] test: trim overlapping Go vendor coverage Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- internal/app/azldev/core/sources/govendor.go | 1 + .../core/sources/govendor_internal_test.go | 20 ++--- internal/govendor/generate_internal_test.go | 88 ++++++++----------- internal/projectconfig/govendor_test.go | 4 +- internal/rpm/spec/vendorprep_test.go | 12 +-- 5 files changed, 48 insertions(+), 77 deletions(-) diff --git a/internal/app/azldev/core/sources/govendor.go b/internal/app/azldev/core/sources/govendor.go index 491520f7b..d24f23b3f 100644 --- a/internal/app/azldev/core/sources/govendor.go +++ b/internal/app/azldev/core/sources/govendor.go @@ -279,6 +279,7 @@ func (p *sourcePreparerImpl) resolveVendorTarget( return err } } + if _, found := existing[ref.Filename]; automatic && found { ref.ReplaceUpstream = true ref.ReplaceReason = "Regenerate the discovered Go vendor Source" diff --git a/internal/app/azldev/core/sources/govendor_internal_test.go b/internal/app/azldev/core/sources/govendor_internal_test.go index d3dd2ed92..49304e971 100644 --- a/internal/app/azldev/core/sources/govendor_internal_test.go +++ b/internal/app/azldev/core/sources/govendor_internal_test.go @@ -99,15 +99,20 @@ func TestGoVendorSourcePreparation(t *testing.T) { 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(), "/tmp/azldev-vendor-*/output/config.toml") + 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:") + if mode == newSource { + assert.Contains(t, string(prep), "%{shescape:vendor.tar.bz2}") + } + history, err := fileutils.ReadFile(ctx.FS(), filepath.Join(filepath.Dir(directory), "sources", ".git", "HEAD")) require.NoError(t, err) assert.Equal(t, "history", string(history)) @@ -120,7 +125,7 @@ func TestGoVendorSourcePreparation(t *testing.T) { return "", nil } preparer, err := NewPreparer(manager, ctx.FS(), ctx, ctx, - WithGoVendorRunner(mock.NewRunner(ctx, "/mock.cfg")), WithSkipLookaside()) + WithGoVendorRunner(mock.NewRunner(ctx, "/mock.cfg").WithBaseDir("/project/build/vendor")), WithSkipLookaside()) require.NoError(t, err) if mode == "diff" { @@ -241,14 +246,3 @@ func TestVendorFingerprintUsesDeclaredInputs(t *testing.T) { assert.Equal(t, declared.SourceFiles, restored.SourceFiles) assert.Equal(t, "generated", effective.SourceFiles[1].Hash, "must not mutate runtime manifest inputs") } - -func TestVendorScratchUsesProjectWorkDir(t *testing.T) { - ctx := newMockProcessorTestCtx() - preparer := &sourcePreparerImpl{ - fs: ctx.FS(), goVendorRunner: mock.NewRunner(ctx, "/mock.cfg").WithBaseDir("/project/build/vendor"), - } - path, err := preparer.vendorScratchDir() - require.NoError(t, err) - assert.True(t, strings.HasPrefix(path, "/project/build/vendor/azldev-vendor-")) - assert.NotContains(t, path, "*") -} diff --git a/internal/govendor/generate_internal_test.go b/internal/govendor/generate_internal_test.go index f8655abe9..62366d907 100644 --- a/internal/govendor/generate_internal_test.go +++ b/internal/govendor/generate_internal_test.go @@ -20,64 +20,42 @@ import ( "github.com/stretchr/testify/require" ) -func TestGenerate(t *testing.T) { - for _, mode := range []string{"success", "failure", "missing name", "bad name", "empty archive"} { - t.Run(mode, func(t *testing.T) { - ctx := testctx.NewCtx() - ctx.CmdFactory.RegisterCommandInSearchPath(mock.MockBinary) - require.NoError(t, fileutils.WriteFile(ctx.FS(), "/input/app.spec", []byte("upstream"), fileperms.PublicFile)) +func TestGenerationFailureScrubsRoot(t *testing.T) { + ctx := testctx.NewCtx() + ctx.CmdFactory.RegisterCommandInSearchPath(mock.MockBinary) - var commands []string + var commands []string - ctx.CmdFactory.RunHandler = func(cmd *exec.Cmd) error { - commands = append(commands, strings.Join(cmd.Args, " ")) + ctx.CmdFactory.RunHandler = func(cmd *exec.Cmd) error { + commands = append(commands, strings.Join(cmd.Args, " ")) - return nil - } - ctx.CmdFactory.RunAndGetOutputHandler = func(cmd *exec.Cmd) (string, error) { - assert.Contains(t, strings.Join(cmd.Args, " "), "go_vendor_archive create") - - if mode == "failure" { - return "native tool failed", errors.New("generation failed") - } - - name := "vendor.tar.bz2" - if mode == "bad name" { - name = "../host" - } - - if mode != "missing name" { - require.NoError(t, fileutils.WriteFile(ctx.FS(), "/work/output/name", []byte(name+"\n"), fileperms.PublicFile)) - } - - payload := "archive" - if mode == "empty archive" { - payload = "" - } - - require.NoError(t, fileutils.WriteFile(ctx.FS(), "/work/output/vendor.tar.bz2", - []byte(payload), fileperms.PublicFile)) - - return "", nil - } - req := Request{SourceDir: "/input", WorkDir: "/work", SpecName: "app.spec", PrepSpec: []byte("private")} - artifact, err := Generate(ctx, ctx.FS(), mock.NewRunner(ctx, "/mock.cfg"), req) - - assert.Contains(t, strings.Join(commands, "\n"), "--scrub all") + return nil + } + failure := errors.New("generation failed") + ctx.CmdFactory.RunAndGetOutputHandler = func(*exec.Cmd) (string, error) { + return "native tool failed", failure + } + err := execute(ctx, mock.NewRunner(ctx, "/mock.cfg"), Request{WorkDir: "/work", SpecName: "app.spec"}, "/output") + require.ErrorIs(t, err, failure) + assert.Contains(t, strings.Join(commands, "\n"), "--scrub all") +} - if mode != "success" { - require.Error(t, err) +func TestReadArtifactRejectsInvalidOutputs(t *testing.T) { + for _, testCase := range []struct{ name, wantErr string }{ + {"", "opening generated vendor output"}, + {"../host", "invalid generated 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)) - return + if testCase.name != "" { + require.NoError(t, fileutils.WriteFile(fs, "/work/output/name", []byte(testCase.name), fileperms.PublicFile)) } - require.NoError(t, err) - assert.Equal(t, "vendor.tar.bz2", artifact.Name) - assert.Equal(t, "/work/vendor.tar.bz2", artifact.Path) - - source, err := fileutils.ReadFile(ctx.FS(), "/input/app.spec") - require.NoError(t, err) - assert.Equal(t, "upstream", string(source)) + _, err := readArtifact(fs, "/work", "/work/output") + require.ErrorContains(t, err, testCase.wantErr) }) } } @@ -91,8 +69,12 @@ func TestGenerationModuleLayout(t *testing.T) { command, err := generationCommand(req, "aarch64") require.NoError(t, err) assert.Contains(t, command[len(command)-1], "--target aarch64") - assert.Contains(t, command[len(command)-1], "go_vendor_archive create") - assert.LessOrEqual(t, strings.Count(command[len(command)-1], "cd cmd/app"), 1) + + 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{ diff --git a/internal/projectconfig/govendor_test.go b/internal/projectconfig/govendor_test.go index 636e5e751..d9984e8df 100644 --- a/internal/projectconfig/govendor_test.go +++ b/internal/projectconfig/govendor_test.go @@ -35,11 +35,11 @@ func TestGoVendorOriginValidation(t *testing.T) { "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.OriginTypeOverlay, ConfigFile: "vendor.toml"}, + "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{{Origin: origin}}}, + "app": {SourceFiles: []projectconfig.SourceFileReference{{Filename: "vendor.tar.gz", Origin: origin}}}, }} require.Error(t, file.Validate()) }) diff --git a/internal/rpm/spec/vendorprep_test.go b/internal/rpm/spec/vendorprep_test.go index fd26c9dc3..ca56e1792 100644 --- a/internal/rpm/spec/vendorprep_test.go +++ b/internal/rpm/spec/vendorprep_test.go @@ -34,13 +34,6 @@ func TestPrepareVendorSource(t *testing.T) { 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}") - assert.Equal(t, input, vendorSpec(), "planning only produces a private spec") - - newSpec := strings.ReplaceAll(input, "tar -xf %{S:5}", "") - plan, err = spec.PrepareVendorSource([]byte(newSpec), "vendor.tar.bz2") - require.NoError(t, err) - assert.False(t, plan.Automatic) - assert.Contains(t, string(plan.Spec), "%{shescape:vendor.tar.bz2}") } func TestPrepareVendorSourceRejectsAmbiguity(t *testing.T) { @@ -71,6 +64,7 @@ func TestPrepareVendorSourceRejectsAmbiguity(t *testing.T) { require.Error(t, err) } - _, err := spec.PrepareVendorSource([]byte(vendorSpec()), "different.tar.bz2") - require.NoError(t, err, "macro-expanded filenames are checked by RPM during private prep") + 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}") } From 9d9d814ce7ef1cc2148c2592f41fe20e9252c2fc Mon Sep 17 00:00:00 2001 From: Antonio Salinas <173939267+Tonisal-byte@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:17:11 -0800 Subject: [PATCH 13/16] feat: render Go vendor sources from configured digests Use the existing batched RPM metadata to resolve the selected Source. Generation remains part of prepare and build; require a reviewed digest for render rather than downloading sources and starting a private vendor root. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../reference/go-vendor-packaging-design.md | 5 +- docs/user/how-to/vendor-go-application.md | 15 +++- .../reference/cli/azldev_component_render.md | 4 +- docs/user/reference/config/components.md | 7 +- .../app/azldev/agentskill/agentskill_test.go | 2 +- .../agentskill/content/comp-toml.md.tmpl | 4 +- .../content/withoutlockfile/comp-toml.md.tmpl | 4 +- internal/app/azldev/cmds/component/render.go | 14 ++-- .../azldev/cmds/component/render_sources.go | 52 ------------- internal/app/azldev/core/sources/govendor.go | 73 +++++++++++++++++++ .../core/sources/govendor_internal_test.go | 30 ++++++++ .../app/azldev/core/sources/mockprocessor.go | 8 +- .../app/azldev/core/sources/sourceprep.go | 12 ++- internal/rpm/spec/vendorprep.go | 9 ++- 14 files changed, 158 insertions(+), 81 deletions(-) delete mode 100644 internal/app/azldev/cmds/component/render_sources.go diff --git a/docs/developer/reference/go-vendor-packaging-design.md b/docs/developer/reference/go-vendor-packaging-design.md index 3fa9d997d..c7b4e8975 100644 --- a/docs/developer/reference/go-vendor-packaging-design.md +++ b/docs/developer/reference/go-vendor-packaging-design.md @@ -26,10 +26,13 @@ module directory, and extra prep packages. ## Acquisition contract -Source preparation, render, and source diffs generate the vendor archive after +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. Filename discovery reuses the +existing batched RPM metadata lookup. To revendor, change the generation inputs and prepare again. An explicit filename does not authorize replacing an unrelated source. diff --git a/docs/user/how-to/vendor-go-application.md b/docs/user/how-to/vendor-go-application.md index 4142851e2..60a433a44 100644 --- a/docs/user/how-to/vendor-go-application.md +++ b/docs/user/how-to/vendor-go-application.md @@ -11,6 +11,9 @@ Rust packages need Cargo vendoring, not this Go provider. ```toml [[components.containerd.source-files]] origin.type = "go-vendor" +# 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 = "go-vendor-tools.toml" ``` @@ -65,14 +68,16 @@ 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. -`hash` is optional specifically for `go-vendor`: azldev computes and records the -generated digest in `sources` (SHA-512 by default, or configured `hash-type`). +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 ``` @@ -90,7 +95,9 @@ generation. Do not patch the old vendor archive using archive overlays: use nati dependency overrides/hooks instead. Ensure prep does not apply the same module patch twice when rebuilding with the regenerated module files. -Render and source diffs also regenerate and need network access. Render retains -the updated manifest, not lookaside payloads. Validate upgrades with source diffs, +Source diffs regenerate the archive. Render instead requires the TOML pin and +writes it to the manifest without downloading or generating vendor inputs. For +automatic filenames it reuses the normal batched RPM metadata expansion. 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 af16bc4a6..95f24f8df 100644 --- a/docs/user/reference/cli/azldev_component_render.md +++ b/docs/user/reference/cli/azldev_component_render.md @@ -17,8 +17,8 @@ subdirectories based on the first character of their name (e.g., specs/c/curl, specs/v/vim). Render normally skips lookaside archives, retaining specs and git-tracked sidecars. -Go-vendor source-files require downloads and regeneration; only the manifest, -not archive payloads, is rendered. Multiple components can be rendered at once. +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 c8d8e45f6..572280f74 100644 --- a/docs/user/reference/config/components.md +++ b/docs/user/reference/config/components.md @@ -396,6 +396,8 @@ Four origin types are supported. [[components.containerd.source-files]] origin.type = "go-vendor" origin.config-file = "go-vendor-tools.toml" +hash-type = "SHA512" +hash = "" ``` This origin generates only a tarball; it never converts the published spec. @@ -404,7 +406,7 @@ See [Generate a Go vendor source archive](../../how-to/vendor-go-application.md) | Key | Default | Meaning | |-----|---------|---------| | `filename` | Discover from the unique secondary Source extraction in `%prep` | Optional plain basename override; explicit collisions use the normal replacement rules. | -| `hash` | Compute and record | Optional expected output digest; a mismatch fails before publication. | +| `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. | @@ -412,7 +414,8 @@ See [Generate a Go vendor source archive](../../how-to/vendor-go-application.md) One Go vendor source is supported per component. Automatic discovery can replace the discovered vendor manifest entry without replacement fields. Generation runs -after overlays and requires source downloads during prepare, render, and diff. +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 930c0ebbd..1211b0025 100644 --- a/internal/app/azldev/agentskill/agentskill_test.go +++ b/internal/app/azldev/agentskill/agentskill_test.go @@ -191,7 +191,7 @@ func TestComponentSkillDocumentsVendorSource(t *testing.T) { require.NoError(t, err) assert.Contains(t, doc, `origin.type = "go-vendor"`) assert.Contains(t, doc, "never converts the spec") - assert.Contains(t, doc, "`hash` is optional output verification") + assert.Contains(t, doc, "render writes the pin without generation") } } diff --git a/internal/app/azldev/agentskill/content/comp-toml.md.tmpl b/internal/app/azldev/agentskill/content/comp-toml.md.tmpl index aff0cf9f1..c8c5f835b 100644 --- a/internal/app/azldev/agentskill/content/comp-toml.md.tmpl +++ b/internal/app/azldev/agentskill/content/comp-toml.md.tmpl @@ -38,10 +38,10 @@ Add sub-tables only for what you change. The fields you will reach for most: For generated Go dependencies, add a `source-files` entry with `origin.type = "go-vendor"`. This generates only a tarball, never converts the spec. Omit `filename` to discover a unique vendor Source; set a stable basename for new -packaging. `hash` is optional output verification; configured mismatches fail. +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, including during render/diff, and needs network/mock access. +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 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 3e34d609e..71757536f 100644 --- a/internal/app/azldev/agentskill/content/withoutlockfile/comp-toml.md.tmpl +++ b/internal/app/azldev/agentskill/content/withoutlockfile/comp-toml.md.tmpl @@ -38,10 +38,10 @@ Add sub-tables only for what you change. The fields you will reach for most: For generated Go dependencies, add a `source-files` entry with `origin.type = "go-vendor"`. This generates only a tarball, never converts the spec. Omit `filename` to discover a unique vendor Source; set a stable basename for new -packaging. `hash` is optional output verification; configured mismatches fail. +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, including during render/diff, and needs network/mock access. +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 diff --git a/internal/app/azldev/cmds/component/render.go b/internal/app/azldev/cmds/component/render.go index f49a20532..dc2309a6a 100644 --- a/internal/app/azldev/cmds/component/render.go +++ b/internal/app/azldev/cmds/component/render.go @@ -65,8 +65,8 @@ subdirectories based on the first character of their name (e.g., specs/c/curl, specs/v/vim). Render normally skips lookaside archives, retaining specs and git-tracked sidecars. -Go-vendor source-files require downloads and regeneration; only the manifest, -not archive payloads, is rendered. Multiple components can be rendered at once. +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,7 +536,7 @@ 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), ) @@ -545,7 +545,7 @@ func prepareComponentSources( preparerOpts = append(preparerOpts, sources.WithRPMDevBumpspec(env, env.WorkDir(), "")) } - preparer, err := newComponentSourcePreparer(env, comp, sourceManager, nil, append( + preparer, err := newSourcePreparer(sourceManager, env.FS(), env, env, append( preparerOpts, sources.WithSpecEditor(specEditor), )...) @@ -768,12 +768,12 @@ func finishComponentRender( return false, fmt.Errorf("filtering unreferenced files for %#q:\n%w", componentName, filterErr) } - // Remove .git directory — must not appear in rendered output. if prep.comp.GetConfig().HasGoVendorSources() { - if err := removeVendorRenderPayloads(env.FS(), componentDir); err != nil { - return false, err + if err := sources.RenderVendorPin(env.FS(), prep.comp, specPath, mockResult.RawSpecFiles); err != nil { + return false, fmt.Errorf("rendering vendor source for %#q:\n%w", componentName, err) } } + // Remove .git directory — must not appear in rendered output. // rpmautospec already read it during the batch mock phase. gitDir := filepath.Join(componentDir, ".git") if removeErr := env.FS().RemoveAll(gitDir); removeErr != nil { diff --git a/internal/app/azldev/cmds/component/render_sources.go b/internal/app/azldev/cmds/component/render_sources.go deleted file mode 100644 index 71fd020be..000000000 --- a/internal/app/azldev/cmds/component/render_sources.go +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -package component - -import ( - "fmt" - "path/filepath" - - "github.com/microsoft/azure-linux-dev-tools/internal/global/opctx" - "github.com/microsoft/azure-linux-dev-tools/internal/providers/sourceproviders/fedorasource" - "github.com/microsoft/azure-linux-dev-tools/internal/utils/fileutils" -) - -func removeVendorRenderPayloads(fs opctx.FS, directory string) error { - path := filepath.Join(directory, fedorasource.SourcesFileName) - - data, err := fileutils.ReadFile(fs, path) - if err != nil { - return fmt.Errorf("reading generated source manifest:\n%w", err) - } - - lines, err := fedorasource.ReadSourcesFile(string(data)) - if err != nil { - return fmt.Errorf("parsing generated source manifest:\n%w", err) - } - - for _, line := range lines { - if line.Entry == nil { - continue - } - - if err := fileutils.ValidateFilename(line.Entry.Filename); err != nil { - return fmt.Errorf("validating payload filename:\n%w", err) - } - - file := filepath.Join(directory, line.Entry.Filename) - - exists, err := fileutils.Exists(fs, file) - if err != nil { - return fmt.Errorf("checking rendered payload:\n%w", err) - } - - if exists { - if err := fs.Remove(file); err != nil { - return fmt.Errorf("excluding generated source payload %#q:\n%w", file, err) - } - } - } - - return nil -} diff --git a/internal/app/azldev/core/sources/govendor.go b/internal/app/azldev/core/sources/govendor.go index d24f23b3f..bdc512cce 100644 --- a/internal/app/azldev/core/sources/govendor.go +++ b/internal/app/azldev/core/sources/govendor.go @@ -13,6 +13,7 @@ import ( "strings" "github.com/microsoft/azure-linux-dev-tools/internal/app/azldev/core/components" + "github.com/microsoft/azure-linux-dev-tools/internal/global/opctx" "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" @@ -27,6 +28,78 @@ func WithGoVendorRunner(runner *mock.Runner) PreparerOption { return func(p *sourcePreparerImpl) { p.goVendorRunner = runner } } +// WithRenderManifest defers vendor entries until the normal render batch has expanded Source tags. +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() +} + +// RenderVendorPin merges the reviewed pin into the manifest without fetching or generating an archive. +func RenderVendorPin(fs opctx.FS, comp components.Component, specPath, rawSpecFiles string) error { + for _, ref := range comp.GetConfig().SourceFiles { + if ref.Origin.Type != projectconfig.OriginTypeGoVendor { + continue + } + + data, err := fileutils.ReadFile(fs, specPath) + if err != nil { + return fmt.Errorf("reading vendor spec:\n%w", err) + } + + plan, err := spec.PrepareVendorSource(data, ref.Filename) + if err != nil { + return fmt.Errorf("identifying vendor Source:\n%w", err) + } + + if plan.SourceNumber != "" { + name, err := expandedVendorFilename(rawSpecFiles, plan.SourceNumber) + if err != nil { + return err + } + + if ref.Filename != "" && ref.Filename != name { + return fmt.Errorf("configured filename %#q does not match vendor Source %#q", ref.Filename, name) + } + + ref.Filename = name + } + + preparer := sourcePreparerImpl{fs: fs, skipLookaside: true} + + dir := filepath.Dir(specPath) + if err := preparer.resolveVendorTarget(comp, dir, &ref, plan.Automatic); err != nil { + return err + } + + config := *comp.GetConfig() + config.SourceFiles = []projectconfig.SourceFileReference{ref} + _, err = preparer.updateSourcesFile(vendorComponent{Component: comp, config: config}, dir, nil) + + return err + } + + return nil +} + +func expandedVendorFilename(output, number string) (string, error) { + for _, line := range strings.Split(output, "\n") { + tag, value, ok := strings.Cut(line, ":") + if ok && strings.EqualFold(tag, "Source"+number) { + name := strings.TrimSpace(value) + if err := fileutils.ValidateFilename(name); err != nil || strings.Contains(name, "%") { + return "", fmt.Errorf("invalid expanded vendor Source%s filename %#q", number, name) + } + + return name, nil + } + } + + return "", fmt.Errorf("vendor Source%s missing from expanded spec", number) +} + type vendorComponent struct { components.Component config projectconfig.ComponentConfig diff --git a/internal/app/azldev/core/sources/govendor_internal_test.go b/internal/app/azldev/core/sources/govendor_internal_test.go index 49304e971..3520b1b83 100644 --- a/internal/app/azldev/core/sources/govendor_internal_test.go +++ b/internal/app/azldev/core/sources/govendor_internal_test.go @@ -179,6 +179,36 @@ func TestGoVendorSourcePreparation(t *testing.T) { } } +func TestRenderVendorPin(t *testing.T) { + ctx := newMockProcessorTestCtx() + comp := components_testutils.NewMockComponent(gomock.NewController(t)) + comp.EXPECT().GetName().AnyTimes().Return("app") + ref := projectconfig.SourceFileReference{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.NoError(t, err) + require.NoError(t, RenderVendorPin(ctx.FS(), comp, "/staged/app.spec", "Source7: app-2-vendor.tar.gz")) + 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" diff --git a/internal/app/azldev/core/sources/mockprocessor.go b/internal/app/azldev/core/sources/mockprocessor.go index a10ff7107..04f68881a 100644 --- a/internal/app/azldev/core/sources/mockprocessor.go +++ b/internal/app/azldev/core/sources/mockprocessor.go @@ -91,9 +91,10 @@ type ComponentInput struct { // ComponentMockResult holds the mock processing result for one component. type ComponentMockResult struct { - Name string // Component name - SpecFiles []string // Files listed by spectool (basenames/relative paths) - Error error // Non-nil if rpmautospec or spectool failed for this component + RawSpecFiles string // Includes the RPM Source numbers for vendor filename discovery. + Name string // Component name + SpecFiles []string // Files listed by spectool (basenames/relative paths) + Error error // Non-nil if rpmautospec or spectool failed for this component } // validateInputs validates all component inputs before batch processing. @@ -445,6 +446,7 @@ func parseBatchJSON(stdout string, inputs []ComponentInput) ([]ComponentMockResu } results[idx].SpecFiles = spectool.ParseSpectoolOutput(compResult.SpecFiles) + results[idx].RawSpecFiles = compResult.SpecFiles } return results, nil diff --git a/internal/app/azldev/core/sources/sourceprep.go b/internal/app/azldev/core/sources/sourceprep.go index d19ed048a..80c51123c 100644 --- a/internal/app/azldev/core/sources/sourceprep.go +++ b/internal/app/azldev/core/sources/sourceprep.go @@ -201,6 +201,7 @@ type sourcePreparerImpl struct { 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]. @@ -308,7 +309,7 @@ func (p *sourcePreparerImpl) PrepareSources( } declaredConfig := component.GetConfig() - vendor := declaredConfig.HasGoVendorSources() + vendor := p.needsVendorInputs(declaredConfig) p = p.withVendorDownloads(vendor) // Fetch the component first (spec, sidecar files, and upstream source tarballs). @@ -1120,6 +1121,15 @@ 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") + } + // The existing render batch expands the RPM Source filename after this stage. + continue + } + formatted, isReplacement, resolvedRef, err := p.processSourceRef( sourceFiles[index], existingByName, componentName, outputDir) if err != nil { diff --git a/internal/rpm/spec/vendorprep.go b/internal/rpm/spec/vendorprep.go index 005bae54f..4cde6bf42 100644 --- a/internal/rpm/spec/vendorprep.go +++ b/internal/rpm/spec/vendorprep.go @@ -15,9 +15,10 @@ import ( // VendorPrep describes a private prep spec, never a replacement published spec. type VendorPrep struct { - Spec []byte - ConfigName string - Automatic bool + SourceNumber string + Spec []byte + ConfigName string + Automatic bool } var ( @@ -81,7 +82,7 @@ func PrepareVendorSource(data []byte, filename string) (*VendorPrep, error) { return &VendorPrep{ Spec: []byte(strings.Join(serializeTree(root), "\n") + "\n"), - ConfigName: configName, Automatic: filename == "", + ConfigName: configName, Automatic: filename == "", SourceNumber: number, }, nil } From a72a09f2ca02d5e71672ac0a3bd2569ce4332fc7 Mon Sep 17 00:00:00 2001 From: Antonio Salinas <173939267+Tonisal-byte@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:18:55 -0800 Subject: [PATCH 14/16] style: format vendor manifest regression test Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- internal/app/azldev/core/sources/govendor_internal_test.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/internal/app/azldev/core/sources/govendor_internal_test.go b/internal/app/azldev/core/sources/govendor_internal_test.go index 3520b1b83..1f2513397 100644 --- a/internal/app/azldev/core/sources/govendor_internal_test.go +++ b/internal/app/azldev/core/sources/govendor_internal_test.go @@ -183,9 +183,11 @@ func TestRenderVendorPin(t *testing.T) { ctx := newMockProcessorTestCtx() comp := components_testutils.NewMockComponent(gomock.NewController(t)) comp.EXPECT().GetName().AnyTimes().Return("app") + ref := projectconfig.SourceFileReference{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)) @@ -200,11 +202,13 @@ func TestRenderVendorPin(t *testing.T) { []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.NoError(t, err) require.NoError(t, RenderVendorPin(ctx.FS(), comp, "/staged/app.spec", "Source7: app-2-vendor.tar.gz")) 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)) } From 0b49dbc88115e505ff10b844207347e6edaedb83 Mon Sep 17 00:00:00 2001 From: Antonio Salinas <173939267+Tonisal-byte@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:29:12 -0800 Subject: [PATCH 15/16] fix: isolate vendor generation and reject ambiguous sources Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/user/how-to/vendor-go-application.md | 3 ++- internal/app/azldev/cmds/component/build.go | 7 +------ internal/govendor/generate.go | 8 +++++++- internal/govendor/generate_internal_test.go | 13 ++++++++++++- internal/projectconfig/component.go | 4 ++++ internal/projectconfig/govendor_test.go | 15 +++++++++++++++ internal/rpm/spec/vendorprep.go | 9 +++++++-- internal/rpm/spec/vendorprep_test.go | 16 +++++++++------- 8 files changed, 57 insertions(+), 18 deletions(-) diff --git a/docs/user/how-to/vendor-go-application.md b/docs/user/how-to/vendor-go-application.md index 60a433a44..e4672a9c8 100644 --- a/docs/user/how-to/vendor-go-application.md +++ b/docs/user/how-to/vendor-go-application.md @@ -22,7 +22,8 @@ By default, azldev finds the single unconditional `tar -xf %{S:N}` or `tar -xf %{SOURCEN}` in `%prep` referencing a secondary Source, then asks RPM to expand its filename. Source numbers and package versions are not embedded in the config. Ambiguous/conditional extraction, secondary setup -extraction (`-a`/`-b`), and release-dependent archive filenames fail rather than +extraction (`-a`/`-b`), opaque prep macro commands during automatic discovery, +and release-dependent archive filenames fail rather than guessing. Use a narrowly scoped prep/Source overlay to make these layouts explicit. The discovered vendor archive's existing `sources` entry is replaced automatically. Upstream lookaside fetching may still download the old vendor payload before diff --git a/internal/app/azldev/cmds/component/build.go b/internal/app/azldev/cmds/component/build.go index 462f483bf..baa94c26c 100644 --- a/internal/app/azldev/cmds/component/build.go +++ b/internal/app/azldev/cmds/component/build.go @@ -395,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/govendor/generate.go b/internal/govendor/generate.go index af86384fe..f3ac9324e 100644 --- a/internal/govendor/generate.go +++ b/internal/govendor/generate.go @@ -94,7 +94,13 @@ func execute(ctx context.Context, base *mock.Runner, req Request, output string) return err } - runner := base.Clone().WithBaseDir(filepath.Join(req.WorkDir, "mock")).EnableNetwork().WithUnprivileged() + 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") diff --git a/internal/govendor/generate_internal_test.go b/internal/govendor/generate_internal_test.go index 62366d907..54a58b288 100644 --- a/internal/govendor/generate_internal_test.go +++ b/internal/govendor/generate_internal_test.go @@ -35,9 +35,20 @@ func TestGenerationFailureScrubsRoot(t *testing.T) { ctx.CmdFactory.RunAndGetOutputHandler = func(*exec.Cmd) (string, error) { return "native tool failed", failure } - err := execute(ctx, mock.NewRunner(ctx, "/mock.cfg"), Request{WorkDir: "/work", SpecName: "app.spec"}, "/output") + 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) { diff --git a/internal/projectconfig/component.go b/internal/projectconfig/component.go index 172ca5495..47543ce25 100644 --- a/internal/projectconfig/component.go +++ b/internal/projectconfig/component.go @@ -626,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 diff --git a/internal/projectconfig/govendor_test.go b/internal/projectconfig/govendor_test.go index d9984e8df..3165c7d66 100644 --- a/internal/projectconfig/govendor_test.go +++ b/internal/projectconfig/govendor_test.go @@ -46,6 +46,21 @@ func TestGoVendorOriginValidation(t *testing.T) { } } +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{{ diff --git a/internal/rpm/spec/vendorprep.go b/internal/rpm/spec/vendorprep.go index 4cde6bf42..e63313413 100644 --- a/internal/rpm/spec/vendorprep.go +++ b/internal/rpm/spec/vendorprep.go @@ -25,6 +25,7 @@ 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. @@ -57,7 +58,7 @@ func PrepareVendorSource(data []byte, filename string) (*VendorPrep, error) { return nil, err } - candidates, err := vendorExtractions(prep, sources) + candidates, err := vendorExtractions(prep, sources, filename == "") if err != nil { return nil, err } @@ -129,7 +130,7 @@ func vendorSourceTags(tree *specTree) (sources map[string]string, configNumber s return sources, configNumber, err } -func vendorExtractions(prep *sectionHandle, sources map[string]string) ([]string, error) { +func vendorExtractions(prep *sectionHandle, sources map[string]string, automatic bool) ([]string, error) { var candidates []string err := prep.VisitLines(func(line *lineHandle) error { @@ -142,6 +143,10 @@ func vendorExtractions(prep *sectionHandle, sources map[string]string) ([]string return errors.New("secondary setup extraction requires an explicit prep overlay for vendor generation") } + if automatic && strings.HasPrefix(text, "%") && !knownPrepMacro.MatchString(text) { + return fmt.Errorf("cannot discover vendor Source through opaque 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) { diff --git a/internal/rpm/spec/vendorprep_test.go b/internal/rpm/spec/vendorprep_test.go index ca56e1792..0be14e154 100644 --- a/internal/rpm/spec/vendorprep_test.go +++ b/internal/rpm/spec/vendorprep_test.go @@ -38,13 +38,15 @@ func TestPrepareVendorSource(t *testing.T) { 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"), - "no extraction": strings.ReplaceAll(vendorSpec(), "tar -xf %{S:5}", ""), - "missing source": strings.ReplaceAll(vendorSpec(), "%{S:5}", "%{S:6}"), + "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}"), + "no extraction": strings.ReplaceAll(vendorSpec(), "tar -xf %{S:5}", ""), + "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:"), From 43fd77ccaa4b54825c34ed4eb1bc7d688579b7c4 Mon Sep 17 00:00:00 2001 From: Antonio Salinas <173939267+Tonisal-byte@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:33:37 -0800 Subject: [PATCH 16/16] feat: require explicit Go vendor archive filenames Use the declared basename for generation and manifest rendering. Require explicit replacement of an existing upstream entry and retain upstream native config selection independently of the archive name. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../reference/go-vendor-packaging-design.md | 12 +- docs/user/how-to/vendor-go-application.md | 23 ++-- docs/user/reference/config/components.md | 12 +- .../agentskill/content/comp-toml.md.tmpl | 2 +- .../content/withoutlockfile/comp-toml.md.tmpl | 2 +- internal/app/azldev/cmds/component/render.go | 5 - internal/app/azldev/core/sources/govendor.go | 105 +++--------------- .../core/sources/govendor_internal_test.go | 27 ++--- .../app/azldev/core/sources/mockprocessor.go | 8 +- .../app/azldev/core/sources/sourceprep.go | 2 - internal/govendor/generate.go | 42 +++---- internal/govendor/generate_internal_test.go | 10 +- internal/projectconfig/component.go | 2 +- internal/projectconfig/govendor.go | 4 +- internal/projectconfig/govendor_test.go | 8 +- internal/rpm/spec/vendorprep.go | 82 +++++--------- internal/rpm/spec/vendorprep_test.go | 9 +- ...ainer_config_generate-schema_stdout_1.snap | 7 +- ...shots_config_generate-schema_stdout_1.snap | 7 +- schemas/azldev.schema.json | 7 +- 20 files changed, 133 insertions(+), 243 deletions(-) diff --git a/docs/developer/reference/go-vendor-packaging-design.md b/docs/developer/reference/go-vendor-packaging-design.md index c7b4e8975..4906ef602 100644 --- a/docs/developer/reference/go-vendor-packaging-design.md +++ b/docs/developer/reference/go-vendor-packaging-design.md @@ -6,8 +6,8 @@ digest of the resulting archive. azldev does not rewrite the published spec. ## Use cases and schema -* **Already vendored (Fedora containerd):** reuse the archive name that the - effective spec expects, rather than pinning a versioned filename in TOML. +* **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. @@ -16,11 +16,14 @@ digest of the resulting archive. azldev does not rewrite the published spec. ```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" ``` -Discover the output name from a supported vendor Source or specify a basename. +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. @@ -31,8 +34,7 @@ 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. Filename discovery reuses the -existing batched RPM metadata lookup. +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. diff --git a/docs/user/how-to/vendor-go-application.md b/docs/user/how-to/vendor-go-application.md index e4672a9c8..88643119c 100644 --- a/docs/user/how-to/vendor-go-application.md +++ b/docs/user/how-to/vendor-go-application.md @@ -10,22 +10,22 @@ Rust packages need Cargo vendoring, not this Go provider. ```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 = "go-vendor-tools.toml" +# origin.config-file = "vendor-tools.toml" ``` -By default, azldev finds the single unconditional -`tar -xf %{S:N}` or `tar -xf %{SOURCEN}` in `%prep` referencing a secondary Source, -then asks RPM to expand its filename. Source numbers and package versions are not -embedded in the config. Ambiguous/conditional extraction, secondary setup -extraction (`-a`/`-b`), opaque prep macro commands during automatic discovery, -and release-dependent archive filenames fail rather than -guessing. Use a narrowly scoped prep/Source overlay to make these layouts explicit. -The discovered vendor archive's existing `sources` entry is replaced automatically. +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. @@ -39,7 +39,7 @@ origin.module-dir = "cmd/example" # optional; relative to the final prep directo origin.prep-packages = ["patch"] # optional tools needed by prep ``` -`filename` overrides discovery and is required when no unique target is found. +`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. @@ -97,8 +97,7 @@ 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 to the manifest without downloading or generating vendor inputs. For -automatic filenames it reuses the normal batched RPM metadata expansion. Render +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/config/components.md b/docs/user/reference/config/components.md index 572280f74..2f44a8876 100644 --- a/docs/user/reference/config/components.md +++ b/docs/user/reference/config/components.md @@ -379,7 +379,7 @@ The `[[components..source-files]]` array defines additional source files t | Field | TOML Key | Type | Required | Description | |-------|----------|------|----------|-------------| -| Filename | `filename` | string | Conditional | Name of the file in the sources directory; optional discovery for `go-vendor`. | +| 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 | @@ -394,8 +394,10 @@ Four origin types are supported. ```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" hash-type = "SHA512" hash = "" ``` @@ -405,15 +407,15 @@ See [Generate a Go vendor source archive](../../how-to/vendor-go-application.md) | Key | Default | Meaning | |-----|---------|---------| -| `filename` | Discover from the unique secondary Source extraction in `%prep` | Optional plain basename override; explicit collisions use the normal replacement rules. | +| `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. Automatic discovery can replace -the discovered vendor manifest entry without replacement fields. Generation runs +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. diff --git a/internal/app/azldev/agentskill/content/comp-toml.md.tmpl b/internal/app/azldev/agentskill/content/comp-toml.md.tmpl index c8c5f835b..3315a0adf 100644 --- a/internal/app/azldev/agentskill/content/comp-toml.md.tmpl +++ b/internal/app/azldev/agentskill/content/comp-toml.md.tmpl @@ -37,7 +37,7 @@ Add sub-tables only for what you change. The fields you will reach for most: For generated Go dependencies, add a `source-files` entry with `origin.type = "go-vendor"`. This generates only a tarball, never converts the spec. -Omit `filename` to discover a unique vendor Source; set a stable basename for new +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 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 71757536f..ba9e91ac6 100644 --- a/internal/app/azldev/agentskill/content/withoutlockfile/comp-toml.md.tmpl +++ b/internal/app/azldev/agentskill/content/withoutlockfile/comp-toml.md.tmpl @@ -37,7 +37,7 @@ Add sub-tables only for what you change. The fields you will reach for most: For generated Go dependencies, add a `source-files` entry with `origin.type = "go-vendor"`. This generates only a tarball, never converts the spec. -Omit `filename` to discover a unique vendor Source; set a stable basename for new +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 diff --git a/internal/app/azldev/cmds/component/render.go b/internal/app/azldev/cmds/component/render.go index dc2309a6a..b4b95dd2e 100644 --- a/internal/app/azldev/cmds/component/render.go +++ b/internal/app/azldev/cmds/component/render.go @@ -768,11 +768,6 @@ func finishComponentRender( return false, fmt.Errorf("filtering unreferenced files for %#q:\n%w", componentName, filterErr) } - if prep.comp.GetConfig().HasGoVendorSources() { - if err := sources.RenderVendorPin(env.FS(), prep.comp, specPath, mockResult.RawSpecFiles); err != nil { - return false, fmt.Errorf("rendering vendor source for %#q:\n%w", componentName, err) - } - } // Remove .git directory — must not appear in rendered output. // rpmautospec already read it during the batch mock phase. gitDir := filepath.Join(componentDir, ".git") diff --git a/internal/app/azldev/core/sources/govendor.go b/internal/app/azldev/core/sources/govendor.go index bdc512cce..83f8ff93f 100644 --- a/internal/app/azldev/core/sources/govendor.go +++ b/internal/app/azldev/core/sources/govendor.go @@ -13,7 +13,6 @@ import ( "strings" "github.com/microsoft/azure-linux-dev-tools/internal/app/azldev/core/components" - "github.com/microsoft/azure-linux-dev-tools/internal/global/opctx" "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" @@ -28,7 +27,7 @@ func WithGoVendorRunner(runner *mock.Runner) PreparerOption { return func(p *sourcePreparerImpl) { p.goVendorRunner = runner } } -// WithRenderManifest defers vendor entries until the normal render batch has expanded Source tags. +// WithRenderManifest renders declared vendor pins without downloading sources or generating payloads. func WithRenderManifest() PreparerOption { return func(p *sourcePreparerImpl) { p.skipLookaside, p.renderManifest = true, true } } @@ -37,69 +36,6 @@ func (p *sourcePreparerImpl) needsVendorInputs(config *projectconfig.ComponentCo return !p.renderManifest && config.HasGoVendorSources() } -// RenderVendorPin merges the reviewed pin into the manifest without fetching or generating an archive. -func RenderVendorPin(fs opctx.FS, comp components.Component, specPath, rawSpecFiles string) error { - for _, ref := range comp.GetConfig().SourceFiles { - if ref.Origin.Type != projectconfig.OriginTypeGoVendor { - continue - } - - data, err := fileutils.ReadFile(fs, specPath) - if err != nil { - return fmt.Errorf("reading vendor spec:\n%w", err) - } - - plan, err := spec.PrepareVendorSource(data, ref.Filename) - if err != nil { - return fmt.Errorf("identifying vendor Source:\n%w", err) - } - - if plan.SourceNumber != "" { - name, err := expandedVendorFilename(rawSpecFiles, plan.SourceNumber) - if err != nil { - return err - } - - if ref.Filename != "" && ref.Filename != name { - return fmt.Errorf("configured filename %#q does not match vendor Source %#q", ref.Filename, name) - } - - ref.Filename = name - } - - preparer := sourcePreparerImpl{fs: fs, skipLookaside: true} - - dir := filepath.Dir(specPath) - if err := preparer.resolveVendorTarget(comp, dir, &ref, plan.Automatic); err != nil { - return err - } - - config := *comp.GetConfig() - config.SourceFiles = []projectconfig.SourceFileReference{ref} - _, err = preparer.updateSourcesFile(vendorComponent{Component: comp, config: config}, dir, nil) - - return err - } - - return nil -} - -func expandedVendorFilename(output, number string) (string, error) { - for _, line := range strings.Split(output, "\n") { - tag, value, ok := strings.Cut(line, ":") - if ok && strings.EqualFold(tag, "Source"+number) { - name := strings.TrimSpace(value) - if err := fileutils.ValidateFilename(name); err != nil || strings.Contains(name, "%") { - return "", fmt.Errorf("invalid expanded vendor Source%s filename %#q", number, name) - } - - return name, nil - } - } - - return "", fmt.Errorf("vendor Source%s missing from expanded spec", number) -} - type vendorComponent struct { components.Component config projectconfig.ComponentConfig @@ -116,7 +52,7 @@ func vendorFingerprintConfig( result := *effective result.SourceFiles = slices.Clone(effective.SourceFiles) - // Generated hashes and discovered names are outputs, not declared build inputs. + // 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 @@ -193,21 +129,20 @@ func (p *sourcePreparerImpl) generateVendorSource( defer fileutils.RemoveAllAndUpdateErrorIfNil(p.fs, scratch, &err) artifact, err := govendor.Generate(ctx, p.fs, p.goVendorRunner, govendor.Request{ - SourceDir: directory, WorkDir: scratch, SpecName: filepath.Base(specPath), + 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, plan.Automatic) + return p.publishVendorSource(component, directory, ref, artifact) } func (p *sourcePreparerImpl) publishVendorSource( component components.Component, directory string, ref projectconfig.SourceFileReference, - artifact govendor.Artifact, automatic bool, + artifact govendor.Artifact, ) (projectconfig.SourceFileReference, error) { - ref.Filename = artifact.Name if ref.HashType == "" { ref.HashType = fileutils.HashTypeSHA512 } @@ -223,7 +158,7 @@ func (p *sourcePreparerImpl) publishVendorSource( } ref.Hash = digest - if err := p.resolveVendorTarget(component, directory, &ref, automatic); err != nil { + if err := p.resolveVendorTarget(component, directory, ref); err != nil { return ref, err } @@ -315,7 +250,7 @@ func (p *sourcePreparerImpl) vendorSettings( } func (p *sourcePreparerImpl) resolveVendorTarget( - component components.Component, directory string, ref *projectconfig.SourceFileReference, automatic bool, + 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 { @@ -333,30 +268,24 @@ func (p *sourcePreparerImpl) resolveVendorTarget( return fmt.Errorf("parsing vendor target manifest:\n%w", err) } - existing := map[string]fedorasource.SourcesFileEntry{} - - for _, line := range lines { - if line.Entry != nil { - existing[line.Entry.Filename] = *line.Entry - } - } - 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 !automatic || ref.ReplaceUpstream { - if _, _, _, err := p.processSourceRef(*ref, existing, component.GetName(), directory); err != nil { - return err + 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 _, found := existing[ref.Filename]; automatic && found { - ref.ReplaceUpstream = true - ref.ReplaceReason = "Regenerate the discovered Go vendor Source" + if exists { + return fmt.Errorf("vendor output %#q conflicts with an existing source", ref.Filename) + } } - return nil + _, 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 index 1f2513397..1b99324e6 100644 --- a/internal/app/azldev/core/sources/govendor_internal_test.go +++ b/internal/app/azldev/core/sources/govendor_internal_test.go @@ -26,7 +26,7 @@ import ( func TestGoVendorSourcePreparation(t *testing.T) { const newSource = "new" for _, mode := range []string{ - "discover", newSource, "expected hash", "mismatch", "collision", "diff", "skip overlays", + "replace", newSource, "expected hash", "mismatch", "collision", "diff", "skip overlays", } { t.Run(mode, func(t *testing.T) { ctx := newMockProcessorTestCtx() @@ -37,8 +37,10 @@ func TestGoVendorSourcePreparation(t *testing.T) { ref := projectconfig.SourceFileReference{Origin: projectconfig.Origin{ Type: projectconfig.OriginTypeGoVendor, ConfigFile: "/project/vendor.toml", }} - if mode == newSource || mode == "collision" { - ref.Filename = "vendor.tar.bz2" + + ref.Filename = "vendor.tar.bz2" + if mode != newSource && mode != "collision" { + ref.ReplaceUpstream, ref.ReplaceReason = true, "regenerate dependencies" } if mode == "mismatch" { @@ -109,18 +111,12 @@ func TestGoVendorSourcePreparation(t *testing.T) { assert.NotContains(t, string(prep), "tar -xf %{S:5}") assert.NotContains(t, string(prep), "Source5:") - if mode == newSource { - assert.Contains(t, string(prep), "%{shescape:vendor.tar.bz2}") - } - history, err := fileutils.ReadFile(ctx.FS(), filepath.Join(filepath.Dir(directory), "sources", ".git", "HEAD")) require.NoError(t, err) assert.Equal(t, "history", string(history)) - for name, content := range map[string]string{"name": "vendor.tar.bz2\n", "vendor.tar.bz2": payload} { - require.NoError(t, fileutils.WriteFile(ctx.FS(), filepath.Join(directory, name), - []byte(content), fileperms.PublicFile)) - } + require.NoError(t, fileutils.WriteFile(ctx.FS(), filepath.Join(directory, ref.Filename), + []byte(payload), fileperms.PublicFile)) return "", nil } @@ -184,7 +180,9 @@ func TestRenderVendorPin(t *testing.T) { comp := components_testutils.NewMockComponent(gomock.NewController(t)) comp.EXPECT().GetName().AnyTimes().Return("app") - ref := projectconfig.SourceFileReference{Origin: projectconfig.Origin{Type: projectconfig.OriginTypeGoVendor}} + 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) @@ -203,9 +201,12 @@ func TestRenderVendorPin(t *testing.T) { 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) - require.NoError(t, RenderVendorPin(ctx.FS(), comp, "/staged/app.spec", "Source7: app-2-vendor.tar.gz")) manifest, err := fileutils.ReadFile(ctx.FS(), "/staged/sources") require.NoError(t, err) diff --git a/internal/app/azldev/core/sources/mockprocessor.go b/internal/app/azldev/core/sources/mockprocessor.go index 04f68881a..a10ff7107 100644 --- a/internal/app/azldev/core/sources/mockprocessor.go +++ b/internal/app/azldev/core/sources/mockprocessor.go @@ -91,10 +91,9 @@ type ComponentInput struct { // ComponentMockResult holds the mock processing result for one component. type ComponentMockResult struct { - RawSpecFiles string // Includes the RPM Source numbers for vendor filename discovery. - Name string // Component name - SpecFiles []string // Files listed by spectool (basenames/relative paths) - Error error // Non-nil if rpmautospec or spectool failed for this component + Name string // Component name + SpecFiles []string // Files listed by spectool (basenames/relative paths) + Error error // Non-nil if rpmautospec or spectool failed for this component } // validateInputs validates all component inputs before batch processing. @@ -446,7 +445,6 @@ func parseBatchJSON(stdout string, inputs []ComponentInput) ([]ComponentMockResu } results[idx].SpecFiles = spectool.ParseSpectoolOutput(compResult.SpecFiles) - results[idx].RawSpecFiles = compResult.SpecFiles } return results, nil diff --git a/internal/app/azldev/core/sources/sourceprep.go b/internal/app/azldev/core/sources/sourceprep.go index 80c51123c..74ec16cde 100644 --- a/internal/app/azldev/core/sources/sourceprep.go +++ b/internal/app/azldev/core/sources/sourceprep.go @@ -1126,8 +1126,6 @@ func (p *sourcePreparerImpl) buildSourceEntries( 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") } - // The existing render batch expands the RPM Source filename after this stage. - continue } formatted, isReplacement, resolvedRef, err := p.processSourceRef( diff --git a/internal/govendor/generate.go b/internal/govendor/generate.go index f3ac9324e..3899e5d92 100644 --- a/internal/govendor/generate.go +++ b/internal/govendor/generate.go @@ -26,11 +26,11 @@ import ( // Request contains an isolated private spec and the effective native tool settings. type Request struct { - SourceDir, WorkDir, SpecName string - PrepSpec []byte - Config string - ModuleDir string - Packages []string + SourceDir, WorkDir, SpecName, Filename string + PrepSpec []byte + Config string + ModuleDir string + Packages []string } // Artifact is a host-owned copy of the generated tarball. @@ -51,7 +51,7 @@ func Generate(ctx context.Context, fs opctx.FS, base *mock.Runner, req Request) return Artifact{}, err } - return readArtifact(fs, req.WorkDir, output) + return readArtifact(fs, req.WorkDir, output, req.Filename) } func stage(fs opctx.FS, req Request) (string, error) { @@ -142,26 +142,14 @@ func execute(ctx context.Context, base *mock.Runner, req Request, output string) return nil } -func readArtifact(fs opctx.FS, workDir, output string) (Artifact, error) { - var artifact Artifact - // Copy opened regular files, never following chroot-controlled symlinks. - nameFile := filepath.Join(workDir, "name") - if err := collect(fs, filepath.Join(output, "name"), nameFile); err != nil { - return artifact, err - } - - name, err := fileutils.ReadFile(fs, nameFile) - if err != nil { - return artifact, fmt.Errorf("reading generated vendor name:\n%w", err) - } - - artifact.Name = strings.TrimSpace(string(name)) - if err := fileutils.ValidateFilename(artifact.Name); err != nil { - return artifact, fmt.Errorf("invalid generated vendor filename:\n%w", err) +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(artifact.Name, "%\r\n") || !archiveFilename(artifact.Name) { - return artifact, fmt.Errorf("unsupported generated vendor filename %#q", artifact.Name) + if strings.ContainsAny(name, "%\r\n") || !archiveFilename(name) { + return artifact, fmt.Errorf("unsupported vendor filename %#q", name) } artifact.Path = filepath.Join(workDir, artifact.Name) @@ -226,15 +214,13 @@ func generationCommand(req Request, arch string) ([]string, error) { quote("rpmautospec", "process-distgit", req.SpecName, req.SpecName), quote(prep...), "IFS= read -r root < /tmp/azldev-vendor/azldev-vendor-root", - "IFS= read -r name < /tmp/azldev-vendor/azldev-vendor-name", - `case "$name" in ""|*/*|*%*|.*) echo 'Invalid vendor filename' >&2; exit 1;; esac`, `cd "$root"`, "cd " + quote(module), quote("test", "-f", filepath.Join(config.General.ModuleDir, "go.mod")), `root=$(pwd -P)`, "cd /azldev-vendor-sources", - `go_vendor_archive create --config /azldev-vendor-output/config.toml --output "/azldev-vendor-output/$name" "$root"`, - `printf '%s\n' "$name" > /azldev-vendor-output/name`, + 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 diff --git a/internal/govendor/generate_internal_test.go b/internal/govendor/generate_internal_test.go index 54a58b288..85ff8885d 100644 --- a/internal/govendor/generate_internal_test.go +++ b/internal/govendor/generate_internal_test.go @@ -53,19 +53,15 @@ func TestGenerationFailureScrubsRoot(t *testing.T) { func TestReadArtifactRejectsInvalidOutputs(t *testing.T) { for _, testCase := range []struct{ name, wantErr string }{ - {"", "opening generated vendor output"}, - {"../host", "invalid generated vendor filename"}, + {"", "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)) - if testCase.name != "" { - require.NoError(t, fileutils.WriteFile(fs, "/work/output/name", []byte(testCase.name), fileperms.PublicFile)) - } - - _, err := readArtifact(fs, "/work", "/work/output") + _, err := readArtifact(fs, "/work", "/work/output", testCase.name) require.ErrorContains(t, err, testCase.wantErr) }) } diff --git a/internal/projectconfig/component.go b/internal/projectconfig/component.go index 47543ce25..d97a2d8fb 100644 --- a/internal/projectconfig/component.go +++ b/internal/projectconfig/component.go @@ -133,7 +133,7 @@ type SourceFileReference struct { Component ComponentReference `toml:"-" json:"-" fingerprint:"-"` // Name of the source file; must be non-empty. - Filename string `toml:"filename,omitempty" json:"filename,omitempty" jsonschema:"description=Source basename. Optional for go-vendor to discover the vendor Source from the spec."` + 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"` diff --git a/internal/projectconfig/govendor.go b/internal/projectconfig/govendor.go index 5bc1d4cc5..05053c126 100644 --- a/internal/projectconfig/govendor.go +++ b/internal/projectconfig/govendor.go @@ -111,8 +111,8 @@ func validateVendorSourceCount(refs []SourceFileReference) error { } func validateSourceFilename(ref SourceFileReference) error { - if ref.Origin.Type == OriginTypeGoVendor && ref.Filename == "" { - return nil + 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 { diff --git a/internal/projectconfig/govendor_test.go b/internal/projectconfig/govendor_test.go index 3165c7d66..9174cec58 100644 --- a/internal/projectconfig/govendor_test.go +++ b/internal/projectconfig/govendor_test.go @@ -17,7 +17,6 @@ import ( func TestGoVendorOriginValidation(t *testing.T) { for name, ref := range map[string]projectconfig.SourceFileReference{ - "discovered": {Origin: projectconfig.Origin{Type: projectconfig.OriginTypeGoVendor}}, "explicit": {Filename: "vendor.tar.bz2", Origin: projectconfig.Origin{ Type: projectconfig.OriginTypeGoVendor, ConfigFile: "vendor.toml", ModuleDir: "cmd/app", PrepPackages: []string{"patch"}, @@ -31,6 +30,13 @@ func TestGoVendorOriginValidation(t *testing.T) { }) } + 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"}}, diff --git a/internal/rpm/spec/vendorprep.go b/internal/rpm/spec/vendorprep.go index e63313413..50361ee45 100644 --- a/internal/rpm/spec/vendorprep.go +++ b/internal/rpm/spec/vendorprep.go @@ -15,10 +15,8 @@ import ( // VendorPrep describes a private prep spec, never a replacement published spec. type VendorPrep struct { - SourceNumber string - Spec []byte - ConfigName string - Automatic bool + Spec []byte + ConfigName string } var ( @@ -31,14 +29,12 @@ var ( // 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 filename != "" { - if err := fileutils.ValidateFilename(filename); err != nil { - return nil, fmt.Errorf("validating vendor filename:\n%w", err) - } + 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") - } + 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")) @@ -58,12 +54,12 @@ func PrepareVendorSource(data []byte, filename string) (*VendorPrep, error) { return nil, err } - candidates, err := vendorExtractions(prep, sources, filename == "") + candidates, err := vendorExtractions(prep, sources) if err != nil { return nil, err } - number, archive, err := selectVendorSource(sources, candidates, filename) + number, err := selectVendorSource(sources, candidates, filename) if err != nil { return nil, err } @@ -79,25 +75,18 @@ func PrepareVendorSource(data []byte, filename string) (*VendorPrep, error) { } } - appendVendorOutputCommands(prep, archive, filename, sources[number]) + 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, Automatic: filename == "", SourceNumber: number, + ConfigName: configName, }, nil } -func appendVendorOutputCommands(prep *sectionHandle, archive, filename, selectedSource string) { - if filename != "" && selectedSource != "" { - prep.AppendLines([]string{"test %{shescape:" + selectedSource + "} = %{shescape:" + filename + "}"}) - } - - prep.AppendLines([]string{ - `pwd -P > "%{_topdir}/azldev-vendor-root"`, - "printf '%%s\\n' %{shescape:" + archive + `} > "%{_topdir}/azldev-vendor-name"`, - }) -} - 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 { @@ -130,7 +119,7 @@ func vendorSourceTags(tree *specTree) (sources map[string]string, configNumber s return sources, configNumber, err } -func vendorExtractions(prep *sectionHandle, sources map[string]string, automatic bool) ([]string, error) { +func vendorExtractions(prep *sectionHandle, sources map[string]string) ([]string, error) { var candidates []string err := prep.VisitLines(func(line *lineHandle) error { @@ -143,8 +132,8 @@ func vendorExtractions(prep *sectionHandle, sources map[string]string, automatic return errors.New("secondary setup extraction requires an explicit prep overlay for vendor generation") } - if automatic && strings.HasPrefix(text, "%") && !knownPrepMacro.MatchString(text) { - return fmt.Errorf("cannot discover vendor Source through opaque prep macro %#q; make extraction explicit", text) + if strings.HasPrefix(text, "%") && !knownPrepMacro.MatchString(text) { + return fmt.Errorf("opaque vendor prep macro %#q; make extraction explicit", text) } match := vendorExtraction.FindStringSubmatch(text) @@ -170,38 +159,21 @@ func vendorExtractions(prep *sectionHandle, sources map[string]string, automatic func selectVendorSource( sources map[string]string, candidates []string, filename string, -) (number, archive string, err error) { - if len(candidates) > 1 || (filename == "" && len(candidates) != 1) { - return "", "", errors.New("cannot discover a unique vendor Source; set 'filename' and simplify prep extraction") - } - - archive = filename - - if len(candidates) == 1 { - number = candidates[0] - if filename == "" { - archive = sources[number] - } else if !strings.Contains(sources[number], "%") && sources[number] != filename { - return "", "", errors.New("explicit vendor filename does not match the extracted Source") - } +) (string, error) { + if len(candidates) > 1 { + return "", errors.New("ambiguous vendor extraction; simplify prep with an overlay") } - if strings.Contains(archive, "://") || strings.ContainsAny(archive, "\r\n") { - return "", "", errors.New("vendor Source must be a local archive filename") + if len(candidates) == 0 { + return vendorSourceWithFilename(sources, filename) } - if strings.Contains(archive, "%{release}") { - return "", "", errors.New("release-dependent vendor filenames require a stable Source overlay") + number := candidates[0] + if !strings.Contains(sources[number], "%") && sources[number] != filename { + return "", errors.New("configured vendor filename does not match the extracted Source") } - if filename != "" && number == "" { - number, err = vendorSourceWithFilename(sources, filename) - if err != nil { - return "", "", err - } - } - - return number, archive, nil + return number, nil } func vendorSourceWithFilename(sources map[string]string, filename string) (string, error) { diff --git a/internal/rpm/spec/vendorprep_test.go b/internal/rpm/spec/vendorprep_test.go index 0be14e154..e8006a66c 100644 --- a/internal/rpm/spec/vendorprep_test.go +++ b/internal/rpm/spec/vendorprep_test.go @@ -25,9 +25,8 @@ func vendorSpec() string { func TestPrepareVendorSource(t *testing.T) { input := vendorSpec() - plan, err := spec.PrepareVendorSource([]byte(input), "") + plan, err := spec.PrepareVendorSource([]byte(input), "app-1-vendor.tar.bz2") require.NoError(t, err) - assert.True(t, plan.Automatic) 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}") @@ -45,23 +44,21 @@ func TestPrepareVendorSourceRejectsAmbiguity(t *testing.T) { "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}"), - "no extraction": strings.ReplaceAll(vendorSpec(), "tar -xf %{S:5}", ""), "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:"), - "release filename": strings.ReplaceAll(vendorSpec(), "app-%{version}-vendor", "app-%{release}-vendor"), "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), "") + _, err := spec.PrepareVendorSource([]byte(input), "vendor.tar.bz2") require.Error(t, err) }) } - for _, name := range []string{"../outside.tar.gz", "%{name}.tar.gz", "bad\nname"} { + for _, name := range []string{"", "../outside.tar.gz", "%{name}.tar.gz", "bad\nname"} { _, err := spec.PrepareVendorSource([]byte(vendorSpec()), name) require.Error(t, err) } diff --git a/scenario/__snapshots__/TestSnapshotsContainer_config_generate-schema_stdout_1.snap b/scenario/__snapshots__/TestSnapshotsContainer_config_generate-schema_stdout_1.snap index 51b7123a8..300f70605 100755 --- a/scenario/__snapshots__/TestSnapshotsContainer_config_generate-schema_stdout_1.snap +++ b/scenario/__snapshots__/TestSnapshotsContainer_config_generate-schema_stdout_1.snap @@ -1352,7 +1352,7 @@ "properties": { "filename": { "type": "string", - "description": "Source basename. Optional for go-vendor to discover the vendor Source from the spec." + "description": "Source file basename." }, "hash": { "type": "string" @@ -1381,7 +1381,10 @@ } }, "additionalProperties": false, - "type": "object" + "type": "object", + "required": [ + "filename" + ] }, "SpecSource": { "properties": { diff --git a/scenario/__snapshots__/TestSnapshots_config_generate-schema_stdout_1.snap b/scenario/__snapshots__/TestSnapshots_config_generate-schema_stdout_1.snap index 51b7123a8..300f70605 100755 --- a/scenario/__snapshots__/TestSnapshots_config_generate-schema_stdout_1.snap +++ b/scenario/__snapshots__/TestSnapshots_config_generate-schema_stdout_1.snap @@ -1352,7 +1352,7 @@ "properties": { "filename": { "type": "string", - "description": "Source basename. Optional for go-vendor to discover the vendor Source from the spec." + "description": "Source file basename." }, "hash": { "type": "string" @@ -1381,7 +1381,10 @@ } }, "additionalProperties": false, - "type": "object" + "type": "object", + "required": [ + "filename" + ] }, "SpecSource": { "properties": { diff --git a/schemas/azldev.schema.json b/schemas/azldev.schema.json index 51b7123a8..300f70605 100644 --- a/schemas/azldev.schema.json +++ b/schemas/azldev.schema.json @@ -1352,7 +1352,7 @@ "properties": { "filename": { "type": "string", - "description": "Source basename. Optional for go-vendor to discover the vendor Source from the spec." + "description": "Source file basename." }, "hash": { "type": "string" @@ -1381,7 +1381,10 @@ } }, "additionalProperties": false, - "type": "object" + "type": "object", + "required": [ + "filename" + ] }, "SpecSource": { "properties": {