Skip to content

Commit ba4a751

Browse files
committed
cmd: introduce command for bumping modules in controller repos
Signed-off-by: Matheus Pimenta <matheuscscp@gmail.com>
1 parent b1df0c1 commit ba4a751

5 files changed

Lines changed: 434 additions & 63 deletions

File tree

Makefile

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,11 @@ prep-ci: flux-tools
154154
release: flux-tools
155155
@./bin/flux-tools pkg release
156156

157+
# Bump fluxcd/pkg dependencies in the current repository.
158+
.PHONY: bump
159+
bump: flux-tools
160+
@./bin/flux-tools bump
161+
157162
# Build the flux-tools binary.
158163
.PHONY: flux-tools
159164
flux-tools:

cmd/cli/bump.go

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/*
2+
Copyright 2026 The Flux authors
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package main
18+
19+
import (
20+
"fmt"
21+
"os"
22+
"os/exec"
23+
24+
"github.com/spf13/cobra"
25+
26+
"github.com/fluxcd/pkg/cmd/internal"
27+
)
28+
29+
var bumpCmd = &cobra.Command{
30+
Use: "bump",
31+
Short: "Bump fluxcd/pkg dependencies in the current repository's go.mod",
32+
RunE: runBump,
33+
}
34+
35+
var bumpCmdFlags struct {
36+
repoPath string
37+
}
38+
39+
func init() {
40+
rootCmd.AddCommand(bumpCmd)
41+
42+
bumpCmd.Flags().StringVar(&bumpCmdFlags.repoPath, "repo-path", "../target",
43+
"Path to the target repository.")
44+
}
45+
46+
func runBump(cmd *cobra.Command, args []string) error {
47+
ctx := setupSignalHandler()
48+
49+
res, err := internal.BumpDeps(ctx, bumpCmdFlags.repoPath)
50+
if err != nil {
51+
return fmt.Errorf("failed to bump dependencies: %w", err)
52+
}
53+
res.PrintSummary()
54+
55+
if res.NothingToUpdate() {
56+
return nil
57+
}
58+
59+
// Show git status to the user.
60+
gitStatus := exec.CommandContext(ctx, "git", "status")
61+
gitStatus.Stdout = os.Stdout
62+
gitStatus.Stderr = os.Stderr
63+
return gitStatus.Run()
64+
}

cmd/internal/bump_deps.go

Lines changed: 267 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,267 @@
1+
/*
2+
Copyright 2026 The Flux authors
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package internal
18+
19+
import (
20+
"context"
21+
"fmt"
22+
"os"
23+
"os/exec"
24+
"regexp"
25+
"strconv"
26+
"strings"
27+
28+
"github.com/go-git/go-git/v5"
29+
"github.com/go-git/go-git/v5/plumbing"
30+
"github.com/go-git/go-git/v5/storage/memory"
31+
)
32+
33+
// Baseline: controller minor versions at flux 2.7.
34+
// For each flux2 minor bump, all controller minors increase by 1.
35+
// Every time a new controller is added, this baseline should be
36+
// updated to the flux2 minor at which it was added.
37+
const baselineFluxMinor = 7
38+
39+
var controllerBaselineMinor = map[string]int{
40+
// the distro itself
41+
"flux2": baselineFluxMinor, // 2.7
42+
43+
// controllers
44+
"source-controller": 7, // 1.7
45+
"kustomize-controller": 7, // 1.7
46+
"helm-controller": 4, // 1.4
47+
"notification-controller": 7, // 1.7
48+
"image-reflector-controller": 0, // 1.0
49+
"image-automation-controller": 0, // 1.0
50+
"source-watcher": 0, // 2.0
51+
}
52+
53+
const pkgRepoURL = "https://github.com/fluxcd/pkg.git"
54+
55+
// depUpdate represents a single dependency version change.
56+
type depUpdate struct {
57+
module string
58+
oldVersion string
59+
newVersion string
60+
}
61+
62+
// BumpResult holds the outcome of a BumpDeps operation.
63+
type BumpResult struct {
64+
pkgBranch string
65+
updates []depUpdate
66+
}
67+
68+
// NothingToUpdate reports whether there are no dependency updates.
69+
func (r *BumpResult) NothingToUpdate() bool {
70+
return len(r.updates) == 0
71+
}
72+
73+
// PrintSummary prints a human-readable summary of the bump result.
74+
func (r *BumpResult) PrintSummary() {
75+
fmt.Printf("pkg branch: %s\n", r.pkgBranch)
76+
if r.NothingToUpdate() {
77+
fmt.Println("All fluxcd/pkg dependencies are up to date.")
78+
return
79+
}
80+
fmt.Println("Updates:")
81+
for _, u := range r.updates {
82+
fmt.Printf(" github.com/fluxcd/pkg/%s: %s => %s\n", u.module, u.oldVersion, u.newVersion)
83+
}
84+
}
85+
86+
// BumpDeps detects the current branch, maps it to the corresponding
87+
// fluxcd/pkg branch, fetches the latest module versions from that branch,
88+
// and updates go.mod accordingly.
89+
func BumpDeps(ctx context.Context, repoPath string) (*BumpResult, error) {
90+
localBranch, err := detectLocalBranch(repoPath)
91+
if err != nil {
92+
return nil, err
93+
}
94+
fmt.Println("Local branch:", localBranch)
95+
96+
controllerName, err := detectControllerName(repoPath)
97+
if err != nil {
98+
return nil, err
99+
}
100+
fmt.Println("Controller:", controllerName)
101+
102+
pkgBranch, err := mapToPkgBranch(localBranch, controllerName)
103+
if err != nil {
104+
return nil, err
105+
}
106+
fmt.Println("pkg branch:", pkgBranch)
107+
108+
latestVersions, err := fetchLatestVersions(ctx, pkgBranch)
109+
if err != nil {
110+
return nil, fmt.Errorf("failed to fetch latest versions from pkg branch %s: %w", pkgBranch, err)
111+
}
112+
113+
updates, err := updateGoMod(ctx, repoPath, latestVersions)
114+
if err != nil {
115+
return nil, fmt.Errorf("failed to update go.mod: %w", err)
116+
}
117+
118+
return &BumpResult{
119+
pkgBranch: pkgBranch,
120+
updates: updates,
121+
}, nil
122+
}
123+
124+
// detectLocalBranch opens the current directory as a git repo and returns the branch name.
125+
func detectLocalBranch(repoPath string) (string, error) {
126+
repo, err := git.PlainOpen(repoPath)
127+
if err != nil {
128+
return "", fmt.Errorf("failed to open repository: %w", err)
129+
}
130+
headRef, err := repo.Head()
131+
if err != nil {
132+
return "", fmt.Errorf("failed to get HEAD reference: %w", err)
133+
}
134+
if !headRef.Name().IsBranch() {
135+
return "", fmt.Errorf("HEAD is not a branch")
136+
}
137+
return headRef.Name().Short(), nil
138+
}
139+
140+
// gomodModuleRegex extracts the module path from a go.mod file.
141+
var gomodModuleRegex = regexp.MustCompile(`(?m)^module\s+(\S+)`)
142+
143+
// detectControllerName reads the target repo's go.mod and extracts the
144+
// controller name (e.g. "helm-controller") from the module path.
145+
func detectControllerName(repoPath string) (string, error) {
146+
gomod := fmt.Sprintf("%s/go.mod", repoPath)
147+
b, err := os.ReadFile(gomod)
148+
if err != nil {
149+
return "", fmt.Errorf("failed to read %s: %w", gomod, err)
150+
}
151+
m := gomodModuleRegex.FindStringSubmatch(string(b))
152+
if m == nil {
153+
return "", fmt.Errorf("failed to find module path in %s", gomod)
154+
}
155+
modulePath := m[1]
156+
// Strip version suffix (e.g. "github.com/fluxcd/flux2/v2" → "github.com/fluxcd/flux2").
157+
if idx := strings.LastIndex(modulePath, "/v"); idx >= 0 {
158+
if _, err := strconv.Atoi(modulePath[idx+2:]); err == nil {
159+
modulePath = modulePath[:idx]
160+
}
161+
}
162+
// Extract the last path component (e.g. "github.com/fluxcd/helm-controller" → "helm-controller").
163+
name := modulePath[strings.LastIndex(modulePath, "/")+1:]
164+
return name, nil
165+
}
166+
167+
// releaseBranchRegex matches branch names like "release/v1.5.x" or "release/v2.3.x".
168+
var releaseBranchRegex = regexp.MustCompile(`^release/v\d+\.(\d+)\.x$`)
169+
170+
// mapToPkgBranch maps a caller repo branch to the corresponding fluxcd/pkg branch
171+
// using the controller's baseline minor version offset.
172+
func mapToPkgBranch(branch, controllerName string) (string, error) {
173+
if branch == "main" {
174+
return "main", nil
175+
}
176+
m := releaseBranchRegex.FindStringSubmatch(branch)
177+
if m == nil {
178+
fmt.Printf("Warning: branch %q does not match expected patterns, defaulting to main\n", branch)
179+
return "main", nil
180+
}
181+
branchMinor, _ := strconv.Atoi(m[1])
182+
baseline, ok := controllerBaselineMinor[controllerName]
183+
if !ok {
184+
return "", fmt.Errorf("unknown controller %q: not in baseline mapping", controllerName)
185+
}
186+
fluxMinor := baselineFluxMinor + (branchMinor - baseline)
187+
return fmt.Sprintf("flux/v2.%d.x", fluxMinor), nil
188+
}
189+
190+
// fetchLatestVersions clones the pkg repo in memory for the given branch
191+
// and returns a map of module name to latest version tag (e.g. "auth" → "v0.5.0").
192+
func fetchLatestVersions(ctx context.Context, pkgBranch string) (map[string]string, error) {
193+
fmt.Printf("Cloning %s (branch %s) ...\n", pkgRepoURL, pkgBranch)
194+
repo, err := git.CloneContext(ctx, memory.NewStorage(), nil, &git.CloneOptions{
195+
URL: pkgRepoURL,
196+
ReferenceName: plumbing.NewBranchReferenceName(pkgBranch),
197+
SingleBranch: true,
198+
Tags: git.AllTags,
199+
})
200+
if err != nil {
201+
return nil, fmt.Errorf("failed to clone pkg repo: %w", err)
202+
}
203+
204+
headRef, err := repo.Head()
205+
if err != nil {
206+
return nil, fmt.Errorf("failed to get HEAD reference: %w", err)
207+
}
208+
209+
moduleLatest, err := collectLatestReachableTags(repo, headRef.Hash())
210+
if err != nil {
211+
return nil, fmt.Errorf("failed to collect latest reachable tags: %w", err)
212+
}
213+
214+
// Convert *semver.Version to "v<version>" strings.
215+
latestVersions := make(map[string]string, len(moduleLatest))
216+
for module, v := range moduleLatest {
217+
latestVersions[module] = "v" + v.String()
218+
}
219+
return latestVersions, nil
220+
}
221+
222+
// gomodPkgDepRegex matches lines like: github.com/fluxcd/pkg/runtime v1.2.0
223+
var gomodPkgDepRegex = regexp.MustCompile(`(github\.com/fluxcd/pkg/(\S+))\s+(v\S+)`)
224+
225+
// updateGoMod reads go.mod, replaces fluxcd/pkg dependency versions with the
226+
// latest ones, writes go.mod back (unless dry-run), and runs go mod tidy.
227+
func updateGoMod(ctx context.Context, repoPath string, latestVersions map[string]string) ([]depUpdate, error) {
228+
gomod := fmt.Sprintf("%s/go.mod", repoPath)
229+
b, err := os.ReadFile(gomod)
230+
if err != nil {
231+
return nil, fmt.Errorf("failed to read %s: %w", gomod, err)
232+
}
233+
oldContent := string(b)
234+
235+
var updates []depUpdate
236+
newContent := gomodPkgDepRegex.ReplaceAllStringFunc(oldContent, func(match string) string {
237+
sub := gomodPkgDepRegex.FindStringSubmatch(match)
238+
// sub[1] = full module path, sub[2] = module name, sub[3] = current version
239+
module := sub[2]
240+
oldVersion := sub[3]
241+
newVersion, ok := latestVersions[module]
242+
if !ok || newVersion == oldVersion {
243+
return match
244+
}
245+
updates = append(updates, depUpdate{
246+
module: module,
247+
oldVersion: oldVersion,
248+
newVersion: newVersion,
249+
})
250+
return sub[1] + " " + newVersion
251+
})
252+
253+
if len(updates) == 0 {
254+
return updates, nil
255+
}
256+
257+
if err := os.WriteFile(gomod, []byte(newContent), 0644); err != nil {
258+
return nil, fmt.Errorf("failed to write %s: %w", gomod, err)
259+
}
260+
gomodtidy := exec.CommandContext(ctx, "go", "mod", "tidy")
261+
gomodtidy.Dir = repoPath
262+
out, err := gomodtidy.CombinedOutput()
263+
if err != nil {
264+
return nil, fmt.Errorf("failed to run go mod tidy: %w\n%s", err, string(out))
265+
}
266+
return updates, nil
267+
}

0 commit comments

Comments
 (0)