Skip to content

Commit dee8529

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

4 files changed

Lines changed: 438 additions & 63 deletions

File tree

cmd/cli/bump.go

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
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+
preReleasePkg bool
37+
}
38+
39+
func init() {
40+
rootCmd.AddCommand(bumpCmd)
41+
42+
bumpCmd.Flags().BoolVar(&bumpCmdFlags.preReleasePkg, "pre-release-pkg", false,
43+
"Temporary flag for Flux 2.8: use the flux/v2.8.x pkg branch for main branches "+
44+
"because the pkg release branch was cut before the Flux distribution release. "+
45+
"Remove this flag once Flux 2.8.0 is released.")
46+
}
47+
48+
func runBump(cmd *cobra.Command, args []string) error {
49+
ctx := setupSignalHandler()
50+
51+
res, err := internal.BumpDeps(ctx, ".", bumpCmdFlags.preReleasePkg)
52+
if err != nil {
53+
return fmt.Errorf("failed to bump dependencies: %w", err)
54+
}
55+
res.PrintSummary()
56+
57+
if res.NothingToUpdate() {
58+
return nil
59+
}
60+
61+
// Show git status to the user.
62+
gitStatus := exec.CommandContext(ctx, "git", "status")
63+
gitStatus.Stdout = os.Stdout
64+
gitStatus.Stderr = os.Stderr
65+
return gitStatus.Run()
66+
}

cmd/internal/bump_deps.go

Lines changed: 274 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,274 @@
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. When preReleasePkg is true, main branches
89+
// use flux/v2.8.x instead of main (temporary workaround for Flux 2.8).
90+
func BumpDeps(ctx context.Context, repoPath string, preReleasePkg bool) (*BumpResult, error) {
91+
localBranch, err := detectLocalBranch(repoPath)
92+
if err != nil {
93+
return nil, err
94+
}
95+
fmt.Println("Local branch:", localBranch)
96+
97+
controllerName, err := detectControllerName(repoPath)
98+
if err != nil {
99+
return nil, err
100+
}
101+
fmt.Println("Controller:", controllerName)
102+
103+
pkgBranch, err := mapToPkgBranch(localBranch, controllerName, preReleasePkg)
104+
if err != nil {
105+
return nil, err
106+
}
107+
fmt.Println("pkg branch:", pkgBranch)
108+
109+
latestVersions, err := fetchLatestVersions(ctx, pkgBranch)
110+
if err != nil {
111+
return nil, fmt.Errorf("failed to fetch latest versions from pkg branch %s: %w", pkgBranch, err)
112+
}
113+
114+
updates, err := updateGoMod(ctx, repoPath, latestVersions)
115+
if err != nil {
116+
return nil, fmt.Errorf("failed to update go.mod: %w", err)
117+
}
118+
119+
return &BumpResult{
120+
pkgBranch: pkgBranch,
121+
updates: updates,
122+
}, nil
123+
}
124+
125+
// detectLocalBranch opens the current directory as a git repo and returns the branch name.
126+
func detectLocalBranch(repoPath string) (string, error) {
127+
repo, err := git.PlainOpen(repoPath)
128+
if err != nil {
129+
return "", fmt.Errorf("failed to open repository: %w", err)
130+
}
131+
headRef, err := repo.Head()
132+
if err != nil {
133+
return "", fmt.Errorf("failed to get HEAD reference: %w", err)
134+
}
135+
if !headRef.Name().IsBranch() {
136+
return "", fmt.Errorf("HEAD is not a branch")
137+
}
138+
return headRef.Name().Short(), nil
139+
}
140+
141+
// gomodModuleRegex extracts the module path from a go.mod file.
142+
var gomodModuleRegex = regexp.MustCompile(`(?m)^module\s+(\S+)`)
143+
144+
// detectControllerName reads the target repo's go.mod and extracts the
145+
// controller name (e.g. "helm-controller") from the module path.
146+
func detectControllerName(repoPath string) (string, error) {
147+
gomod := fmt.Sprintf("%s/go.mod", repoPath)
148+
b, err := os.ReadFile(gomod)
149+
if err != nil {
150+
return "", fmt.Errorf("failed to read %s: %w", gomod, err)
151+
}
152+
m := gomodModuleRegex.FindStringSubmatch(string(b))
153+
if m == nil {
154+
return "", fmt.Errorf("failed to find module path in %s", gomod)
155+
}
156+
modulePath := m[1]
157+
// Strip version suffix (e.g. "github.com/fluxcd/flux2/v2" → "github.com/fluxcd/flux2").
158+
if idx := strings.LastIndex(modulePath, "/v"); idx >= 0 {
159+
if _, err := strconv.Atoi(modulePath[idx+2:]); err == nil {
160+
modulePath = modulePath[:idx]
161+
}
162+
}
163+
// Extract the last path component (e.g. "github.com/fluxcd/helm-controller" → "helm-controller").
164+
name := modulePath[strings.LastIndex(modulePath, "/")+1:]
165+
return name, nil
166+
}
167+
168+
// releaseBranchRegex matches branch names like "release/v1.5.x" or "release/v2.3.x".
169+
var releaseBranchRegex = regexp.MustCompile(`^release/v\d+\.(\d+)\.x$`)
170+
171+
// mapToPkgBranch maps a caller repo branch to the corresponding fluxcd/pkg branch
172+
// using the controller's baseline minor version offset.
173+
func mapToPkgBranch(branch, controllerName string, preReleasePkg bool) (string, error) {
174+
switch {
175+
case preReleasePkg: // TODO: remove after 2.8.0 is released
176+
return "flux/v2.8.x", nil
177+
case branch == "main":
178+
return "main", nil
179+
}
180+
m := releaseBranchRegex.FindStringSubmatch(branch)
181+
if m == nil {
182+
fmt.Printf("Warning: branch %q does not match expected patterns, defaulting to main\n", branch)
183+
return "main", nil
184+
}
185+
branchMinor, _ := strconv.Atoi(m[1])
186+
baseline, ok := controllerBaselineMinor[controllerName]
187+
if !ok {
188+
return "", fmt.Errorf("unknown controller %q: not in baseline mapping", controllerName)
189+
}
190+
fluxMinor := baselineFluxMinor + (branchMinor - baseline)
191+
return fmt.Sprintf("flux/v2.%d.x", fluxMinor), nil
192+
}
193+
194+
// fetchLatestVersions clones the pkg repo in memory for the given branch
195+
// and returns a map of module name to latest version tag (e.g. "auth" → "v0.5.0").
196+
func fetchLatestVersions(ctx context.Context, pkgBranch string) (map[string]string, error) {
197+
fmt.Printf("Cloning %s (branch %s) ...\n", pkgRepoURL, pkgBranch)
198+
repo, err := git.CloneContext(ctx, memory.NewStorage(), nil, &git.CloneOptions{
199+
URL: pkgRepoURL,
200+
ReferenceName: plumbing.NewBranchReferenceName(pkgBranch),
201+
SingleBranch: true,
202+
Tags: git.AllTags,
203+
})
204+
if err != nil {
205+
return nil, fmt.Errorf("failed to clone pkg repo: %w", err)
206+
}
207+
208+
headRef, err := repo.Head()
209+
if err != nil {
210+
return nil, fmt.Errorf("failed to get HEAD reference: %w", err)
211+
}
212+
213+
moduleLatest, err := collectLatestReachableTags(repo, headRef.Hash())
214+
if err != nil {
215+
return nil, fmt.Errorf("failed to collect latest reachable tags: %w", err)
216+
}
217+
218+
// Convert *semver.Version to "v<version>" strings.
219+
latestVersions := make(map[string]string, len(moduleLatest))
220+
for module, v := range moduleLatest {
221+
latestVersions[module] = "v" + v.String()
222+
}
223+
return latestVersions, nil
224+
}
225+
226+
// gomodPkgDepRegex matches lines like: github.com/fluxcd/pkg/runtime v1.2.0
227+
var gomodPkgDepRegex = regexp.MustCompile(`(?m)^\s+(github\.com/fluxcd/pkg/(\S+))\s+(v\S+)`)
228+
229+
// updateGoMod reads go.mod, replaces fluxcd/pkg dependency versions with the
230+
// latest ones, writes go.mod back (unless dry-run), and runs go mod tidy.
231+
func updateGoMod(ctx context.Context, repoPath string, latestVersions map[string]string) ([]depUpdate, error) {
232+
gomod := fmt.Sprintf("%s/go.mod", repoPath)
233+
b, err := os.ReadFile(gomod)
234+
if err != nil {
235+
return nil, fmt.Errorf("failed to read %s: %w", gomod, err)
236+
}
237+
oldContent := string(b)
238+
239+
var updates []depUpdate
240+
newContent := gomodPkgDepRegex.ReplaceAllStringFunc(oldContent, func(match string) string {
241+
sub := gomodPkgDepRegex.FindStringSubmatch(match)
242+
// sub[0] = full match (with leading whitespace)
243+
// sub[1] = full module path, sub[2] = module name, sub[3] = current version
244+
module := sub[2]
245+
oldVersion := sub[3]
246+
newVersion, ok := latestVersions[module]
247+
if !ok || newVersion == oldVersion {
248+
return match
249+
}
250+
updates = append(updates, depUpdate{
251+
module: module,
252+
oldVersion: oldVersion,
253+
newVersion: newVersion,
254+
})
255+
// Preserve leading whitespace from the original match.
256+
ws := match[:strings.Index(match, sub[1])]
257+
return ws + sub[1] + " " + newVersion
258+
})
259+
260+
if len(updates) == 0 {
261+
return updates, nil
262+
}
263+
264+
if err := os.WriteFile(gomod, []byte(newContent), 0644); err != nil {
265+
return nil, fmt.Errorf("failed to write %s: %w", gomod, err)
266+
}
267+
gomodtidy := exec.CommandContext(ctx, "go", "mod", "tidy")
268+
gomodtidy.Dir = repoPath
269+
out, err := gomodtidy.CombinedOutput()
270+
if err != nil {
271+
return nil, fmt.Errorf("failed to run go mod tidy: %w\n%s", err, string(out))
272+
}
273+
return updates, nil
274+
}

0 commit comments

Comments
 (0)