diff --git a/build.go b/build.go index 2407cad..e016675 100644 --- a/build.go +++ b/build.go @@ -31,6 +31,9 @@ type BuildRequest struct { // ModuleDir selects a repository-relative module directory; empty selects // the repository root. ModuleDir string + // Source selects explicit source and publication capabilities. Nil retains + // the ModuleDir Go-module shorthand. + Source *SourceSpec Version string // stable vMAJOR.MINOR.PATCH value injected at link time. Spec BuildSpec // application package, artifact name, and targets. OutputDir string // output location; relative paths use ModuleDir and empty selects /dist. @@ -87,7 +90,7 @@ func Build(ctx context.Context, request BuildRequest) (BuildResult, error) { return failure(err) } result.RepositoryDir = repositoryDir - identity, err := releaseidentity.FromWorkingTree(ctx, repositoryDir, request.ModuleDir, request.Version) + identity, err := releaseidentity.FromWorkingSource(ctx, repositoryDir, request.ModuleDir, request.Version, internalSourceSpec(request.Source)) result.ModuleDir, result.ModulePath, result.Tag = identity.ModuleDir, identity.ModulePath, identity.Tag if err != nil { return failure(err) diff --git a/check.go b/check.go index 454f9e0..2758565 100644 --- a/check.go +++ b/check.go @@ -39,9 +39,12 @@ type ReleaseRequest struct { // ModuleDir selects a repository-relative module directory; empty selects // the repository root. ModuleDir string - Product string - Version string // stable semantic version, independent of the derived Git tag. - Remote string + // Source selects explicit source and publication capabilities. Nil retains + // the ModuleDir Go-module shorthand. + Source *SourceSpec + Product string + Version string // stable semantic version, independent of the derived Git tag. + Remote string // ExpectedPushURL optionally requires Publish's resolved push URL to match // this string exactly before validation or tag creation. Check ignores this // publication-only expectation. A mismatch returns ErrUnexpectedPushURL. @@ -195,6 +198,7 @@ func candidateRequest(request ReleaseRequest) candidate.Request { result := candidate.Request{ RepositoryDir: request.RepositoryDir, ModuleDir: request.ModuleDir, + Source: internalSourceSpec(request.Source), Product: request.Product, Version: request.Version, Validation: validation.Settings{ diff --git a/cmd/releasekit/internal/cli/config.go b/cmd/releasekit/internal/cli/config.go index b8732d0..46dc358 100644 --- a/cmd/releasekit/internal/cli/config.go +++ b/cmd/releasekit/internal/cli/config.go @@ -14,6 +14,7 @@ import ( "strings" "go.maximumdirect.net/releasekit/internal/process" + "go.maximumdirect.net/releasekit/internal/releaseidentity" "go.maximumdirect.net/releasekit/internal/versioncontract" ) @@ -172,14 +173,50 @@ type CheckCommand struct { // Settings contains the product, remote, publication expectation, shared // validation selections, and check commands read from a releasekit.json profile. type Settings struct { - Product string `json:"product"` - ModuleDir string `json:"module_dir,omitempty"` - Remote string `json:"remote,omitempty"` - ExpectedPushURL string `json:"expected_push_url,omitempty"` - Checks []CheckCommand `json:"checks,omitempty"` - Validation *ValidationSettings `json:"validation,omitempty"` - Build *BuildSettings `json:"build,omitempty"` - Delivery *DeliverySettings `json:"delivery,omitempty"` + Product string `json:"product"` + ModuleDir string `json:"module_dir,omitempty"` + Source *SourceSettings `json:"source,omitempty"` + Go *struct{} `json:"go,omitempty"` + Publication *PublicationSettings `json:"publication,omitempty"` + Version *VersionSettings `json:"version,omitempty"` + Remote string `json:"remote,omitempty"` + ExpectedPushURL string `json:"expected_push_url,omitempty"` + Checks []CheckCommand `json:"checks,omitempty"` + Validation *ValidationSettings `json:"validation,omitempty"` + Build *BuildSettings `json:"build,omitempty"` + Delivery *DeliverySettings `json:"delivery,omitempty"` +} + +type SourceSettings struct { + Dir string `json:"dir,omitempty"` + TagPrefix *string `json:"tag_prefix,omitempty"` +} + +type PublicationSettings struct { + Mode string `json:"mode,omitempty"` +} + +type VersionSettings struct { + Format string `json:"format,omitempty"` + Prefix *string `json:"prefix,omitempty"` +} + +// SourceSpec maps the optional profile selection to the internal selection. +func (s Settings) SourceSpec() *releaseidentity.SourceSpec { + if s.Source == nil && s.Go == nil && s.Publication == nil && s.Version == nil { + return nil + } + result := &releaseidentity.SourceSpec{GoEnabled: s.Go != nil} + if s.Source != nil { + result.Dir, result.TagPrefix = s.Source.Dir, s.Source.TagPrefix + } + if s.Publication != nil { + result.Publication = s.Publication.Mode + } + if s.Version != nil { + result.VersionFormat, result.VersionPrefix = s.Version.Format, s.Version.Prefix + } + return result } // ValidationSettings selects shared candidate checks in a release profile. @@ -283,6 +320,12 @@ func LoadSettings(repoDir, configPath string) (Settings, error) { if strings.TrimSpace(settings.Product) == "" { return Settings{}, fmt.Errorf("profile %q: product is required", configPath) } + if source := settings.SourceSpec(); source != nil { + _, err := releaseidentity.NormalizeSource(settings.ModuleDir, source) + if err != nil { + return Settings{}, fmt.Errorf("profile %q: source selection: %w", configPath, err) + } + } if settings.Remote == "" { settings.Remote = "origin" } diff --git a/cmd/releasekit/internal/cli/source_test.go b/cmd/releasekit/internal/cli/source_test.go new file mode 100644 index 0000000..e25dfa2 --- /dev/null +++ b/cmd/releasekit/internal/cli/source_test.go @@ -0,0 +1,51 @@ +package cli + +import ( + "os" + "path/filepath" + "testing" +) + +func TestProfileSourceSelection(t *testing.T) { + tests := []struct { + name, fields string + explicit, goEnabled bool + mode, format string + emptyPrefix, invalid bool + }{ + {name: "legacy"}, + {name: "null is omitted", fields: `,"source":null,"go":null,"publication":null,"version":null`}, + {name: "source root", fields: `,"source":{}`, explicit: true}, + {name: "explicit unprefixed tag", fields: `,"source":{"tag_prefix":""}`, explicit: true}, + {name: "Go application", fields: `,"go":{}`, explicit: true, goEnabled: true}, + {name: "Go module", fields: `,"go":{},"publication":{"mode":"go-module"}`, explicit: true, goEnabled: true, mode: "go-module"}, + {name: "calendar with explicit empty prefix", fields: `,"version":{"format":"date","prefix":""}`, explicit: true, format: "date", emptyPrefix: true}, + {name: "unknown source field", fields: `,"source":{"unknown":true}`, invalid: true}, + {name: "module publication without Go", fields: `,"publication":{"mode":"go-module"}`, invalid: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "releasekit.json"), []byte(`{"product":"test"`+tt.fields+`}`), 0600); err != nil { + t.Fatal(err) + } + settings, err := LoadSettings(dir, "") + if (err != nil) != tt.invalid { + t.Fatalf("LoadSettings error = %v", err) + } + if tt.invalid { + return + } + source := settings.SourceSpec() + if (source != nil) != tt.explicit { + t.Fatalf("source = %+v", source) + } + if source != nil && (source.GoEnabled != tt.goEnabled || string(source.Publication) != tt.mode || string(source.VersionFormat) != tt.format || (source.VersionPrefix != nil && *source.VersionPrefix == "") != tt.emptyPrefix) { + t.Fatalf("source = %+v", source) + } + if tt.name == "explicit unprefixed tag" && (source.TagPrefix == nil || *source.TagPrefix != "") { + t.Fatalf("tag prefix was not preserved: %+v", source) + } + }) + } +} diff --git a/cmd/releasekit/main.go b/cmd/releasekit/main.go index 4ef1e3f..68c78f0 100644 --- a/cmd/releasekit/main.go +++ b/cmd/releasekit/main.go @@ -204,6 +204,7 @@ func runBuild(ctx context.Context, invocation cli.Invocation, stdout, stderr io. result, err := releasekit.Build(ctx, releasekit.BuildRequest{ RepositoryDir: invocation.Repository, ModuleDir: settings.ModuleDir, + Source: sourceSpec(settings), Version: invocation.Version, Spec: *configuredBuildSpec(settings.Build), OutputDir: invocation.OutputDir, @@ -252,10 +253,22 @@ func runBuild(ctx context.Context, invocation cli.Invocation, stdout, stderr io. return 0 } +func sourceSpec(settings cli.Settings) *releasekit.SourceSpec { + source := settings.SourceSpec() + if source == nil { + return nil + } + return &releasekit.SourceSpec{ + Dir: source.Dir, GoEnabled: source.GoEnabled, Publication: releasekit.PublicationMode(source.Publication), + VersionFormat: releasekit.VersionFormat(source.VersionFormat), VersionPrefix: source.VersionPrefix, TagPrefix: source.TagPrefix, + } +} + func candidateRequest(invocation cli.Invocation, settings cli.Settings, output io.Writer) releasekit.ReleaseRequest { request := releasekit.ReleaseRequest{ RepositoryDir: invocation.Repository, ModuleDir: settings.ModuleDir, + Source: sourceSpec(settings), Product: settings.Product, Version: invocation.Version, Remote: settings.Remote, @@ -520,6 +533,7 @@ func deliverWithDestination(ctx context.Context, invocation cli.Invocation, sett result, err := releasekit.Deliver(ctx, releasekit.DeliveryRequest{ RepositoryDir: invocation.Repository, ModuleDir: settings.ModuleDir, + Source: sourceSpec(settings), Product: settings.Product, Version: invocation.Version, ExpectedTag: invocation.ExpectedTag, diff --git a/cmd/releasekit/source_test.go b/cmd/releasekit/source_test.go new file mode 100644 index 0000000..1011175 --- /dev/null +++ b/cmd/releasekit/source_test.go @@ -0,0 +1,24 @@ +package main + +import ( + "testing" + + "go.maximumdirect.net/releasekit/cmd/releasekit/internal/cli" +) + +func TestSourceSelectionMapsToRequest(t *testing.T) { + empty := "" + settings := cli.Settings{ + ModuleDir: "app", + Source: &cli.SourceSettings{TagPrefix: &empty}, + Go: &struct{}{}, + Version: &cli.VersionSettings{Format: "date", Prefix: &empty}, + } + request := candidateRequest(cli.Invocation{}, settings, nil) + if request.Source == nil || !request.Source.GoEnabled || request.Source.Dir != "" || string(request.Source.Publication) != "" || string(request.Source.VersionFormat) != "date" || request.Source.VersionPrefix == nil || *request.Source.VersionPrefix != "" || request.Source.TagPrefix == nil || *request.Source.TagPrefix != "" || request.ModuleDir != "app" { + t.Fatalf("mapped selection = %+v, module directory = %q", request.Source, request.ModuleDir) + } + if sourceSpec(cli.Settings{}) != nil { + t.Fatal("legacy profile was converted to an explicit source selection") + } +} diff --git a/delivery.go b/delivery.go index 5133927..03d301e 100644 --- a/delivery.go +++ b/delivery.go @@ -101,8 +101,11 @@ type DeliveryRequest struct { // ModuleDir selects a repository-relative module directory; empty selects // the repository root. ModuleDir string - Product string - Version string + // Source selects explicit source and publication capabilities. Nil retains + // the ModuleDir Go-module shorthand. + Source *SourceSpec + Product string + Version string // ExpectedTag optionally requires the full CI event tag to match the // selected module's derived tag before building or making hosted requests. ExpectedTag string @@ -165,6 +168,7 @@ func Deliver(ctx context.Context, request DeliveryRequest) (DeliveryResult, erro internalResult, err := internaldelivery.Deliver(ctx, internaldelivery.Request{ RepositoryDir: request.RepositoryDir, ModuleDir: request.ModuleDir, + Source: internalSourceSpec(request.Source), Product: request.Product, Version: request.Version, ExpectedTag: request.ExpectedTag, diff --git a/docs/adr/0005-module-release-scope.md b/docs/adr/0005-module-release-scope.md index e61084c..38bdee7 100644 --- a/docs/adr/0005-module-release-scope.md +++ b/docs/adr/0005-module-release-scope.md @@ -2,7 +2,9 @@ ## Status -Accepted. +Accepted; partially superseded by [ADR 0007](0007-general-source-release-identity.md) +for releases that do not select Go module publication. Its module-scoped +validation and Go module publication conventions continue to apply. ## Date diff --git a/docs/adr/0007-general-source-release-identity.md b/docs/adr/0007-general-source-release-identity.md index 6ea4ca8..f87e972 100644 --- a/docs/adr/0007-general-source-release-identity.md +++ b/docs/adr/0007-general-source-release-identity.md @@ -2,7 +2,7 @@ ## Status -Draft for review. Upon acceptance, supersedes the requirement in +Accepted. Supersedes the requirement in [ADR 0005](0005-module-release-scope.md) that every release selects a Go module. Its module-scoped validation and Go module publication conventions continue to apply to those uses. diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index b691503..bcc7057 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -34,6 +34,12 @@ source-publication completion point continue to apply. ## Stage 1: Normalize source, Go, and publication selection +**Completed:** Profile and facade selection now preserve legacy module defaults, +normalize explicit selections, resolve physical working or committed directories, +and load Go declarations only when selected. Targeted identity, candidate, profile, +and facade mapping tests pass, as does the compiled API/dependency check. General +source identity and the corresponding operation behavior follow in the next stages. + **Work:** refactor profile loading in `cmd/releasekit/internal/cli/config.go` and introduce the shared internal selection model in `internal/releaseidentity`. diff --git a/internal/candidate/check.go b/internal/candidate/check.go index aa3dd45..63ef31a 100644 --- a/internal/candidate/check.go +++ b/internal/candidate/check.go @@ -33,6 +33,7 @@ type Candidate struct { type Request struct { RepositoryDir string ModuleDir string + Source *releaseidentity.SourceSpec Product string Version string Validation validation.Settings @@ -91,7 +92,7 @@ func Capture(ctx context.Context, request Request) (Candidate, error) { return captured, fmt.Errorf("release candidate worktree and index must be clean:\n%s", state.status) } - identity, err := releaseidentity.FromCommitted(ctx, repositoryDir, request.ModuleDir, request.Version, state.commit) + identity, err := releaseidentity.FromCommittedSource(ctx, repositoryDir, request.ModuleDir, request.Version, state.commit, request.Source) captured.ModuleDir = identity.ModuleDir captured.ModulePath = identity.ModulePath captured.Tag = identity.Tag diff --git a/internal/candidate/check_test.go b/internal/candidate/check_test.go index f76e5c2..1fa63c0 100644 --- a/internal/candidate/check_test.go +++ b/internal/candidate/check_test.go @@ -14,6 +14,7 @@ import ( "testing" "go.maximumdirect.net/releasekit/internal/gotool" + "go.maximumdirect.net/releasekit/internal/releaseidentity" "go.maximumdirect.net/releasekit/internal/validation" ) @@ -47,6 +48,27 @@ func TestValidStableVersion(t *testing.T) { } } +func TestCaptureUsesExplicitModuleSelection(t *testing.T) { + repository := newRepository(t, "# Example Product v1.2.3\n\nRoot release.\n") + moduleDir := "components/tool" + writeTestFile(t, repository, moduleDir+"/go.mod", "module example.com/tool\n") + writeTestFile(t, repository, moduleDir+"/docs/releases/v1.2.3.md", "# Example Product v1.2.3\n\nNested release.\n") + gitRun(t, repository, "add", moduleDir) + gitRun(t, repository, "commit", "-m", "add nested module") + + captured, err := Capture(context.Background(), Request{ + RepositoryDir: repository, + Source: &releaseidentity.SourceSpec{Dir: moduleDir, GoEnabled: true, Publication: "go-module"}, + Product: "Example Product", Version: testVersion, + }) + if err != nil { + t.Fatal(err) + } + if captured.ModuleDir != filepath.Join(repository, moduleDir) || captured.ModulePath != "example.com/tool" || captured.Tag != moduleDir+"/"+testVersion { + t.Fatalf("captured candidate = %+v", captured) + } +} + func TestCheckCapturesCandidateAndCallsAdditionalChecksOnce(t *testing.T) { repository := newRepository(t, "# Example Product v1.2.3\n\nRelease note.\n") writeTestFile(t, repository, "guide.md", "# Guide\n[section](#guide)\n") diff --git a/internal/delivery/delivery.go b/internal/delivery/delivery.go index 9b124d5..e8474f9 100644 --- a/internal/delivery/delivery.go +++ b/internal/delivery/delivery.go @@ -33,6 +33,7 @@ const ( type Request struct { RepositoryDir string ModuleDir string + Source *releaseidentity.SourceSpec Product string Version string ExpectedTag string @@ -85,7 +86,7 @@ func deliver(ctx context.Context, request Request, remove func(string) error) (r return result, err } result.CandidateCommit = commit - identity, err := releaseidentity.FromCommitted(ctx, repositoryDir, request.ModuleDir, request.Version, commit) + identity, err := releaseidentity.FromCommittedSource(ctx, repositoryDir, request.ModuleDir, request.Version, commit, request.Source) result.ModuleDir = identity.ModuleDir result.ModulePath = identity.ModulePath result.Tag = identity.Tag diff --git a/internal/publish/publish.go b/internal/publish/publish.go index a530c4a..59c6adf 100644 --- a/internal/publish/publish.go +++ b/internal/publish/publish.go @@ -11,6 +11,7 @@ import ( "go.maximumdirect.net/releasekit/internal/candidate" "go.maximumdirect.net/releasekit/internal/git" "go.maximumdirect.net/releasekit/internal/gotool" + "go.maximumdirect.net/releasekit/internal/releaseidentity" "go.maximumdirect.net/releasekit/internal/validation" ) @@ -44,6 +45,7 @@ var ErrUnexpectedPushURL = errors.New("unexpected publication push URL") type Request struct { RepositoryDir string ModuleDir string + Source *releaseidentity.SourceSpec Product string Version string Remote string @@ -101,6 +103,7 @@ func Publish(ctx context.Context, request Request) (result Result, resultErr err checks := candidate.Request{ RepositoryDir: request.RepositoryDir, ModuleDir: request.ModuleDir, + Source: request.Source, Product: request.Product, Version: request.Version, Validation: request.Validation, diff --git a/internal/releaseidentity/identity.go b/internal/releaseidentity/identity.go index 5fe6e2c..3b534d3 100644 --- a/internal/releaseidentity/identity.go +++ b/internal/releaseidentity/identity.go @@ -5,7 +5,6 @@ package releaseidentity import ( "context" "fmt" - "os" "path" "path/filepath" "strings" @@ -73,15 +72,14 @@ func ResolveSelection(repositoryDir, moduleDir string) (Selection, error) { // FromCommitted derives identity from the selected module declaration at a // captured commit. The selected module must contain its own go.mod. func FromCommitted(ctx context.Context, repositoryDir, moduleDir, version, commit string) (Identity, error) { - resolver, err := committedPaths(repositoryDir, commit) - if err != nil { - return Identity{Version: version}, err - } - selection, err := selectCommittedDirectory(ctx, resolver, moduleDir) - if err != nil { - return Identity{Selection: selection, Version: version}, err - } - return fromCommittedSelection(ctx, selection, version, commit, resolver) + return FromCommittedSource(ctx, repositoryDir, moduleDir, version, commit, nil) +} + +// FromCommittedSource resolves source selection and the declaration captured at +// commit before deriving the currently supported module publication identity. +func FromCommittedSource(ctx context.Context, repositoryDir, moduleDir, version, commit string, source *SourceSpec) (Identity, error) { + selection, err := LoadCommittedSource(ctx, repositoryDir, moduleDir, commit, source) + return deriveSelectedModule(selection, version, err) } // ResolveCommittedSelection resolves directory selection without reading the @@ -126,46 +124,63 @@ func selectCommittedDirectory(ctx context.Context, resolver git.PathResolver, mo return selection, nil } -func fromCommittedSelection(ctx context.Context, selection Selection, version, commit string, resolver git.PathResolver) (Identity, error) { - identity := Identity{Selection: selection, Version: version} +func readCommittedDeclaration(ctx context.Context, selection Selection, commit string, resolver git.PathResolver) ([]byte, error) { if err := ctx.Err(); err != nil { - return identity, fmt.Errorf("resolve committed release identity: %w", err) + return nil, fmt.Errorf("resolve committed release identity: %w", err) } declarationPath, err := resolver.ResolveDestination(ctx, "go.mod", moduleFilePath(selection.ModuleSubdir)) if err != nil { - return identity, fmt.Errorf("resolve selected module declaration at %s: %w", commit, err) + return nil, fmt.Errorf("resolve selected module declaration at %s: %w", commit, err) } if declarationPath.Kind != git.DestinationEntry { - return identity, fmt.Errorf("selected module declaration resolves to %s at %q", declarationPath.Kind, declarationPath.Path) + return nil, fmt.Errorf("selected module declaration resolves to %s at %q", declarationPath.Kind, declarationPath.Path) } entry, _, err := resolver.Lookup(ctx, declarationPath.Path) if err != nil { - return identity, err + return nil, err } declaration, err := git.ReadBlob(ctx, selection.RepositoryDir, entry.ObjectID) if err != nil { - return identity, fmt.Errorf("read selected module declaration at %s: %w", commit, err) + return nil, fmt.Errorf("read selected module declaration at %s: %w", commit, err) } - return Derive(selection, declaration, version) + return declaration, nil } // FromWorkingTree derives identity from the selected module declaration in the // working tree. The selected module must contain its own go.mod. func FromWorkingTree(ctx context.Context, repositoryDir, moduleDir, version string) (Identity, error) { - selection, err := ResolveSelection(repositoryDir, moduleDir) - identity := Identity{Selection: selection, Version: version} + return FromWorkingSource(ctx, repositoryDir, moduleDir, version, nil) +} + +// FromWorkingSource resolves source selection and a working declaration before +// deriving the currently supported module publication identity. +func FromWorkingSource(ctx context.Context, repositoryDir, moduleDir, version string, source *SourceSpec) (Identity, error) { + selection, err := LoadWorkingSource(ctx, repositoryDir, moduleDir, source) + return deriveSelectedModule(selection, version, err) +} + +func deriveSelectedModule(source ResolvedSource, version string, err error) (Identity, error) { + identity := Identity{Selection: source.Selection, ModulePath: source.ModulePath, Version: version} if err != nil { return identity, err } - if err := ctx.Err(); err != nil { - return identity, fmt.Errorf("resolve working-tree release identity: %w", err) + if source.Publication != "go-module" { + return identity, fmt.Errorf("general source release identity is not yet supported") } - declarationPath := filepath.Join(selection.ModuleDir, "go.mod") - declaration, err := os.ReadFile(declarationPath) + if source.VersionFormat != "semver" || source.VersionPrefix != "v" { + return identity, fmt.Errorf("Go module publication requires prefixed semantic versions and the module-derived tag") + } + identity, err = deriveModule(source.Selection, source.ModulePath, version) if err != nil { - return identity, fmt.Errorf("read selected module declaration %q: %w", declarationPath, err) + return identity, err } - return Derive(selection, declaration, version) + if source.TagPrefix != nil { + prefix := strings.TrimSuffix(strings.TrimSuffix(identity.Tag, version), "/") + if *source.TagPrefix != prefix { + return identity, fmt.Errorf("source tag prefix %q conflicts with Go module tag prefix %q", *source.TagPrefix, prefix) + } + } + return identity, nil } // Derive applies Go module path-major rules and derives the standard full tag @@ -175,14 +190,16 @@ func Derive(selection Selection, declaration []byte, version string) (Identity, if selection.RepositoryDir == "" || selection.ModuleDir == "" || selection.ModuleSubdir == "" { return identity, fmt.Errorf("incomplete module selection") } - modulePath := modfile.ModulePath(declaration) - if modulePath == "" { - return identity, fmt.Errorf("selected module declaration has no valid module directive") - } + modulePath, err := modulePathFromDeclaration(declaration) identity.ModulePath = modulePath - if err := module.CheckImportPath(modulePath); err != nil { - return identity, fmt.Errorf("invalid module path %q: %w", modulePath, err) + if err != nil { + return identity, err } + return deriveModule(selection, modulePath, version) +} + +func deriveModule(selection Selection, modulePath, version string) (Identity, error) { + identity := Identity{Selection: selection, ModulePath: modulePath, Version: version} _, pathMajor, ok := module.SplitPathVersion(modulePath) if !ok { return identity, fmt.Errorf("module path %q has an invalid major-version suffix", modulePath) @@ -212,6 +229,20 @@ func Derive(selection Selection, declaration []byte, version string) (Identity, }, nil } +func modulePathFromDeclaration(declaration []byte) (string, error) { + modulePath := modfile.ModulePath(declaration) + if modulePath == "" { + return "", fmt.Errorf("selected module declaration has no valid module directive") + } + if err := module.CheckImportPath(modulePath); err != nil { + return modulePath, fmt.Errorf("invalid module path %q: %w", modulePath, err) + } + if _, _, ok := module.SplitPathVersion(modulePath); !ok { + return modulePath, fmt.Errorf("module path %q has an invalid major-version suffix", modulePath) + } + return modulePath, nil +} + func moduleFilePath(moduleSubdir string) string { if moduleSubdir == "." { return "go.mod" diff --git a/internal/releaseidentity/selection.go b/internal/releaseidentity/selection.go new file mode 100644 index 0000000..f215acc --- /dev/null +++ b/internal/releaseidentity/selection.go @@ -0,0 +1,210 @@ +package releaseidentity + +import ( + "context" + "fmt" + "os" + "path/filepath" + + "go.maximumdirect.net/releasekit/internal/git" +) + +// SourceSpec describes explicit source, Go, publication, and version choices. +// Nil SourceSpec selects the historical Go-module shorthand. +type SourceSpec struct { + Dir string + GoEnabled bool + Publication string + VersionFormat string + VersionPrefix *string + TagPrefix *string +} + +// SourceSelection contains the normalized configuration, independent of the +// working or committed module declaration. +type SourceSelection struct { + Dir string + GoEnabled bool + Publication string + VersionFormat string + VersionPrefix string + TagPrefix *string +} + +// ResolvedSource joins the configuration selection with its physical scope. +type ResolvedSource struct { + SourceSelection + Selection + ModulePath string +} + +// ResolveWorkingSource resolves the selected working-tree directory without +// requiring a module declaration. +func ResolveWorkingSource(repositoryDir, moduleDir string, source *SourceSpec) (ResolvedSource, error) { + config, err := NormalizeSource(moduleDir, source) + if err != nil { + return ResolvedSource{}, err + } + directory, err := ResolveSelection(repositoryDir, sourceDirectory(moduleDir, source)) + if err != nil { + return ResolvedSource{SourceSelection: config}, err + } + if source != nil && source.Dir != "" && moduleDir != "" { + module, err := ResolveSelection(repositoryDir, moduleDir) + if err != nil { + return ResolvedSource{SourceSelection: config, Selection: directory}, err + } + if module.ModuleDir != directory.ModuleDir { + return ResolvedSource{SourceSelection: config, Selection: directory}, selectionConflict(source.Dir, moduleDir) + } + } + info, err := os.Stat(directory.ModuleDir) + if err != nil { + return ResolvedSource{SourceSelection: config, Selection: directory}, fmt.Errorf("inspect source directory: %w", err) + } + if !info.IsDir() { + return ResolvedSource{SourceSelection: config, Selection: directory}, fmt.Errorf("selected source %q is not a directory", config.Dir) + } + config.Dir = directory.ModuleSubdir + return ResolvedSource{SourceSelection: config, Selection: directory}, nil +} + +// ResolveCommittedSource resolves the selected directory in a captured commit +// without reading a module declaration or relying on the working tree. +func ResolveCommittedSource(ctx context.Context, repositoryDir, moduleDir, commit string, source *SourceSpec) (ResolvedSource, error) { + config, err := NormalizeSource(moduleDir, source) + if err != nil { + return ResolvedSource{}, err + } + resolver, err := committedPaths(repositoryDir, commit) + if err != nil { + return ResolvedSource{SourceSelection: config}, err + } + directory, err := resolveCommittedSourceDirectory(ctx, resolver, moduleDir, source) + if err == nil { + config.Dir = directory.ModuleSubdir + } + return ResolvedSource{SourceSelection: config, Selection: directory}, err +} + +// LoadWorkingSource resolves the source scope and reads its module declaration +// only when Go capability is selected. +func LoadWorkingSource(ctx context.Context, repositoryDir, moduleDir string, source *SourceSpec) (ResolvedSource, error) { + if err := ctx.Err(); err != nil { + return ResolvedSource{}, err + } + resolved, err := ResolveWorkingSource(repositoryDir, moduleDir, source) + if err != nil || !resolved.GoEnabled { + return resolved, err + } + if err := ctx.Err(); err != nil { + return resolved, err + } + declarationPath := filepath.Join(resolved.ModuleDir, "go.mod") + declaration, err := os.ReadFile(declarationPath) + if err != nil { + return resolved, fmt.Errorf("read selected module declaration %q: %w", declarationPath, err) + } + resolved.ModulePath, err = modulePathFromDeclaration(declaration) + return resolved, err +} + +// LoadCommittedSource reads the selected module declaration from the captured +// commit, without requiring that declaration in the working tree. +func LoadCommittedSource(ctx context.Context, repositoryDir, moduleDir, commit string, source *SourceSpec) (ResolvedSource, error) { + config, err := NormalizeSource(moduleDir, source) + if err != nil { + return ResolvedSource{}, err + } + resolver, err := committedPaths(repositoryDir, commit) + if err != nil { + return ResolvedSource{SourceSelection: config}, err + } + directory, err := resolveCommittedSourceDirectory(ctx, resolver, moduleDir, source) + resolved := ResolvedSource{SourceSelection: config, Selection: directory} + if err != nil { + return resolved, err + } + resolved.Dir = directory.ModuleSubdir + if !resolved.GoEnabled { + return resolved, nil + } + declaration, err := readCommittedDeclaration(ctx, directory, commit, resolver) + if err != nil { + return resolved, err + } + resolved.ModulePath, err = modulePathFromDeclaration(declaration) + return resolved, err +} + +func resolveCommittedSourceDirectory(ctx context.Context, resolver git.PathResolver, moduleDir string, source *SourceSpec) (Selection, error) { + directory, err := selectCommittedDirectory(ctx, resolver, sourceDirectory(moduleDir, source)) + if err != nil { + return directory, err + } + if source != nil && source.Dir != "" && moduleDir != "" { + module, err := selectCommittedDirectory(ctx, resolver, moduleDir) + if err != nil { + return directory, err + } + if module.ModuleSubdir != directory.ModuleSubdir { + return directory, selectionConflict(source.Dir, moduleDir) + } + } + return directory, nil +} + +func selectionConflict(sourceDir, moduleDir string) error { + return fmt.Errorf("source.dir %q conflicts with module_dir %q", sourceDir, moduleDir) +} + +func sourceDirectory(moduleDir string, source *SourceSpec) string { + if source != nil && source.Dir != "" { + return source.Dir + } + return moduleDir +} + +// NormalizeSource applies explicit defaults and preserves the legacy shorthand. +func NormalizeSource(moduleDir string, source *SourceSpec) (SourceSelection, error) { + if source == nil { + source = &SourceSpec{GoEnabled: true, Publication: "go-module"} + } + dir := source.Dir + if dir == "" { + dir = moduleDir + } + if dir == "" { + dir = "." + } + if filepath.IsAbs(dir) { + return SourceSelection{}, fmt.Errorf("source directory must be repository-relative: %q", dir) + } + result := SourceSelection{Dir: filepath.ToSlash(filepath.Clean(dir)), GoEnabled: source.GoEnabled, Publication: source.Publication, VersionFormat: source.VersionFormat, TagPrefix: source.TagPrefix} + if result.Publication == "" { + result.Publication = "source" + } + if result.Publication != "source" && result.Publication != "go-module" { + return SourceSelection{}, fmt.Errorf("invalid publication mode %q", result.Publication) + } + if result.Publication == "go-module" && !result.GoEnabled { + return SourceSelection{}, fmt.Errorf("go-module publication requires Go capability") + } + if result.VersionFormat == "" { + result.VersionFormat = "semver" + } + switch result.VersionFormat { + case "semver": + result.VersionPrefix = "v" + case "date", "year-month": + default: + return SourceSelection{}, fmt.Errorf("invalid version format %q", result.VersionFormat) + } + if source.VersionPrefix != nil { + result.VersionPrefix = *source.VersionPrefix + } + if result.VersionPrefix != "" && result.VersionPrefix != "v" { + return SourceSelection{}, fmt.Errorf("version prefix must be \"v\" or empty") + } + return result, nil +} diff --git a/internal/releaseidentity/selection_test.go b/internal/releaseidentity/selection_test.go new file mode 100644 index 0000000..141f29c --- /dev/null +++ b/internal/releaseidentity/selection_test.go @@ -0,0 +1,141 @@ +package releaseidentity + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestNormalizeSource(t *testing.T) { + empty := "" + tests := []struct { + name string + module string + source *SourceSpec + want SourceSelection + invalid bool + }{ + {name: "legacy", module: "nested", want: SourceSelection{Dir: "nested", GoEnabled: true, Publication: "go-module", VersionFormat: "semver", VersionPrefix: "v"}}, + {name: "explicit root", source: &SourceSpec{}, want: SourceSelection{Dir: ".", Publication: "source", VersionFormat: "semver", VersionPrefix: "v"}}, + {name: "Go application", module: "app", source: &SourceSpec{GoEnabled: true, VersionFormat: "date"}, want: SourceSelection{Dir: "app", GoEnabled: true, Publication: "source", VersionFormat: "date"}}, + {name: "Go module", module: "app/.", source: &SourceSpec{Dir: "app", GoEnabled: true, Publication: "go-module", VersionPrefix: &empty}, want: SourceSelection{Dir: "app", GoEnabled: true, Publication: "go-module", VersionFormat: "semver"}}, + {name: "missing Go", source: &SourceSpec{Publication: "go-module"}, invalid: true}, + {name: "invalid format", source: &SourceSpec{VersionFormat: "other"}, invalid: true}, + {name: "invalid prefix", source: &SourceSpec{VersionPrefix: strPtr("release-")}, invalid: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := NormalizeSource(tt.module, tt.source) + if (err != nil) != tt.invalid { + t.Fatalf("NormalizeSource error = %v", err) + } + if !tt.invalid && got != tt.want { + t.Fatalf("NormalizeSource = %+v, want %+v", got, tt.want) + } + }) + } +} + +func TestLoadSourceUsesSelectedDeclaration(t *testing.T) { + repo := t.TempDir() + gitIdentityRun(t, repo, "init", "-q") + gitIdentityRun(t, repo, "config", "user.name", "ReleaseKit test") + gitIdentityRun(t, repo, "config", "user.email", "releasekit@example.invalid") + if err := os.Mkdir(filepath.Join(repo, "app"), 0755); err != nil { + t.Fatal(err) + } + mod := filepath.Join(repo, "app", "go.mod") + if err := os.WriteFile(mod, []byte("module example.com/committed\n"), 0644); err != nil { + t.Fatal(err) + } + if err := os.Symlink("app", filepath.Join(repo, "alias")); err != nil { + t.Fatal(err) + } + if err := os.Mkdir(filepath.Join(repo, "config"), 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(repo, "config", "settings.json"), []byte("{}"), 0644); err != nil { + t.Fatal(err) + } + gitIdentityRun(t, repo, "add", ".") + gitIdentityRun(t, repo, "commit", "-qm", "add module") + commit := strings.TrimSpace(gitIdentityOutput(t, repo, "rev-parse", "HEAD")) + if err := os.WriteFile(mod, []byte("module example.com/working\n"), 0644); err != nil { + t.Fatal(err) + } + spec := &SourceSpec{Dir: "app", GoEnabled: true} + working, err := LoadWorkingSource(context.Background(), repo, "", spec) + if err != nil || working.ModulePath != "example.com/working" || working.ModuleSubdir != "app" || working.Publication != "source" { + t.Fatalf("working source = %+v, error = %v", working, err) + } + committed, err := LoadCommittedSource(context.Background(), repo, "", commit, spec) + if err != nil || committed.ModulePath != "example.com/committed" || committed.ModuleSubdir != "app" { + t.Fatalf("committed source = %+v, error = %v", committed, err) + } + if _, err := LoadCommittedSource(context.Background(), repo, "alias", commit, spec); err != nil { + t.Fatalf("matching committed directories: %v", err) + } + if _, err := LoadCommittedSource(context.Background(), repo, ".", commit, spec); err == nil { + t.Fatal("expected conflicting committed directories to fail") + } + moduleSpec := &SourceSpec{Dir: "app", GoEnabled: true, Publication: "go-module"} + identity, err := FromCommittedSource(context.Background(), repo, "alias", "v1.2.3", commit, moduleSpec) + if err != nil || identity.ModulePath != "example.com/committed" || identity.Tag != "app/v1.2.3" { + t.Fatalf("explicit module identity = %+v, error = %v", identity, err) + } + matchingPrefix, conflictingPrefix := "app", "other" + moduleSpec.TagPrefix = &matchingPrefix + if _, err := FromCommittedSource(context.Background(), repo, "", "v1.2.3", commit, moduleSpec); err != nil { + t.Fatalf("matching module tag prefix: %v", err) + } + moduleSpec.TagPrefix = &conflictingPrefix + if _, err := FromCommittedSource(context.Background(), repo, "", "v1.2.3", commit, moduleSpec); err == nil { + t.Fatal("accepted conflicting module tag prefix") + } + config, err := LoadCommittedSource(context.Background(), repo, "", commit, &SourceSpec{Dir: "config"}) + if err != nil || config.ModulePath != "" || config.ModuleSubdir != "config" { + t.Fatalf("committed source-only selection = %+v, error = %v", config, err) + } + if err := os.Remove(mod); err != nil { + t.Fatal(err) + } + if _, err := LoadWorkingSource(context.Background(), repo, "", spec); err == nil { + t.Fatal("Go selection accepted a missing module declaration") + } + if source, err := LoadWorkingSource(context.Background(), repo, "", &SourceSpec{Dir: "app"}); err != nil || source.ModulePath != "" { + t.Fatalf("source-only selection = %+v, error = %v", source, err) + } +} + +func strPtr(s string) *string { return &s } + +func TestResolveWorkingSourceWithoutModule(t *testing.T) { + repo := t.TempDir() + if err := os.Mkdir(filepath.Join(repo, "config"), 0755); err != nil { + t.Fatal(err) + } + got, err := ResolveWorkingSource(repo, "", &SourceSpec{Dir: "config"}) + if err != nil { + t.Fatal(err) + } + if got.ModuleSubdir != "config" || got.GoEnabled || got.Publication != "source" { + t.Fatalf("selection = %+v", got) + } + if err := os.Symlink("config", filepath.Join(repo, "alias")); err != nil { + t.Fatal(err) + } + if _, err := ResolveWorkingSource(repo, "alias", &SourceSpec{Dir: "config"}); err != nil { + t.Fatalf("matching physical directories: %v", err) + } + if _, err := ResolveWorkingSource(repo, ".", &SourceSpec{Dir: "config"}); err == nil { + t.Fatal("expected conflicting directories to fail") + } + if err := os.WriteFile(filepath.Join(repo, "file"), nil, 0600); err != nil { + t.Fatal(err) + } + if _, err := ResolveWorkingSource(repo, "", &SourceSpec{Dir: "file"}); err == nil { + t.Fatal("expected a file selection to fail") + } +} diff --git a/publish.go b/publish.go index 603b830..2e3c0f7 100644 --- a/publish.go +++ b/publish.go @@ -92,6 +92,7 @@ func Publish(ctx context.Context, request ReleaseRequest) (PublicationResult, er result, err := publish.Publish(ctx, publish.Request{ RepositoryDir: candidateInput.RepositoryDir, ModuleDir: candidateInput.ModuleDir, + Source: candidateInput.Source, Product: candidateInput.Product, Version: candidateInput.Version, Remote: request.Remote, diff --git a/source.go b/source.go new file mode 100644 index 0000000..e8ac4dd --- /dev/null +++ b/source.go @@ -0,0 +1,51 @@ +package releasekit + +import "go.maximumdirect.net/releasekit/internal/releaseidentity" + +// PublicationMode selects the distribution contract for a source release. +type PublicationMode string + +const ( + // PublicationSource selects a general source release. + PublicationSource PublicationMode = "source" + // PublicationGoModule selects Go module publication and requires GoEnabled. + PublicationGoModule PublicationMode = "go-module" +) + +// VersionFormat selects the grammar of a release identifier. +type VersionFormat string + +const ( + // VersionSemver selects stable semantic versions. + VersionSemver VersionFormat = "semver" + // VersionDate selects Gregorian dates with an optional revision. + VersionDate VersionFormat = "date" + // VersionYearMonth selects a year, month, and revision. + VersionYearMonth VersionFormat = "year-month" +) + +// SourceSpec explicitly selects a source scope and its release capabilities. +// An empty Dir selects ModuleDir if supplied, otherwise the repository root. +// A nil VersionPrefix selects the format default; a nil TagPrefix derives the +// source tag prefix from the physical source directory. +type SourceSpec struct { + Dir string // repository-relative source directory. + GoEnabled bool // select Go module validation and build capabilities. + // Publication defaults to PublicationSource for an explicit selection. + Publication PublicationMode + // VersionFormat defaults to VersionSemver. + VersionFormat VersionFormat + // VersionPrefix may be "v" or ""; nil uses the selected format's default. + VersionPrefix *string + TagPrefix *string // nil derives the prefix; a pointer to "" removes it. +} + +func internalSourceSpec(source *SourceSpec) *releaseidentity.SourceSpec { + if source == nil { + return nil + } + return &releaseidentity.SourceSpec{ + Dir: source.Dir, GoEnabled: source.GoEnabled, Publication: string(source.Publication), + VersionFormat: string(source.VersionFormat), VersionPrefix: source.VersionPrefix, TagPrefix: source.TagPrefix, + } +} diff --git a/source_test.go b/source_test.go new file mode 100644 index 0000000..b7f6b8a --- /dev/null +++ b/source_test.go @@ -0,0 +1,15 @@ +package releasekit + +import "testing" + +func TestCandidateRequestPreservesSourceSelection(t *testing.T) { + empty := "" + request := ReleaseRequest{Source: &SourceSpec{Dir: "app", GoEnabled: true, Publication: PublicationSource, VersionFormat: VersionDate, VersionPrefix: &empty, TagPrefix: &empty}} + selection := candidateRequest(request).Source + if selection == nil || selection.Dir != "app" || !selection.GoEnabled || selection.Publication != "source" || selection.VersionFormat != "date" || selection.VersionPrefix == nil || *selection.VersionPrefix != "" || selection.TagPrefix == nil || *selection.TagPrefix != "" { + t.Fatalf("source selection = %+v", selection) + } + if candidateRequest(ReleaseRequest{}).Source != nil { + t.Fatal("legacy module shorthand became an explicit selection") + } +}