Skip to content

Commit ede3698

Browse files
Use Environment Context over consts
1 parent 79a1f4b commit ede3698

34 files changed

Lines changed: 492 additions & 135 deletions

cmd/compliance/sbom.go

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import (
1313
"github.com/go-nv/goenv/internal/errors"
1414
"github.com/go-nv/goenv/internal/platform"
1515
"github.com/go-nv/goenv/internal/resolver"
16+
"github.com/go-nv/goenv/internal/utils"
1617
"github.com/spf13/cobra"
1718
)
1819

@@ -100,6 +101,7 @@ func runSBOMProject(cmd *cobra.Command, args []string) error {
100101
ctx := cmdutil.GetContexts(cmd)
101102
cfg := ctx.Config
102103
mgr := ctx.Manager
104+
env := ctx.Environment
103105

104106
// Validate flags
105107
if sbomImage != "" && sbomDir != "." {
@@ -117,7 +119,7 @@ func runSBOMProject(cmd *cobra.Command, args []string) error {
117119
}
118120

119121
// Resolve tool path using version context
120-
toolPath, err := resolveSBOMTool(cfg, sbomTool, goVersion, versionSource)
122+
toolPath, err := resolveSBOMTool(cfg, env, sbomTool, goVersion, versionSource)
121123
if err != nil {
122124
return err
123125
}
@@ -172,9 +174,9 @@ func runSBOMProject(cmd *cobra.Command, args []string) error {
172174
}
173175

174176
// resolveSBOMTool finds the tool binary using version-aware resolution
175-
func resolveSBOMTool(cfg *config.Config, tool, version, versionSource string) (string, error) {
177+
func resolveSBOMTool(cfg *config.Config, env *utils.GoenvEnvironment, tool, version, versionSource string) (string, error) {
176178
// Use resolver to respect local vs global context
177-
r := resolver.New(cfg)
179+
r := resolver.New(cfg, env)
178180

179181
if version != "unknown" && version != "" {
180182
if toolPath, err := r.ResolveBinary(tool, version, versionSource); err == nil {

cmd/compliance/sbom_test.go

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package compliance
22

33
import (
4+
"context"
45
"os"
56
"path/filepath"
67
"strings"
@@ -150,8 +151,11 @@ func TestResolveSBOMTool(t *testing.T) {
150151

151152
testutil.WriteTestFile(t, toolPath, []byte(content), utils.PermFileExecutable)
152153

154+
env, err := utils.LoadEnvironment(context.Background())
155+
require.NoError(t, err, "Failed to load environment")
156+
153157
// Test resolution with global version context (host bin accessible)
154-
resolvedPath, err := resolveSBOMTool(cfg, toolName, "1.21.0", "")
158+
resolvedPath, err := resolveSBOMTool(cfg, env, toolName, "1.21.0", "")
155159
require.NoError(t, err, "Failed to resolve tool")
156160

157161
assert.Equal(t, toolPath, resolvedPath, "Expected path")
@@ -164,8 +168,11 @@ func TestResolveSBOMTool_NotFound(t *testing.T) {
164168
Root: tmpDir,
165169
}
166170

171+
env, err := utils.LoadEnvironment(context.Background())
172+
require.NoError(t, err, "Failed to load environment")
173+
167174
// Test resolution for non-existent tool with global context
168-
_, err := resolveSBOMTool(cfg, "nonexistent-tool", "1.21.0", "")
175+
_, err = resolveSBOMTool(cfg, env, "nonexistent-tool", "1.21.0", "")
169176
assert.Error(t, err, "Expected error for non-existent tool")
170177

171178
assert.Contains(t, err.Error(), "not found", "Expected 'not found' error %v", err)

cmd/core/explain.go

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ func runExplain(cmd *cobra.Command, args []string) error {
6464
ctx := cmdutil.GetContexts(cmd)
6565
cfg := ctx.Config
6666
mgr := ctx.Manager
67+
env := ctx.Environment
6768

6869
// Get current version and source
6970
version, source, err := mgr.GetCurrentVersion()
@@ -99,13 +100,13 @@ func runExplain(cmd *cobra.Command, args []string) error {
99100
}
100101

101102
// Explain the source based on type
102-
explainSource(cmd, version, source, cfg)
103+
explainSource(cmd, version, source, cfg, env)
103104

104105
// Show version resolution order
105106
if explainFlags.verbose {
106-
fmt.Fprintln(cmd.OutOrStdout())
107-
fmt.Fprintln(cmd.OutOrStdout(), "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
108-
showResolutionOrder(cmd, cfg)
107+
fmt.Fprintln(cmd.OutOrStdout(), "")
108+
fmt.Fprintln(cmd.OutOrStdout(), "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
109+
showResolutionOrder(cmd, cfg, env)
109110
}
110111

111112
// Additional helpful commands
@@ -122,10 +123,10 @@ func runExplain(cmd *cobra.Command, args []string) error {
122123
return nil
123124
}
124125

125-
func explainSource(cmd *cobra.Command, version, source string, cfg *config.Config) {
126+
func explainSource(cmd *cobra.Command, version, source string, cfg *config.Config, env *utils.GoenvEnvironment) {
126127
// Determine the type of source
127128
switch {
128-
case strings.Contains(source, utils.GoenvEnvVarVersion.String()):
129+
case strings.Contains(source, "GOENV_VERSION"):
129130
explainEnvironmentVariable(cmd, version)
130131

131132
case strings.Contains(source, config.VersionFileName) && !strings.Contains(source, cfg.Root):
@@ -153,7 +154,7 @@ func explainEnvironmentVariable(cmd *cobra.Command, version string) {
153154
fmt.Fprintln(cmd.OutOrStdout(), "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
154155
fmt.Fprintln(cmd.OutOrStdout())
155156
fmt.Fprintf(cmd.OutOrStdout(), "The %s environment variable is set to %s.\n",
156-
utils.Cyan(utils.GoenvEnvVarVersion.String()), utils.Green(version))
157+
utils.Cyan("GOENV_VERSION"), utils.Green(version))
157158
fmt.Fprintln(cmd.OutOrStdout())
158159
fmt.Fprintln(cmd.OutOrStdout(), "This takes the HIGHEST PRIORITY over all other version sources.")
159160
fmt.Fprintln(cmd.OutOrStdout(), "It overrides both local .go-version files and the global default.")
@@ -314,20 +315,20 @@ func explainUnknown(cmd *cobra.Command, version, source string) {
314315
fmt.Fprintln(cmd.OutOrStdout(), " goenv local 1.23.0")
315316
}
316317

317-
func showResolutionOrder(cmd *cobra.Command, cfg *config.Config) {
318+
func showResolutionOrder(cmd *cobra.Command, cfg *config.Config, env *utils.GoenvEnvironment) {
318319
fmt.Fprintf(cmd.OutOrStdout(), "%s Version Resolution Order\n", utils.Emoji("📚"))
319-
fmt.Fprintln(cmd.OutOrStdout(), "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
320+
fmt.Fprintln(cmd.OutOrStdout(), "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
320321
fmt.Fprintln(cmd.OutOrStdout())
321322
fmt.Fprintln(cmd.OutOrStdout(), "goenv searches for version settings in this order:")
322323
fmt.Fprintln(cmd.OutOrStdout())
323324

324325
// 1. GOENV_VERSION
325-
envVersion := utils.GoenvEnvVarVersion.UnsafeValue()
326+
envVersion := env.GetVersion()
326327
if envVersion != "" {
327-
fmt.Fprintf(cmd.OutOrStdout(), "1. %s %s\n", utils.Green("✓"), utils.BoldGreen(fmt.Sprintf("%s environment variable", utils.GoenvEnvVarVersion.String())))
328+
fmt.Fprintf(cmd.OutOrStdout(), "1. %s %s\n", utils.Green("✓"), utils.BoldGreen("GOENV_VERSION environment variable"))
328329
fmt.Fprintf(cmd.OutOrStdout(), " Currently: %s\n", utils.Cyan(envVersion))
329330
} else {
330-
fmt.Fprintf(cmd.OutOrStdout(), "1. %s %s environment variable\n", utils.Gray("○"), utils.GoenvEnvVarVersion.String())
331+
fmt.Fprintf(cmd.OutOrStdout(), "1. %s %s environment variable\n", utils.Gray("○"), "GOENV_VERSION")
331332
fmt.Fprintf(cmd.OutOrStdout(), " %s\n", utils.Gray("Not set"))
332333
}
333334
fmt.Fprintln(cmd.OutOrStdout())
@@ -352,8 +353,7 @@ func showResolutionOrder(cmd *cobra.Command, cfg *config.Config) {
352353
// 4. go.mod
353354
gomodFile := filepath.Join(cwd, config.GoModFileName)
354355
if utils.PathExists(gomodFile) {
355-
disableGoMod := utils.GoenvEnvVarDisableGomod.UnsafeValue()
356-
if disableGoMod == "1" || disableGoMod == "true" {
356+
if env.HasDisableGomod() {
357357
fmt.Fprintf(cmd.OutOrStdout(), "4. %s go.mod file\n", utils.Gray("○"))
358358
fmt.Fprintf(cmd.OutOrStdout(), " %s\n", utils.Yellow("Found but disabled by GOENV_DISABLE_GOMOD"))
359359
} else {

cmd/core/install.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@ func runInstall(cmd *cobra.Command, args []string) error {
103103

104104
ctx := cmdutil.GetContexts(cmd)
105105
cfg := ctx.Config
106+
env := ctx.Environment
106107

107108
// Validate flags
108109
if installFlags.ipv4 && installFlags.ipv6 {
@@ -155,7 +156,7 @@ func runInstall(cmd *cobra.Command, args []string) error {
155156
goVersion = resolved // Use resolved version for installation
156157
} else {
157158
// Try to detect version from current directory (as documented in help text)
158-
mgr := manager.NewManager(cfg)
159+
mgr := manager.NewManager(cfg, env)
159160
detectedVersion, source, err := mgr.GetCurrentVersion()
160161

161162
if err == nil && detectedVersion != "" && detectedVersion != "system" {
@@ -253,13 +254,13 @@ func runInstall(cmd *cobra.Command, args []string) error {
253254

254255
// Auto-rehash to update shims for new Go version and installed tools
255256
// Skip if --no-rehash flag or GOENV_NO_AUTO_REHASH environment variable is set
256-
shouldRehash := !installFlags.noRehash && !utils.GoenvEnvVarNoAutoRehash.IsTrue()
257+
shouldRehash := !installFlags.noRehash && !env.HasNoAutoRehash()
257258

258259
if shouldRehash {
259260
if cfg.Debug {
260261
fmt.Fprintln(cmd.OutOrStdout(), "Debug: Auto-rehashing after installation")
261262
}
262-
shimMgr := shims.NewShimManager(cfg)
263+
shimMgr := shims.NewShimManager(cfg, env)
263264
_ = shimMgr.Rehash() // Don't fail the install if rehash fails
264265
} else if cfg.Debug {
265266
fmt.Fprintln(cmd.OutOrStdout(), "Debug: Skipping auto-rehash (disabled via flag or environment)")

cmd/core/uninstall.go

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -170,8 +170,12 @@ func checkActiveVersionAndOffer(cmd *cobra.Command, cfg *config.Config, mgr *man
170170
return true // Proceed without checks
171171
}
172172

173+
// Get environment from context
174+
ctxs := cmdutil.GetContexts(cmd)
175+
env := ctxs.Environment
176+
173177
// Check if version is active in various contexts
174-
isActive, context := isVersionActive(cfg, version)
178+
isActive, context := isVersionActive(cfg, env, version)
175179

176180
if !isActive {
177181
return true // Not active, safe to proceed
@@ -291,9 +295,9 @@ func promptVersionSelection(cmd *cobra.Command, requestedVersion string, matchin
291295
}
292296

293297
// isVersionActive checks if a version is currently active
294-
func isVersionActive(cfg *config.Config, version string) (bool, string) {
298+
func isVersionActive(cfg *config.Config, env *utils.GoenvEnvironment, version string) (bool, string) {
295299
// Check GOENV_VERSION environment variable
296-
if envVersion := utils.GoenvEnvVarVersion.UnsafeValue(); envVersion != "" {
300+
if envVersion := env.GetVersion(); envVersion != "" {
297301
if envVersion == version {
298302
return true, "(via GOENV_VERSION environment variable)"
299303
}

cmd/core/use.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ func runUse(cmd *cobra.Command, args []string) error {
9292
ctx := cmdutil.GetContexts(cmd)
9393
cfg := ctx.Config
9494
mgr := ctx.Manager
95+
env := ctx.Environment
9596

9697
// Resolve version spec (handles "latest", "stable", etc.)
9798
version, err := mgr.ResolveVersionSpec(versionSpec)
@@ -219,7 +220,7 @@ func runUse(cmd *cobra.Command, args []string) error {
219220
if !useFlags.quiet {
220221
fmt.Fprintf(cmd.OutOrStdout(), "\n%sUpdating shims...\n", utils.Emoji("🔄 "))
221222
}
222-
if err := runRehashForUse(cfg); err != nil {
223+
if err := runRehashForUse(cfg, env); err != nil {
223224
fmt.Fprintf(cmd.OutOrStderr(), "%sWarning: Failed to update shims: %v\n", utils.Emoji("⚠️ "), err)
224225
}
225226

@@ -252,8 +253,8 @@ func runUse(cmd *cobra.Command, args []string) error {
252253
}
253254

254255
// runRehashForUse is a helper to run rehash without output
255-
func runRehashForUse(cfg *config.Config) error {
256-
shimMgr := shims.NewShimManager(cfg)
256+
func runRehashForUse(cfg *config.Config, env *utils.GoenvEnvironment) error {
257+
shimMgr := shims.NewShimManager(cfg, env)
257258
return shimMgr.Rehash()
258259
}
259260

@@ -338,7 +339,7 @@ func detectVersionFileConflicts(dir string, targetVersion string) []VersionFileC
338339
// using the manager API for consistent parsing
339340
func readVersionFileSimple(path string) string {
340341
cfg := config.Load()
341-
mgr := manager.NewManager(cfg)
342+
mgr := manager.NewManager(cfg, nil)
342343
_ = cfg // unused but required by SetupContext
343344

344345
version, err := mgr.ReadVersionFile(path)

cmd/diagnostics/doctor.go

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,7 @@ func runDoctor(cmd *cobra.Command, args []string) error {
176176
ctx := cmdutil.GetContexts(cmd)
177177
cfg := ctx.Config
178178
mgr := ctx.Manager
179+
env := ctx.Environment
179180
results := []checkResult{}
180181

181182
// Validate and parse --fail-on flag
@@ -240,13 +241,13 @@ func runDoctor(cmd *cobra.Command, args []string) error {
240241
results = append(results, checkNetwork())
241242

242243
// Check 11: VS Code integration
243-
results = append(results, checkVSCodeIntegration(cfg))
244+
results = append(results, checkVSCodeIntegration(cfg, env))
244245

245246
// Check 11b: VS Code Go extension PATH injection
246247
results = append(results, checkVSCodeGoExtension())
247248

248249
// Check 12: go.mod version compatibility
249-
results = append(results, checkGoModVersion(cfg))
250+
results = append(results, checkGoModVersion(cfg, env))
250251

251252
// Check 13: Verify 'which go' matches expected version
252253
results = append(results, checkWhichGo(cfg, mgr))
@@ -273,7 +274,7 @@ func runDoctor(cmd *cobra.Command, args []string) error {
273274
results = append(results, checkCacheIsolationEffectiveness(cfg, mgr))
274275

275276
// Check 19: Rosetta detection (macOS only)
276-
results = append(results, checkRosetta(cfg))
277+
results = append(results, checkRosetta(cfg, env))
277278

278279
// Check 20: PATH order (goenv shims before system Go)
279280
results = append(results, checkPathOrder(cfg))
@@ -1740,7 +1741,8 @@ func detectFixableIssues(results []checkResult, cfg *config.Config) []fixableIss
17401741
// Fix helper functions
17411742

17421743
func fixRehash(cmd *cobra.Command, cfg *config.Config) error {
1743-
shimMgr := shims.NewShimManager(cfg)
1744+
ctx := cmdutil.GetContexts(cmd)
1745+
shimMgr := shims.NewShimManager(cfg, ctx.Environment)
17441746
return shimMgr.Rehash()
17451747
}
17461748

@@ -1809,7 +1811,8 @@ func fixReinstallCorrupted(cmd *cobra.Command, cfg *config.Config, version strin
18091811
}
18101812

18111813
func fixSetVersion(cmd *cobra.Command, cfg *config.Config) error {
1812-
mgr := manager.NewManager(cfg)
1814+
ctx := cmdutil.GetContexts(cmd)
1815+
mgr := manager.NewManager(cfg, ctx.Environment)
18131816
versions, err := mgr.ListInstalledVersions()
18141817
if err != nil || len(versions) == 0 {
18151818
return fmt.Errorf("no versions installed")
@@ -1824,7 +1827,8 @@ func fixInstallLatest(cmd *cobra.Command, cfg *config.Config) error {
18241827
}
18251828

18261829
func fixGoModVersion(cmd *cobra.Command, cfg *config.Config, version string) error {
1827-
mgr := manager.NewManager(cfg)
1830+
ctx := cmdutil.GetContexts(cmd)
1831+
mgr := manager.NewManager(cfg, ctx.Environment)
18281832
if mgr.IsVersionInstalled(version) {
18291833
fmt.Fprintf(cmd.OutOrStdout(), " Run: goenv local %s\n", version)
18301834
} else {
@@ -2693,7 +2697,7 @@ func checkNetwork() checkResult {
26932697
}
26942698
}
26952699

2696-
func checkVSCodeIntegration(cfg *config.Config) checkResult {
2700+
func checkVSCodeIntegration(cfg *config.Config, env *utils.GoenvEnvironment) checkResult {
26972701
// Get current working directory
26982702
cwd, err := os.Getwd()
26992703
if err != nil {
@@ -2734,7 +2738,7 @@ func checkVSCodeIntegration(cfg *config.Config) checkResult {
27342738
}
27352739

27362740
// Get current Go version to validate against
2737-
mgr := manager.NewManager(cfg)
2741+
mgr := manager.NewManager(cfg, env)
27382742
currentVersion, _, _, err := mgr.GetCurrentVersionResolved()
27392743
if err != nil || currentVersion == "" {
27402744
// Can't determine current version - do basic check
@@ -2861,7 +2865,7 @@ func checkVSCodeGoExtension() checkResult {
28612865
}
28622866
}
28632867

2864-
func checkGoModVersion(cfg *config.Config) checkResult {
2868+
func checkGoModVersion(cfg *config.Config, env *utils.GoenvEnvironment) checkResult {
28652869
cwd, _ := os.Getwd()
28662870
gomodPath := filepath.Join(cwd, config.GoModFileName)
28672871

@@ -2876,7 +2880,7 @@ func checkGoModVersion(cfg *config.Config) checkResult {
28762880
}
28772881

28782882
// Get current Go version (resolved, e.g., "1.25" → "1.25.4")
2879-
mgr := manager.NewManager(cfg)
2883+
mgr := manager.NewManager(cfg, env)
28802884
currentVersion, _, _, err := mgr.GetCurrentVersionResolved()
28812885
if err != nil {
28822886
return checkResult{
@@ -3540,7 +3544,7 @@ func checkCacheIsolationEffectiveness(cfg *config.Config, mgr *manager.Manager)
35403544
}
35413545
}
35423546

3543-
func checkRosetta(cfg *config.Config) checkResult {
3547+
func checkRosetta(cfg *config.Config, env *utils.GoenvEnvironment) checkResult {
35443548
// Only relevant on macOS
35453549
if !platform.IsMacOS() {
35463550
return checkResult{
@@ -3614,7 +3618,7 @@ func checkRosetta(cfg *config.Config) checkResult {
36143618
}
36153619

36163620
// Check current Go version architecture
3617-
mgr := manager.NewManager(cfg)
3621+
mgr := manager.NewManager(cfg, env)
36183622
// Get resolved version (e.g., "1.25" → "1.25.4")
36193623
currentVersion, _, _, err := mgr.GetCurrentVersionResolved()
36203624
if err != nil || currentVersion == "" || currentVersion == manager.SystemVersion {

0 commit comments

Comments
 (0)