Skip to content

Commit 52bc1ed

Browse files
authored
Merge pull request #1116 from fluxcd/cmd-bump
cmd: introduce command for bumping modules in controller repos
2 parents b1df0c1 + 5537abd commit 52bc1ed

4 files changed

Lines changed: 448 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: 284 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,284 @@
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+
"regexp"
24+
"strconv"
25+
"strings"
26+
27+
"github.com/go-git/go-git/v5"
28+
"github.com/go-git/go-git/v5/plumbing"
29+
"github.com/go-git/go-git/v5/storage/memory"
30+
)
31+
32+
// Baseline: controller minor versions at flux 2.7.
33+
// For each flux2 minor bump, all controller minors increase by 1.
34+
// Every time a new controller is added, this baseline should be
35+
// updated to the flux2 minor at which it was added.
36+
const baselineFluxMinor = 7
37+
38+
var controllerBaselineMinor = map[string]int{
39+
// the distro itself
40+
"flux2": baselineFluxMinor, // 2.7
41+
42+
// controllers
43+
"source-controller": 7, // 1.7
44+
"kustomize-controller": 7, // 1.7
45+
"helm-controller": 4, // 1.4
46+
"notification-controller": 7, // 1.7
47+
"image-reflector-controller": 0, // 1.0
48+
"image-automation-controller": 0, // 1.0
49+
"source-watcher": 0, // 2.0
50+
}
51+
52+
const pkgRepoURL = "https://github.com/fluxcd/pkg.git"
53+
54+
// depUpdate represents a single dependency version change.
55+
type depUpdate struct {
56+
module string
57+
oldVersion string
58+
newVersion string
59+
}
60+
61+
// BumpResult holds the outcome of a BumpDeps operation.
62+
type BumpResult struct {
63+
pkgBranch string
64+
updates []depUpdate
65+
}
66+
67+
// NothingToUpdate reports whether there are no dependency updates.
68+
func (r *BumpResult) NothingToUpdate() bool {
69+
return len(r.updates) == 0
70+
}
71+
72+
// PrintSummary prints a human-readable summary of the bump result.
73+
func (r *BumpResult) PrintSummary() {
74+
fmt.Printf("pkg branch: %s\n", r.pkgBranch)
75+
if r.NothingToUpdate() {
76+
fmt.Println("All fluxcd/pkg dependencies are up to date.")
77+
return
78+
}
79+
fmt.Println("Updates:")
80+
for _, u := range r.updates {
81+
fmt.Printf(" github.com/fluxcd/pkg/%s: %s => %s\n", u.module, u.oldVersion, u.newVersion)
82+
}
83+
}
84+
85+
// BumpDeps detects the current branch, maps it to the corresponding
86+
// fluxcd/pkg branch, fetches the latest module versions from that branch,
87+
// and updates go.mod accordingly. When preReleasePkg is true, main branches
88+
// use flux/v2.8.x instead of main (temporary workaround for Flux 2.8).
89+
func BumpDeps(ctx context.Context, repoPath string, preReleasePkg bool) (*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, preReleasePkg)
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+
var allUpdates []depUpdate
114+
115+
// Bump go.mod files in dependency order: api/ first (root depends on it),
116+
// then root, then tests/integration/ (may depend on root).
117+
// go mod tidy is not run here; callers handle it separately.
118+
modules := []string{"api", ".", "tests/integration"}
119+
for _, mod := range modules {
120+
dir := repoPath
121+
if mod != "." {
122+
dir = repoPath + "/" + mod
123+
if _, err := os.Stat(dir + "/go.mod"); err != nil {
124+
continue
125+
}
126+
}
127+
fmt.Printf("Bumping %s/go.mod ...\n", mod)
128+
updates, err := replaceGoModVersions(dir, latestVersions)
129+
if err != nil {
130+
return nil, fmt.Errorf("failed to update %s/go.mod: %w", mod, err)
131+
}
132+
allUpdates = append(allUpdates, updates...)
133+
}
134+
135+
return &BumpResult{
136+
pkgBranch: pkgBranch,
137+
updates: allUpdates,
138+
}, nil
139+
}
140+
141+
// detectLocalBranch opens the current directory as a git repo and returns the branch name.
142+
func detectLocalBranch(repoPath string) (string, error) {
143+
repo, err := git.PlainOpen(repoPath)
144+
if err != nil {
145+
return "", fmt.Errorf("failed to open repository: %w", err)
146+
}
147+
headRef, err := repo.Head()
148+
if err != nil {
149+
return "", fmt.Errorf("failed to get HEAD reference: %w", err)
150+
}
151+
if !headRef.Name().IsBranch() {
152+
return "", fmt.Errorf("HEAD is not a branch")
153+
}
154+
return headRef.Name().Short(), nil
155+
}
156+
157+
// gomodModuleRegex extracts the module path from a go.mod file.
158+
var gomodModuleRegex = regexp.MustCompile(`(?m)^module\s+(\S+)`)
159+
160+
// detectControllerName reads the target repo's go.mod and extracts the
161+
// controller name (e.g. "helm-controller") from the module path.
162+
func detectControllerName(repoPath string) (string, error) {
163+
gomod := fmt.Sprintf("%s/go.mod", repoPath)
164+
b, err := os.ReadFile(gomod)
165+
if err != nil {
166+
return "", fmt.Errorf("failed to read %s: %w", gomod, err)
167+
}
168+
m := gomodModuleRegex.FindStringSubmatch(string(b))
169+
if m == nil {
170+
return "", fmt.Errorf("failed to find module path in %s", gomod)
171+
}
172+
modulePath := m[1]
173+
// Strip version suffix (e.g. "github.com/fluxcd/flux2/v2" → "github.com/fluxcd/flux2").
174+
if idx := strings.LastIndex(modulePath, "/v"); idx >= 0 {
175+
if _, err := strconv.Atoi(modulePath[idx+2:]); err == nil {
176+
modulePath = modulePath[:idx]
177+
}
178+
}
179+
// Extract the last path component (e.g. "github.com/fluxcd/helm-controller" → "helm-controller").
180+
name := modulePath[strings.LastIndex(modulePath, "/")+1:]
181+
return name, nil
182+
}
183+
184+
// releaseBranchRegex matches branch names like "release/v1.5.x" or "release/v2.3.x".
185+
var releaseBranchRegex = regexp.MustCompile(`^release/v\d+\.(\d+)\.x$`)
186+
187+
// mapToPkgBranch maps a caller repo branch to the corresponding fluxcd/pkg branch
188+
// using the controller's baseline minor version offset.
189+
func mapToPkgBranch(branch, controllerName string, preReleasePkg bool) (string, error) {
190+
switch {
191+
case preReleasePkg: // TODO: remove after 2.8.0 is released
192+
return "flux/v2.8.x", nil
193+
case branch == "main":
194+
return "main", nil
195+
}
196+
m := releaseBranchRegex.FindStringSubmatch(branch)
197+
if m == nil {
198+
fmt.Printf("Warning: branch %q does not match expected patterns, defaulting to main\n", branch)
199+
return "main", nil
200+
}
201+
branchMinor, _ := strconv.Atoi(m[1])
202+
baseline, ok := controllerBaselineMinor[controllerName]
203+
if !ok {
204+
return "", fmt.Errorf("unknown controller %q: not in baseline mapping", controllerName)
205+
}
206+
fluxMinor := baselineFluxMinor + (branchMinor - baseline)
207+
return fmt.Sprintf("flux/v2.%d.x", fluxMinor), nil
208+
}
209+
210+
// fetchLatestVersions clones the pkg repo in memory for the given branch
211+
// and returns a map of module name to latest version tag (e.g. "auth" → "v0.5.0").
212+
func fetchLatestVersions(ctx context.Context, pkgBranch string) (map[string]string, error) {
213+
fmt.Printf("Cloning %s (branch %s) ...\n", pkgRepoURL, pkgBranch)
214+
repo, err := git.CloneContext(ctx, memory.NewStorage(), nil, &git.CloneOptions{
215+
URL: pkgRepoURL,
216+
ReferenceName: plumbing.NewBranchReferenceName(pkgBranch),
217+
SingleBranch: true,
218+
Tags: git.AllTags,
219+
})
220+
if err != nil {
221+
return nil, fmt.Errorf("failed to clone pkg repo: %w", err)
222+
}
223+
224+
headRef, err := repo.Head()
225+
if err != nil {
226+
return nil, fmt.Errorf("failed to get HEAD reference: %w", err)
227+
}
228+
229+
moduleLatest, err := collectLatestReachableTags(repo, headRef.Hash())
230+
if err != nil {
231+
return nil, fmt.Errorf("failed to collect latest reachable tags: %w", err)
232+
}
233+
234+
// Convert *semver.Version to "v<version>" strings.
235+
latestVersions := make(map[string]string, len(moduleLatest))
236+
for module, v := range moduleLatest {
237+
latestVersions[module] = "v" + v.String()
238+
}
239+
return latestVersions, nil
240+
}
241+
242+
// gomodPkgDepRegex matches lines like: github.com/fluxcd/pkg/runtime v1.2.0
243+
var gomodPkgDepRegex = regexp.MustCompile(`(?m)^\s+(github\.com/fluxcd/pkg/(\S+))\s+(v\S+)`)
244+
245+
// replaceGoModVersions reads go.mod, replaces fluxcd/pkg dependency versions
246+
// with the latest ones, and writes the file back.
247+
func replaceGoModVersions(dir string, latestVersions map[string]string) ([]depUpdate, error) {
248+
gomod := dir + "/go.mod"
249+
b, err := os.ReadFile(gomod)
250+
if err != nil {
251+
return nil, fmt.Errorf("failed to read %s: %w", gomod, err)
252+
}
253+
oldContent := string(b)
254+
255+
var updates []depUpdate
256+
newContent := gomodPkgDepRegex.ReplaceAllStringFunc(oldContent, func(match string) string {
257+
sub := gomodPkgDepRegex.FindStringSubmatch(match)
258+
// sub[0] = full match (with leading whitespace)
259+
// sub[1] = full module path, sub[2] = module name, sub[3] = current version
260+
module := sub[2]
261+
oldVersion := sub[3]
262+
newVersion, ok := latestVersions[module]
263+
if !ok || newVersion == oldVersion {
264+
return match
265+
}
266+
updates = append(updates, depUpdate{
267+
module: module,
268+
oldVersion: oldVersion,
269+
newVersion: newVersion,
270+
})
271+
// Preserve leading whitespace from the original match.
272+
ws := match[:strings.Index(match, sub[1])]
273+
return ws + sub[1] + " " + newVersion
274+
})
275+
276+
if len(updates) == 0 {
277+
return updates, nil
278+
}
279+
280+
if err := os.WriteFile(gomod, []byte(newContent), 0644); err != nil {
281+
return nil, fmt.Errorf("failed to write %s: %w", gomod, err)
282+
}
283+
return updates, nil
284+
}

0 commit comments

Comments
 (0)