Release/1.0 #1

Merged
k3nny merged 19 commits from release/1.0 into main 2026-07-11 22:11:21 +02:00
14 changed files with 558 additions and 21 deletions
Showing only changes of commit dfdf2b019a - Show all commits
+11
View File
@@ -50,6 +50,17 @@ git:
# - "packages/frontend/package.json" # - "packages/frontend/package.json"
# - "packages/backend/package.json" # - "packages/backend/package.json"
# gradle:
# Single build.gradle or build.gradle.kts path (opt-in — no default).
# Both Groovy DSL (single-quoted) and Kotlin DSL (double-quoted) are supported.
# build_file: "build.gradle"
# Multiple build files for multi-module projects (overrides build_file).
# build_files:
# - "build.gradle"
# - "module-a/build.gradle"
# - "module-b/build.gradle"
gitlab: gitlab:
# GitLab instance URL. Falls back to the CI_SERVER_URL environment variable. # GitLab instance URL. Falls back to the CI_SERVER_URL environment variable.
# url: "https://gitlab.example.com" # url: "https://gitlab.example.com"
+9
View File
@@ -3,6 +3,15 @@
All notable changes to this project will be documented in this file. All notable changes to this project will be documented in this file.
Format: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Format: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
## [1.6.0] - 2026-07-11
### Added
- **Gradle support** — new `internal/gradle` package; reads and writes the version assignment in `build.gradle` (Groovy DSL, single-quoted) and `build.gradle.kts` (Kotlin DSL, double-quoted); original quote style preserved on write; `regexp.QuoteMeta` ensures version strings with dots or special chars are safe
- **`gradle.build_file` / `gradle.build_files` config** — opt-in, no default; `build_files` list overrides `build_file` for multi-module projects; follows the same multi-value pattern as `maven.pom_paths` and `node.package_jsons`
- **`--gradle <path>` flag** — overrides `gradle.build_file` from config and clears `gradle.build_files`; mirrored in verbose config table as `gradle.paths`
- **`FuzzReadVersion` / `FuzzWriteVersion`** in `internal/gradle` — 100% per-package statement coverage maintained across all 13 packages
## [1.5.1] - 2026-07-11 ## [1.5.1] - 2026-07-11
### Added ### Added
+2 -1
View File
@@ -61,12 +61,13 @@ All seed cases must pass. The table below is authoritative — keep it in sync w
| `internal/branch` | `FuzzParse` | parses branch name strings | | `internal/branch` | `FuzzParse` | parses branch name strings |
| `internal/changelog` | `FuzzUpdate` | rewrites arbitrary existing file content | | `internal/changelog` | `FuzzUpdate` | rewrites arbitrary existing file content |
| `internal/commits` | `FuzzParse` | parses arbitrary commit message strings | | `internal/commits` | `FuzzParse` | parses arbitrary commit message strings |
| `internal/gradle` | `FuzzReadVersion`, `FuzzWriteVersion` | reads/rewrites arbitrary Gradle build file content |
| `internal/glclient` | `FuzzEncodeProjectPath` | encodes arbitrary project path strings | | `internal/glclient` | `FuzzEncodeProjectPath` | encodes arbitrary project path strings |
| `internal/maven` | `FuzzReadVersion`, `FuzzReplaceProjectVersion` | reads/rewrites arbitrary XML file content | | `internal/maven` | `FuzzReadVersion`, `FuzzReplaceProjectVersion` | reads/rewrites arbitrary XML file content |
| `internal/node` | `FuzzReadVersion`, `FuzzWriteVersion` | reads/rewrites arbitrary JSON file content | | `internal/node` | `FuzzReadVersion`, `FuzzWriteVersion` | reads/rewrites arbitrary JSON file content |
| `internal/notes` | `FuzzGenerate` | generates notes from arbitrary commit messages | | `internal/notes` | `FuzzGenerate` | generates notes from arbitrary commit messages |
Packages **not** requiring fuzz tests (no free-form text parsing): `internal/config` (yaml.v3 handles parsing), `internal/ghclient` (HTTP client, no text parsing), `internal/gitutil` (git operations), `internal/version` (typed inputs only), `cmd` (CLI orchestration). Packages **not** requiring fuzz tests (no free-form text parsing): `internal/config` (yaml.v3 handles parsing), `internal/ghclient` (HTTP client, no text parsing), `internal/gitutil` (git operations), `internal/version` (typed inputs only), `cmd` (CLI orchestration). When adding a new package, check whether it parses text or rewrites files — if yes, add a row above.
Fuzz seed corpus guidelines: Fuzz seed corpus guidelines:
- Include a realistic happy-path input as the first seed. - Include a realistic happy-path input as the first seed.
+8 -2
View File
@@ -1,6 +1,6 @@
# releaser # releaser
![release](https://img.shields.io/badge/release-v1.5.1-blue.svg) ![release](https://img.shields.io/badge/release-v1.6.0-blue.svg)
A CI-friendly release automation tool for GitFlow workflows using Conventional Commits. A CI-friendly release automation tool for GitFlow workflows using Conventional Commits.
@@ -23,7 +23,7 @@ release/1.2 branch
2. **Tag discovery** — finds the latest tag matching `major.minor.*` on the current branch 2. **Tag discovery** — finds the latest tag matching `major.minor.*` on the current branch
3. **Commit analysis** — parses Conventional Commits between last tag and HEAD 3. **Commit analysis** — parses Conventional Commits between last tag and HEAD
4. **Version bump** — increments patch (the minor is owned by the branch) 4. **Version bump** — increments patch (the minor is owned by the branch)
5. **Release** — updates `pom.xml`, commits, tags, creates GitLab or GitHub release 5. **Release** — updates `pom.xml` / `package.json` / `build.gradle`, commits, tags, creates GitLab or GitHub release
## Version bump rules ## Version bump rules
@@ -115,6 +115,12 @@ node: # opt-in — no default; om
# - "packages/frontend/package.json" # - "packages/frontend/package.json"
# - "packages/backend/package.json" # - "packages/backend/package.json"
gradle: # opt-in — no default; omit to skip
# build_file: "build.gradle" # Groovy or Kotlin DSL; single path
# build_files: # multi-module: list overrides build_file
# - "build.gradle"
# - "module-a/build.gradle"
gitlab: gitlab:
url: "https://gitlab.example.com" # or env CI_SERVER_URL url: "https://gitlab.example.com" # or env CI_SERVER_URL
token: "" # env GITLAB_TOKEN (never commit this) token: "" # env GITLAB_TOKEN (never commit this)
+1 -1
View File
@@ -85,5 +85,5 @@
## Future / backlog ## Future / backlog
- Gradle support (`build.gradle` / `build.gradle.kts`) - ~~Gradle support (`build.gradle` / `build.gradle.kts`)~~ — ✓ shipped v1.6.0 (`internal/gradle`; Groovy + Kotlin DSL; multi-module via `gradle.build_files`; `--gradle` flag)
- Slack / Teams notification on release - Slack / Teams notification on release
+58 -16
View File
@@ -18,6 +18,7 @@ import (
"git.k3nny.fr/releaser/internal/ghclient" "git.k3nny.fr/releaser/internal/ghclient"
"git.k3nny.fr/releaser/internal/gitutil" "git.k3nny.fr/releaser/internal/gitutil"
"git.k3nny.fr/releaser/internal/glclient" "git.k3nny.fr/releaser/internal/glclient"
"git.k3nny.fr/releaser/internal/gradle"
"git.k3nny.fr/releaser/internal/maven" "git.k3nny.fr/releaser/internal/maven"
"git.k3nny.fr/releaser/internal/node" "git.k3nny.fr/releaser/internal/node"
"git.k3nny.fr/releaser/internal/notes" "git.k3nny.fr/releaser/internal/notes"
@@ -78,6 +79,17 @@ node:
# - "packages/frontend/package.json" # - "packages/frontend/package.json"
# - "packages/backend/package.json" # - "packages/backend/package.json"
gradle:
# Single build.gradle or build.gradle.kts path (opt-in — no default).
# Both Groovy DSL (single-quoted) and Kotlin DSL (double-quoted) are supported.
# build_file: "build.gradle"
# Multiple build files for multi-module projects (overrides build_file).
# build_files:
# - "build.gradle"
# - "module-a/build.gradle"
# - "module-b/build.gradle"
gitlab: gitlab:
# GitLab instance URL. Falls back to the CI_SERVER_URL environment variable. # GitLab instance URL. Falls back to the CI_SERVER_URL environment variable.
# url: "https://gitlab.example.com" # url: "https://gitlab.example.com"
@@ -149,6 +161,7 @@ func newRootCmd() *cobra.Command {
branchOverride string branchOverride string
repoPath string repoPath string
pomOverride string pomOverride string
gradleOverride string
changelogFile string changelogFile string
tagPrefixFlag string tagPrefixFlag string
tagPrefixSet bool tagPrefixSet bool
@@ -171,6 +184,7 @@ func newRootCmd() *cobra.Command {
repoPath: repoPath, repoPath: repoPath,
branchOverride: branchOverride, branchOverride: branchOverride,
pomOverride: pomOverride, pomOverride: pomOverride,
gradleOverride: gradleOverride,
changelogFile: changelogFile, changelogFile: changelogFile,
tagPrefixFlag: tagPrefixFlag, tagPrefixFlag: tagPrefixFlag,
tagPrefixSet: tagPrefixSet, tagPrefixSet: tagPrefixSet,
@@ -196,6 +210,7 @@ func newRootCmd() *cobra.Command {
root.Flags().StringVar(&branchOverride, "branch", "", "override branch name detection (required in detached HEAD)") root.Flags().StringVar(&branchOverride, "branch", "", "override branch name detection (required in detached HEAD)")
root.Flags().StringVar(&repoPath, "repo", ".", "path to git repository") root.Flags().StringVar(&repoPath, "repo", ".", "path to git repository")
root.Flags().StringVar(&pomOverride, "pom", "", "override maven.pom_path from config") root.Flags().StringVar(&pomOverride, "pom", "", "override maven.pom_path from config")
root.Flags().StringVar(&gradleOverride, "gradle", "", "override gradle.build_file from config")
root.Flags().StringVar(&changelogFile, "changelog-file", "CHANGELOG.md", "path to changelog file relative to repo root") root.Flags().StringVar(&changelogFile, "changelog-file", "CHANGELOG.md", "path to changelog file relative to repo root")
root.Flags().StringVar(&tagPrefixFlag, "tag-prefix", "", "override git.tag_prefix from config") root.Flags().StringVar(&tagPrefixFlag, "tag-prefix", "", "override git.tag_prefix from config")
root.Flags().StringVar(&patternFlag, "branch-pattern", "", "override git.branch_pattern from config") root.Flags().StringVar(&patternFlag, "branch-pattern", "", "override git.branch_pattern from config")
@@ -215,22 +230,23 @@ func main() {
} }
type options struct { type options struct {
init bool init bool
verbose bool verbose bool
repoPath string repoPath string
branchOverride string branchOverride string
pomOverride string pomOverride string
changelogFile string gradleOverride string
tagPrefixFlag string changelogFile string
tagPrefixSet bool tagPrefixFlag string
patternFlag string tagPrefixSet bool
patternSet bool patternFlag string
dryRun bool patternSet bool
noPush bool dryRun bool
noRelease bool noPush bool
noCommit bool noRelease bool
tagOnly bool noCommit bool
releaseEnvFile string tagOnly bool
releaseEnvFile string
} }
func printVerboseConfig(cfg config.Config, src config.Sources) { func printVerboseConfig(cfg config.Config, src config.Sources) {
@@ -273,6 +289,13 @@ func printVerboseConfig(cfg config.Config, src config.Sources) {
} }
return strings.Join(paths, ", ") return strings.Join(paths, ", ")
}()}, }()},
{"gradle.paths", func() string {
paths := cfg.Gradle.EffectiveBuildFiles()
if len(paths) == 0 {
return "(not configured)"
}
return strings.Join(paths, ", ")
}()},
{"gitlab.url", cfg.GitLab.URL}, {"gitlab.url", cfg.GitLab.URL},
{"gitlab.token", func() string { {"gitlab.token", func() string {
if cfg.GitLab.Token != "" { if cfg.GitLab.Token != "" {
@@ -360,6 +383,11 @@ func run(o options) error {
cfg.Maven.PomPaths = nil cfg.Maven.PomPaths = nil
src["maven.pom_paths"] = "flag: --pom" src["maven.pom_paths"] = "flag: --pom"
} }
if o.gradleOverride != "" {
cfg.Gradle.BuildFile = o.gradleOverride
cfg.Gradle.BuildFiles = nil
src["gradle.build_files"] = "flag: --gradle"
}
if o.patternSet { if o.patternSet {
cfg.Git.BranchPattern = o.patternFlag cfg.Git.BranchPattern = o.patternFlag
src["git.branch_pattern"] = "flag: --branch-pattern" src["git.branch_pattern"] = "flag: --branch-pattern"
@@ -552,6 +580,20 @@ func run(o options) error {
filesToCommit = append(filesToCommit, relPkgPath) filesToCommit = append(filesToCommit, relPkgPath)
} }
// build.gradle / build.gradle.kts (opt-in via gradle.build_file / gradle.build_files)
for _, relGradlePath := range cfg.Gradle.EffectiveBuildFiles() {
gradlePath := filepath.Join(absRepo, relGradlePath)
currentGradleVersion, err := gradle.ReadVersion(gradlePath)
if err != nil {
return fmt.Errorf("read gradle version: %w", err)
}
if err := gradle.WriteVersion(gradlePath, currentGradleVersion, nextVersion); err != nil {
return fmt.Errorf("update gradle version: %w", err)
}
logDone("%s: %s → %s", relGradlePath, currentGradleVersion, nextVersion)
filesToCommit = append(filesToCommit, relGradlePath)
}
// CHANGELOG.md // CHANGELOG.md
changelogAbsPath := filepath.Join(absRepo, o.changelogFile) changelogAbsPath := filepath.Join(absRepo, o.changelogFile)
if err := changelog.Update(changelogAbsPath, nextTag, nextVersion, messages); err != nil { if err := changelog.Update(changelogAbsPath, nextTag, nextVersion, messages); err != nil {
+116 -1
View File
@@ -1093,7 +1093,8 @@ func TestPrintVerboseConfigBumpRulesAndNode(t *testing.T) {
Git: config.GitConfig{ Git: config.GitConfig{
BumpRules: config.BumpRulesConfig{Breaking: "minor", Feat: "minor", Fix: "minor"}, BumpRules: config.BumpRulesConfig{Breaking: "minor", Feat: "minor", Fix: "minor"},
}, },
Node: config.NodeConfig{PackageJSON: "package.json"}, Node: config.NodeConfig{PackageJSON: "package.json"},
Gradle: config.GradleConfig{BuildFile: "build.gradle"},
} }
src := config.Sources{} src := config.Sources{}
@@ -1112,6 +1113,9 @@ func TestPrintVerboseConfigBumpRulesAndNode(t *testing.T) {
if !strings.Contains(output, "package.json") { if !strings.Contains(output, "package.json") {
t.Error("expected 'package.json' in output for node.paths") t.Error("expected 'package.json' in output for node.paths")
} }
if !strings.Contains(output, "build.gradle") {
t.Error("expected 'build.gradle' in output for gradle.paths")
}
} }
// ── node package.json handling ──────────────────────────────────────────────── // ── node package.json handling ────────────────────────────────────────────────
@@ -1200,3 +1204,114 @@ func TestRunNodeWriteVersionFails(t *testing.T) {
t.Fatal("expected error when package.json is read-only") t.Fatal("expected error when package.json is read-only")
} }
} }
// ── gradle build file handling ────────────────────────────────────────────────
func writeGradleFile(t *testing.T, dir, ver string) {
t.Helper()
content := fmt.Sprintf("group = \"com.example\"\nversion = \"%s\"\n", ver)
if err := os.WriteFile(filepath.Join(dir, "build.gradle"), []byte(content), 0644); err != nil {
t.Fatal(err)
}
}
func TestRunGradleVersionBump(t *testing.T) {
dir := t.TempDir()
repo, err := gogit.PlainInit(dir, false)
if err != nil {
t.Fatal(err)
}
writeGradleFile(t, dir, "0.0.0")
commitAll(t, repo, dir, "chore: init")
os.WriteFile(filepath.Join(dir, ".releaser.yml"), []byte("gradle:\n build_file: \"build.gradle\"\n"), 0644)
addFile(t, dir, "x.go", "// fix")
w, _ := repo.Worktree()
w.Add("x.go")
w.Commit("fix: something", &gogit.CommitOptions{Author: testSig()})
if err := execCmd(t, "--no-push", "--branch", "release/1.2", "--repo", dir); err != nil {
t.Fatalf("gradle version bump: unexpected error: %v", err)
}
data, _ := os.ReadFile(filepath.Join(dir, "build.gradle"))
if !strings.Contains(string(data), `version = "1.2.0"`) {
t.Errorf("expected version 1.2.0 in build.gradle, got: %s", data)
}
}
func TestRunGradleOverrideFlag(t *testing.T) {
dir := t.TempDir()
repo, err := gogit.PlainInit(dir, false)
if err != nil {
t.Fatal(err)
}
// Write gradle file at custom path
if err := os.MkdirAll(filepath.Join(dir, "sub"), 0755); err != nil {
t.Fatal(err)
}
content := "version = \"0.0.0\"\n"
os.WriteFile(filepath.Join(dir, "sub", "build.gradle"), []byte(content), 0644)
commitAll(t, repo, dir, "chore: init")
addFile(t, dir, "x.go", "// fix")
w, _ := repo.Worktree()
w.Add("x.go")
w.Commit("fix: something", &gogit.CommitOptions{Author: testSig()})
if err := execCmd(t, "--no-push", "--branch", "release/1.2", "--repo", dir, "--gradle", "sub/build.gradle"); err != nil {
t.Fatalf("--gradle flag: unexpected error: %v", err)
}
data, _ := os.ReadFile(filepath.Join(dir, "sub", "build.gradle"))
if !strings.Contains(string(data), `version = "1.2.0"`) {
t.Errorf("expected version 1.2.0, got: %s", data)
}
}
func TestRunGradleReadVersionFails(t *testing.T) {
dir := t.TempDir()
repo, err := gogit.PlainInit(dir, false)
if err != nil {
t.Fatal(err)
}
// build.gradle with no version assignment
os.WriteFile(filepath.Join(dir, "build.gradle"), []byte(`group = "com.example"`), 0644)
commitAll(t, repo, dir, "chore: init")
os.WriteFile(filepath.Join(dir, ".releaser.yml"), []byte("gradle:\n build_file: \"build.gradle\"\n"), 0644)
addFile(t, dir, "x.go", "// fix")
w, _ := repo.Worktree()
w.Add("x.go")
w.Commit("fix: something", &gogit.CommitOptions{Author: testSig()})
if err := execCmd(t, "--branch", "release/1.2", "--repo", dir); err == nil {
t.Fatal("expected error when build.gradle has no version assignment")
}
}
func TestRunGradleWriteVersionFails(t *testing.T) {
dir := t.TempDir()
repo, err := gogit.PlainInit(dir, false)
if err != nil {
t.Fatal(err)
}
writeGradleFile(t, dir, "0.0.0")
commitAll(t, repo, dir, "chore: init")
os.WriteFile(filepath.Join(dir, ".releaser.yml"), []byte("gradle:\n build_file: \"build.gradle\"\n"), 0644)
addFile(t, dir, "x.go", "// fix")
w, _ := repo.Worktree()
w.Add("x.go")
w.Commit("fix: something", &gogit.CommitOptions{Author: testSig()})
os.Chmod(filepath.Join(dir, "build.gradle"), 0444)
defer os.Chmod(filepath.Join(dir, "build.gradle"), 0644)
if err := execCmd(t, "--branch", "release/1.2", "--repo", dir); err == nil {
t.Fatal("expected error when build.gradle is read-only")
}
}
+17
View File
@@ -3,6 +3,23 @@ title: Changelog
weight: 50 weight: 50
--- ---
## v1.6.0 — 2026-07-11
### Added
- **Gradle support** — opt-in via `gradle.build_file` (single path) or `gradle.build_files` (list, overrides single); supports both Groovy DSL (`version = '1.2.3'`) and Kotlin DSL (`version = "1.2.3"`); original quote style preserved on write; `--gradle <path>` CLI flag for one-off overrides
## v1.5.1 — 2026-07-11
### Added
- **Documentation site** — Hugo + Geekdoc; installation, CLI reference, configuration, CI integration, and changelog pages; deployed to `gh-pages` via Gitea CI on push to `main`
- **`FuzzUpdate`** in `internal/changelog` and **`FuzzWriteVersion`** in `internal/node` — complete fuzz coverage for all file-rewriting packages
### Changed
- **CLAUDE.md** — fuzzing completeness guidelines with authoritative table
## v1.5.0 — 2026-07-11 ## v1.5.0 — 2026-07-11
### Added ### Added
+29
View File
@@ -45,6 +45,14 @@ node: # opt-in — omit section t
# - "packages/frontend/package.json" # - "packages/frontend/package.json"
# - "packages/backend/package.json" # - "packages/backend/package.json"
gradle: # opt-in — omit section to skip
# build_file: "build.gradle" # Groovy or Kotlin DSL; single path
# Multi-module: list overrides build_file.
# build_files:
# - "build.gradle"
# - "module-a/build.gradle"
gitlab: gitlab:
url: "https://gitlab.example.com" # or env CI_SERVER_URL url: "https://gitlab.example.com" # or env CI_SERVER_URL
token: "" # prefer env GITLAB_TOKEN token: "" # prefer env GITLAB_TOKEN
@@ -119,3 +127,24 @@ node:
- "packages/frontend/package.json" - "packages/frontend/package.json"
- "packages/backend/package.json" - "packages/backend/package.json"
``` ```
## Gradle support
The `gradle` section is opt-in — if omitted, no build file is touched. Both Groovy DSL (`version = '1.2.3'`) and Kotlin DSL (`version = "1.2.3"`) are supported; the original quote style is preserved on write.
```yaml
gradle:
build_file: "build.gradle"
```
Use `build_files` for multi-module projects:
```yaml
gradle:
build_files:
- "build.gradle"
- "module-a/build.gradle"
- "module-b/build.gradle"
```
The `--gradle <path>` CLI flag sets a single build file path and clears `build_files`.
+1
View File
@@ -39,6 +39,7 @@ releaser --verbose --dry-run
| `--branch-pattern <regex>` | `^(?:.*/)?release/(\d+)\.(\d+)$` | Override branch pattern (two capture groups: major, minor) | | `--branch-pattern <regex>` | `^(?:.*/)?release/(\d+)\.(\d+)$` | Override branch pattern (two capture groups: major, minor) |
| `--tag-prefix <prefix>` | `""` | Prefix for version tags (e.g. `v``v1.2.3`) | | `--tag-prefix <prefix>` | `""` | Prefix for version tags (e.g. `v``v1.2.3`) |
| `--pom <path>` | `pom.xml` | Path to pom.xml relative to repo root | | `--pom <path>` | `pom.xml` | Path to pom.xml relative to repo root |
| `--gradle <path>` | — | Override `gradle.build_file` from config |
| `--changelog-file <path>` | `CHANGELOG.md` | Path to changelog file | | `--changelog-file <path>` | `CHANGELOG.md` | Path to changelog file |
| `--release-env-file <path>` | `release.env` | Path for dotenv artifact; pass `""` to disable | | `--release-env-file <path>` | `release.env` | Path for dotenv artifact; pass `""` to disable |
| `--no-commit` | false | Update version files but stop before committing | | `--no-commit` | false | Update version files but stop before committing |
+26
View File
@@ -17,6 +17,7 @@ type Config struct {
Git GitConfig `yaml:"git"` Git GitConfig `yaml:"git"`
Maven MavenConfig `yaml:"maven"` Maven MavenConfig `yaml:"maven"`
Node NodeConfig `yaml:"node"` Node NodeConfig `yaml:"node"`
Gradle GradleConfig `yaml:"gradle"`
GitLab GitLabConfig `yaml:"gitlab"` GitLab GitLabConfig `yaml:"gitlab"`
GitHub GitHubConfig `yaml:"github"` GitHub GitHubConfig `yaml:"github"`
} }
@@ -73,6 +74,23 @@ func (n NodeConfig) EffectivePaths() []string {
return nil return nil
} }
type GradleConfig struct {
BuildFile string `yaml:"build_file"` // single path (opt-in, no default)
BuildFiles []string `yaml:"build_files"` // multiple paths; overrides BuildFile
}
// EffectiveBuildFiles returns the list of Gradle build file paths to process.
// Returns nil when no gradle paths are configured (gradle processing is opt-in).
func (g GradleConfig) EffectiveBuildFiles() []string {
if len(g.BuildFiles) > 0 {
return g.BuildFiles
}
if g.BuildFile != "" {
return []string{g.BuildFile}
}
return nil
}
type GitLabConfig struct { type GitLabConfig struct {
URL string `yaml:"url"` URL string `yaml:"url"`
Token string `yaml:"token"` Token string `yaml:"token"`
@@ -117,6 +135,8 @@ func defaultSources() Sources {
"maven.pom_paths": "default", "maven.pom_paths": "default",
"node.package_json": "default", "node.package_json": "default",
"node.package_jsons": "default", "node.package_jsons": "default",
"gradle.build_file": "default",
"gradle.build_files": "default",
"gitlab.url": "default", "gitlab.url": "default",
"gitlab.token": "default", "gitlab.token": "default",
"gitlab.project": "default", "gitlab.project": "default",
@@ -193,6 +213,12 @@ func LoadWithSources(dir string) (Config, Sources, error) {
if len(overlay.Node.PackageJSONs) > 0 { if len(overlay.Node.PackageJSONs) > 0 {
src["node.package_jsons"] = "config file" src["node.package_jsons"] = "config file"
} }
if overlay.Gradle.BuildFile != "" {
src["gradle.build_file"] = "config file"
}
if len(overlay.Gradle.BuildFiles) > 0 {
src["gradle.build_files"] = "config file"
}
if overlay.GitLab.URL != "" { if overlay.GitLab.URL != "" {
src["gitlab.url"] = "config file" src["gitlab.url"] = "config file"
} }
+46
View File
@@ -292,6 +292,52 @@ func TestApplyEnvWithSourcesCIServerURL(t *testing.T) {
} }
} }
func TestGradleEffectiveBuildFiles(t *testing.T) {
// Neither set → nil (opt-in)
if got := (GradleConfig{}).EffectiveBuildFiles(); got != nil {
t.Errorf("empty config: got %v, want nil", got)
}
// BuildFile only
if got := (GradleConfig{BuildFile: "build.gradle"}).EffectiveBuildFiles(); len(got) != 1 || got[0] != "build.gradle" {
t.Errorf("BuildFile only: got %v", got)
}
// BuildFiles wins over BuildFile
g := GradleConfig{BuildFile: "build.gradle", BuildFiles: []string{"a/build.gradle", "b/build.gradle"}}
if got := g.EffectiveBuildFiles(); len(got) != 2 || got[0] != "a/build.gradle" {
t.Errorf("BuildFiles priority: got %v", got)
}
}
func TestLoadGradleSources(t *testing.T) {
dir := t.TempDir()
content := "gradle:\n build_file: \"build.gradle\"\n"
if err := os.WriteFile(filepath.Join(dir, filename), []byte(content), 0644); err != nil {
t.Fatal(err)
}
_, src, err := LoadWithSources(dir)
if err != nil {
t.Fatal(err)
}
if src["gradle.build_file"] != "config file" {
t.Errorf("src[gradle.build_file] = %q, want %q", src["gradle.build_file"], "config file")
}
}
func TestLoadGradleBuildFilesSources(t *testing.T) {
dir := t.TempDir()
content := "gradle:\n build_files:\n - \"a/build.gradle\"\n - \"b/build.gradle\"\n"
if err := os.WriteFile(filepath.Join(dir, filename), []byte(content), 0644); err != nil {
t.Fatal(err)
}
_, src, err := LoadWithSources(dir)
if err != nil {
t.Fatal(err)
}
if src["gradle.build_files"] != "config file" {
t.Errorf("src[gradle.build_files] = %q, want %q", src["gradle.build_files"], "config file")
}
}
func TestLoadPartialOverride(t *testing.T) { func TestLoadPartialOverride(t *testing.T) {
dir := t.TempDir() dir := t.TempDir()
// Only override tag_prefix — commit_message should keep its default // Only override tag_prefix — commit_message should keep its default
+54
View File
@@ -0,0 +1,54 @@
package gradle
import (
"fmt"
"os"
"regexp"
)
// versionRe matches a Gradle/Kotlin DSL version assignment on its own line.
// Group 1 captures the version string (without quotes).
// Handles both double-quoted (Kotlin/Groovy) and single-quoted (Groovy) forms,
// with or without spaces around =.
var versionRe = regexp.MustCompile(`(?m)^[ \t]*version\s*=\s*["']([^"']+)["']`)
// ReadVersion returns the version value from a build.gradle or build.gradle.kts file.
func ReadVersion(path string) (string, error) {
data, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("read %s: %w", path, err)
}
m := versionRe.FindStringSubmatch(string(data))
if m == nil {
return "", fmt.Errorf("no version assignment found in %s", path)
}
return m[1], nil
}
// WriteVersion replaces the version assignment in a build.gradle or build.gradle.kts
// file in-place. oldVersion must match what ReadVersion returned. Quote style is preserved.
func WriteVersion(path, oldVersion, newVersion string) error {
data, err := os.ReadFile(path)
if err != nil {
return fmt.Errorf("read %s: %w", path, err)
}
updated, ok := replaceVersion(string(data), oldVersion, newVersion)
if !ok {
return fmt.Errorf("version %q not found in %s", oldVersion, path)
}
return os.WriteFile(path, []byte(updated), 0644)
}
// replaceVersion finds and replaces the first version assignment line in a Gradle build file.
// Quote style (single or double) of the original line is preserved.
// Returns the updated content and true if a replacement was made.
func replaceVersion(content, oldVersion, newVersion string) (string, bool) {
re := regexp.MustCompile(`(?m)^([ \t]*version\s*=\s*)(["'])` + regexp.QuoteMeta(oldVersion) + `["']`)
m := re.FindStringSubmatchIndex(content)
if m == nil {
return content, false
}
prefix := content[m[2]:m[3]] // "version = " etc., preserving whitespace
quote := content[m[4]:m[5]] // " or '
return content[:m[0]] + prefix + quote + newVersion + quote + content[m[1]:], true
}
+180
View File
@@ -0,0 +1,180 @@
package gradle
import (
"os"
"path/filepath"
"strings"
"testing"
)
const gradleGroovy = `plugins {
id 'java'
}
group = 'com.example'
version = '1.2.3'
description = 'My project'
`
const gradleKotlin = `plugins {
kotlin("jvm") version "1.9.0"
}
group = "com.example"
version = "1.2.3"
description = "My project"
`
func writeGradle(t *testing.T, content string) string {
t.Helper()
path := filepath.Join(t.TempDir(), "build.gradle")
if err := os.WriteFile(path, []byte(content), 0644); err != nil {
t.Fatal(err)
}
return path
}
// ── ReadVersion ──────────────────────────────────────────────────────────────
func TestReadVersionGroovy(t *testing.T) {
got, err := ReadVersion(writeGradle(t, gradleGroovy))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got != "1.2.3" {
t.Errorf("got %q, want 1.2.3", got)
}
}
func TestReadVersionKotlin(t *testing.T) {
got, err := ReadVersion(writeGradle(t, gradleKotlin))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got != "1.2.3" {
t.Errorf("got %q, want 1.2.3", got)
}
}
func TestReadVersionNoSpaces(t *testing.T) {
got, err := ReadVersion(writeGradle(t, `version="1.0.0"`))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got != "1.0.0" {
t.Errorf("got %q, want 1.0.0", got)
}
}
func TestReadVersionMissingFile(t *testing.T) {
_, err := ReadVersion(filepath.Join(t.TempDir(), "build.gradle"))
if err == nil {
t.Error("expected error for missing file")
}
}
func TestReadVersionNoVersionField(t *testing.T) {
_, err := ReadVersion(writeGradle(t, `group = "com.example"`))
if err == nil {
t.Error("expected error when no version assignment is present")
}
}
// ── WriteVersion ─────────────────────────────────────────────────────────────
func TestWriteVersionKotlin(t *testing.T) {
path := writeGradle(t, gradleKotlin)
if err := WriteVersion(path, "1.2.3", "1.2.4"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
data, _ := os.ReadFile(path)
if !strings.Contains(string(data), `version = "1.2.4"`) {
t.Errorf("expected updated version; got:\n%s", data)
}
// plugin version declaration must not be touched
if !strings.Contains(string(data), `kotlin("jvm") version "1.9.0"`) {
t.Error("plugin version was incorrectly modified")
}
}
func TestWriteVersionGroovy(t *testing.T) {
path := writeGradle(t, gradleGroovy)
if err := WriteVersion(path, "1.2.3", "1.2.4"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
data, _ := os.ReadFile(path)
if !strings.Contains(string(data), `version = '1.2.4'`) {
t.Errorf("expected updated version with single quotes; got:\n%s", data)
}
}
func TestWriteVersionMissingFile(t *testing.T) {
err := WriteVersion(filepath.Join(t.TempDir(), "build.gradle"), "1.0.0", "1.0.1")
if err == nil {
t.Error("expected error for missing file")
}
}
func TestWriteVersionNotFound(t *testing.T) {
path := writeGradle(t, gradleKotlin)
err := WriteVersion(path, "9.9.9", "9.9.10")
if err == nil {
t.Error("expected error when old version not found in file")
}
}
func TestWriteVersionReadOnly(t *testing.T) {
path := writeGradle(t, gradleKotlin)
os.Chmod(path, 0444)
defer os.Chmod(path, 0644)
err := WriteVersion(path, "1.2.3", "1.2.4")
if err == nil {
t.Error("expected error writing to read-only file")
}
}
// ── replaceVersion ────────────────────────────────────────────────────────────
func TestReplaceVersionNotFound(t *testing.T) {
content := `group = "com.example"`
got, ok := replaceVersion(content, "1.0.0", "1.0.1")
if ok {
t.Error("expected ok=false when version not present")
}
if got != content {
t.Error("content should be unchanged when not found")
}
}
// ── fuzz ──────────────────────────────────────────────────────────────────────
// FuzzReadVersion verifies ReadVersion never panics on arbitrary file content.
func FuzzReadVersion(f *testing.F) {
f.Add(gradleGroovy)
f.Add(gradleKotlin)
f.Add(`version="1.0.0"`)
f.Add(`group = "com.example"`)
f.Add("")
f.Add("\x00\xff")
f.Fuzz(func(t *testing.T, content string) {
path := filepath.Join(t.TempDir(), "build.gradle")
os.WriteFile(path, []byte(content), 0644) //nolint:errcheck
ReadVersion(path) //nolint:errcheck
})
}
// FuzzWriteVersion verifies WriteVersion never panics on arbitrary content or version strings.
func FuzzWriteVersion(f *testing.F) {
f.Add(gradleGroovy, "1.2.3", "1.2.4")
f.Add(gradleKotlin, "1.2.3", "1.2.4")
f.Add(`version="1.0.0"`, "1.0.0", "1.0.1")
f.Add("", "1.0.0", "1.0.1")
f.Add(`version = "1.0.0"`, "", "1.0.1")
f.Fuzz(func(t *testing.T, content, oldVersion, newVersion string) {
path := filepath.Join(t.TempDir(), "build.gradle")
os.WriteFile(path, []byte(content), 0644) //nolint:errcheck
WriteVersion(path, oldVersion, newVersion) //nolint:errcheck
})
}