-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbase_tool.go
More file actions
808 lines (688 loc) · 27.3 KB
/
base_tool.go
File metadata and controls
808 lines (688 loc) · 27.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
package tools
import (
"fmt"
"net/url"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"sync"
"github.com/gnodet/mvx/pkg/config"
"github.com/gnodet/mvx/pkg/util"
"github.com/gnodet/mvx/pkg/version"
)
// getUserFriendlyURL converts long redirect URLs to user-friendly display URLs
func getUserFriendlyURL(inputURL string) string {
// Handle GitHub release asset URLs
if strings.Contains(inputURL, "release-assets.githubusercontent.com") {
// Extract filename from response-content-disposition parameter
if strings.Contains(inputURL, "response-content-disposition=attachment") {
if start := strings.Index(inputURL, "filename%3D"); start != -1 {
start += len("filename%3D")
if end := strings.Index(inputURL[start:], "&"); end != -1 {
filename := inputURL[start : start+end]
// URL decode the filename
if decoded, err := url.QueryUnescape(filename); err == nil {
return fmt.Sprintf("github.com/.../releases/%s", decoded)
}
}
}
}
return "github.com/.../releases/[asset]"
}
// Handle other long URLs with query parameters
if len(inputURL) > 80 && strings.Contains(inputURL, "?") {
baseURL := strings.Split(inputURL, "?")[0]
if len(baseURL) > 50 {
// Extract domain and path
if parsed, err := url.Parse(baseURL); err == nil {
if len(parsed.Path) > 30 {
// Show domain + shortened path
pathParts := strings.Split(parsed.Path, "/")
if len(pathParts) > 3 {
return fmt.Sprintf("%s/.../%s", parsed.Host, pathParts[len(pathParts)-1])
}
}
return fmt.Sprintf("%s%s", parsed.Host, parsed.Path)
}
}
return baseURL
}
// For normal URLs, return as-is
return inputURL
}
// pathCacheEntry represents a cached path result
type pathCacheEntry struct {
path string
err error
}
// BaseTool provides common functionality for all tools
type BaseTool struct {
manager *Manager
toolName string
binaryName string
pathCache map[string]pathCacheEntry
cacheMux sync.RWMutex
}
// NewBaseTool creates a new base tool instance
func NewBaseTool(manager *Manager, toolName string, binaryName string) *BaseTool {
return &BaseTool{
manager: manager,
toolName: toolName,
binaryName: binaryName,
pathCache: make(map[string]pathCacheEntry),
}
}
// GetManager returns the tool manager
func (b *BaseTool) GetManager() *Manager {
return b.manager
}
// GetToolName returns the tool name
func (b *BaseTool) GetToolName() string {
return b.toolName
}
func (b *BaseTool) GetBinaryName() string {
return b.binaryName
}
// SupportsChecksumVerification returns whether this tool supports checksum verification
// Default implementation returns true for all tools
func (b *BaseTool) SupportsChecksumVerification() bool {
return true
}
// getCacheKey generates a cache key for path operations
func (b *BaseTool) getCacheKey(version string, cfg config.ToolConfig, operation string) string {
return fmt.Sprintf("%s:%s:%s:%s", operation, version, cfg.Distribution, b.toolName)
}
// getCachedPath retrieves a cached path result
func (b *BaseTool) getCachedPath(cacheKey string) (string, error, bool) {
b.cacheMux.RLock()
defer b.cacheMux.RUnlock()
if entry, exists := b.pathCache[cacheKey]; exists {
return entry.path, entry.err, true
}
return "", nil, false
}
// setCachedPath stores a path result in cache
func (b *BaseTool) setCachedPath(cacheKey string, path string, err error) {
b.cacheMux.Lock()
defer b.cacheMux.Unlock()
b.pathCache[cacheKey] = pathCacheEntry{
path: path,
err: err,
}
}
// clearPathCache clears the path cache (useful for testing)
func (b *BaseTool) clearPathCache() {
b.cacheMux.Lock()
defer b.cacheMux.Unlock()
b.pathCache = make(map[string]pathCacheEntry)
}
// getPlatformBinaryPath returns the platform-specific binary path
func (b *BaseTool) getPlatformBinaryPath(binPath, binaryName string) string {
return b.getPlatformBinaryPathWithExtension(binPath, binaryName)
}
// getPlatformBinaryPathWithExtension returns the platform-specific binary path with custom extension
func (b *BaseTool) getPlatformBinaryPathWithExtension(binPath, binaryName string) string {
return filepath.Join(binPath, binaryName)
}
// checkSystemBinaryExists checks if a system binary exists with platform-specific extensions
func (b *BaseTool) checkSystemBinaryExists(basePath, binaryName string) (bool, string) {
// Try the exact binary name first
fullPath := filepath.Join(basePath, binaryName)
if _, err := os.Stat(fullPath); err == nil {
return true, fullPath
}
return false, ""
}
// CreateInstallDir creates the installation directory for a tool version
func (b *BaseTool) CreateInstallDir(version, distribution string) (string, error) {
pathManager := NewInstallationPathManager(b.manager.GetToolsDir())
return pathManager.CreateToolInstallDir(b.toolName, version, distribution)
}
// Download performs a robust download with checksum verification
func (b *BaseTool) Download(url, version string, cfg config.ToolConfig) (string, error) {
// Always determine file extension from the download URL
fileExtension := detectFileExtensionFromURL(url)
// Create temporary file for download
tmpFile, err := os.CreateTemp("", fmt.Sprintf("%s-*%s", b.toolName, fileExtension))
if err != nil {
return "", fmt.Errorf("failed to create temporary file: %w", err)
}
defer tmpFile.Close()
// Configure robust download with checksum verification
downloadConfig := DefaultDownloadConfig(url, tmpFile.Name())
// Note: MinSize/MaxSize/ExpectedType removed - we rely on checksums for validation
downloadConfig.ToolName = b.toolName
downloadConfig.Version = version
downloadConfig.Config = cfg
// Get the tool instance for checksum verification
if tool, err := b.manager.GetTool(b.toolName); err == nil {
downloadConfig.Tool = tool
}
// Perform robust download with checksum verification
result, err := RobustDownload(downloadConfig)
if err != nil {
os.Remove(tmpFile.Name()) // Clean up on failure
return "", fmt.Errorf("%s download failed: %s", strings.Title(b.toolName), DiagnoseDownloadError(url, err))
}
// Show user-friendly URL instead of long redirect URLs
displayURL := getUserFriendlyURL(result.FinalURL)
fmt.Printf(" 📦 Downloaded %d bytes from %s\n", result.Size, displayURL)
// Return the path to the downloaded file
return tmpFile.Name(), nil
}
// Extract extracts an archive file to the destination directory
func (b *BaseTool) Extract(archivePath, destDir string) error {
// Use automatic archive type detection based on file extension
return ExtractArchive(archivePath, destDir)
}
// VerificationConfig contains configuration for tool verification
type VerificationConfig struct {
BinaryName string // Binary name to verify
VersionArgs []string // Arguments to get version (e.g., ["--version"])
ExpectedVersion string // Expected version string in output
DebugInfo bool // Whether to show debug information on failure
}
// Verify performs post-installation verification of a tool
func (b *BaseTool) Verify(installDir, version string, cfg config.ToolConfig) error {
// Default verification: check if installation directory exists and is not empty
if _, err := os.Stat(installDir); os.IsNotExist(err) {
return fmt.Errorf("installation directory does not exist: %s", installDir)
}
// Check if directory is not empty
entries, err := os.ReadDir(installDir)
if err != nil {
return fmt.Errorf("failed to read installation directory: %w", err)
}
if len(entries) == 0 {
return fmt.Errorf("installation directory is empty: %s", installDir)
}
return nil
}
// VerifyWithConfig performs comprehensive verification using configuration
func (b *BaseTool) VerifyWithConfig(version string, cfg config.ToolConfig, verifyConfig VerificationConfig) error {
// Get tool path
_, err := b.manager.GetTool(b.toolName)
if err != nil {
return VerifyError(b.toolName, version, fmt.Errorf("failed to get tool: %w", err))
}
// Use FindBinaryParentDir to locate the binary directory
installDir := b.manager.GetToolVersionDir(b.toolName, version, cfg.Distribution)
binaryName := verifyConfig.BinaryName
pathResolver := NewPathResolver(b.manager.GetToolsDir())
binDir, err := pathResolver.FindBinaryParentDir(installDir, binaryName)
if err != nil {
if verifyConfig.DebugInfo {
b.printVerificationDebugInfo(version, cfg, err)
}
return VerifyError(b.toolName, version, fmt.Errorf("failed to get binary path: %w", err))
}
// Set up environment for verification (needed for tools like Maven that depend on Java)
env, err := b.setupVerificationEnvironment(cfg)
if err != nil {
util.LogVerbose("Failed to setup verification environment: %v", err)
env = nil // Fall back to default environment
}
// Verify binary exists and works
if err := b.VerifyBinaryWithConfig(binDir, verifyConfig, env); err != nil {
return VerifyError(b.toolName, version, err)
}
return nil
}
// setupVerificationEnvironment sets up environment variables needed for tool verification
func (b *BaseTool) setupVerificationEnvironment(cfg config.ToolConfig) ([]string, error) {
// Create a minimal config that includes this tool and its dependencies
tempConfig := &config.Config{
Tools: make(map[string]config.ToolConfig),
}
// Add this tool to the config
tempConfig.Tools[b.toolName] = cfg
// Add dependencies if this tool has any
if tool, err := b.manager.GetTool(b.toolName); err == nil {
if depProvider, ok := tool.(DependencyProvider); ok {
dependencies := depProvider.GetDependencies()
util.LogVerbose("Setting up dependencies for %s verification: %v", b.toolName, dependencies)
// Add dependencies to the temporary config
for _, depName := range dependencies {
if depTool, err := b.manager.GetTool(depName); err == nil {
// Try to find an installed version of the dependency
if installedVersions := b.getInstalledVersionsForTool(depTool, depName); len(installedVersions) > 0 {
// Use the first available installed version
depConfig := config.ToolConfig{
Version: installedVersions[0].Version,
Distribution: installedVersions[0].Distribution,
}
tempConfig.Tools[depName] = depConfig
util.LogVerbose("Added dependency %s %s to verification environment", depName, installedVersions[0].Version)
}
}
}
}
}
// Use the standard environment setup
envMap, err := b.manager.SetupEnvironment(tempConfig)
if err != nil {
return nil, fmt.Errorf("failed to setup verification environment: %w", err)
}
// Start with current environment
envVars := make(map[string]string)
for _, envVar := range os.Environ() {
parts := strings.SplitN(envVar, "=", 2)
if len(parts) == 2 {
envVars[parts[0]] = parts[1]
}
}
// Override with tool environment
for key, value := range envMap {
envVars[key] = value
}
// Convert to environment slice format
envSlice := make([]string, 0, len(envVars))
for key, value := range envVars {
envSlice = append(envSlice, fmt.Sprintf("%s=%s", key, value))
}
return envSlice, nil
}
// SetupHomeEnvironment is a generic helper for setting up *_HOME environment variables
// It gets the tool's bin path and sets envVarName to the parent directory
// The getPath function should return the bin directory path for the tool
func (b *BaseTool) SetupHomeEnvironment(version string, cfg config.ToolConfig, envVars map[string]string, envVarName string, getPath func(string, config.ToolConfig) (string, error)) error {
binPath, err := getPath(version, cfg)
if err != nil {
util.LogVerbose("Could not determine %s for %s %s: %v", envVarName, b.toolName, version, err)
return nil
}
// *_HOME should point to the installation directory, not the bin directory
if strings.HasSuffix(binPath, "/bin") {
homeDir := strings.TrimSuffix(binPath, "/bin")
envVars[envVarName] = homeDir
util.LogVerbose("Set %s=%s for %s %s", envVarName, homeDir, b.toolName, version)
}
return nil
}
// getInstalledVersionsForTool gets installed versions for a tool (helper for verification environment)
func (b *BaseTool) getInstalledVersionsForTool(tool Tool, toolName string) []InstalledVersion {
// Try to get installed versions if the tool supports it
switch t := tool.(type) {
case *JavaTool:
versions := t.ListInstalledVersions("")
// Filter out versions with empty distribution to avoid path issues
var validVersions []InstalledVersion
for _, v := range versions {
if v.Distribution != "" {
validVersions = append(validVersions, v)
}
}
return validVersions
default:
// For other tools, we could implement a generic way to find installed versions
// For now, return empty slice
return []InstalledVersion{}
}
}
// DownloadAndExtract performs a robust download with checksum verification and extraction
// This is a convenience method that combines Download and Extract
func (b *BaseTool) DownloadAndExtract(url, destDir, version string, cfg config.ToolConfig) error {
// Download the file
archivePath, err := b.Download(url, version, cfg)
if err != nil {
return err
}
defer os.Remove(archivePath) // Clean up downloaded file after extraction
// Extract the file
return b.Extract(archivePath, destDir)
}
// VerifyBinary runs a binary with version flag and checks the output
func (b *BaseTool) VerifyBinary(binPath, binaryName, version string, versionArgs []string) error {
exe := b.getPlatformBinaryPath(binPath, binaryName)
// Run version command
cmd := exec.Command(exe, versionArgs...)
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("%s verification failed: %w\nOutput: %s", b.toolName, err, output)
}
return nil
}
// VerifyBinaryWithConfig runs a binary with configuration and environment and checks the output
func (b *BaseTool) VerifyBinaryWithConfig(binPath string, verifyConfig VerificationConfig, env []string) error {
exe := b.getPlatformBinaryPath(binPath, verifyConfig.BinaryName)
// Check if binary exists
if _, err := os.Stat(exe); err != nil {
return fmt.Errorf("%s executable not found at %s: %w", verifyConfig.BinaryName, exe, err)
}
// Run version command
cmd := exec.Command(exe, verifyConfig.VersionArgs...)
if env != nil {
cmd.Env = env
}
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("%s verification failed: %w\nOutput: %s", b.toolName, err, output)
}
// Check version if expected version is provided
if verifyConfig.ExpectedVersion != "" {
outputStr := string(output)
if !strings.Contains(outputStr, verifyConfig.ExpectedVersion) {
return fmt.Errorf("%s version mismatch: expected %s, got %s", b.toolName, verifyConfig.ExpectedVersion, outputStr)
}
}
return nil
}
// printVerificationDebugInfo prints detailed debug information for verification failures
func (b *BaseTool) printVerificationDebugInfo(version string, cfg config.ToolConfig, pathErr error) {
fmt.Printf(" 🔍 Debug: %s installation verification failed\n", b.toolName)
// Try to determine install directory
installDir := b.manager.GetToolVersionDir(b.toolName, version, cfg.Distribution)
fmt.Printf(" Install directory: %s\n", installDir)
fmt.Printf(" Error getting bin path: %v\n", pathErr)
// List contents of install directory for debugging
if entries, readErr := os.ReadDir(installDir); readErr == nil {
fmt.Printf(" Install directory contents:\n")
for _, entry := range entries {
fmt.Printf(" - %s (dir: %t)\n", entry.Name(), entry.IsDir())
}
}
}
// IsInstalled checks if a binary exists at the expected path
func (b *BaseTool) IsInstalled(binPath string) bool {
exe := b.getPlatformBinaryPath(binPath, b.GetBinaryName())
_, err := os.Stat(exe)
return err == nil
}
// GetDisplayName returns the default display name for this tool
// Tools should override this method to provide their own display name
func (b *BaseTool) GetDisplayName() string {
// Default implementation: title case of tool name
return strings.Title(b.toolName)
}
// PrintDownloadMessage prints a standardized download message
func (b *BaseTool) PrintDownloadMessage(version string) {
toolDisplayName := b.GetDisplayName()
fmt.Printf(" ⏳ Downloading %s %s...\n", toolDisplayName, version)
}
// StandardInstall provides a standard installation flow for most tools
func (b *BaseTool) StandardInstall(version string, cfg config.ToolConfig, getDownloadURL func(string) string) error {
// Check if we should use system tool instead of downloading
if UseSystemTool(b.toolName) {
util.LogVerbose("%s=true, forcing use of system %s", getSystemToolEnvVar(b.toolName), b.toolName)
// Try primary binary name in PATH
if toolPath, err := exec.LookPath(b.binaryName); err == nil {
fmt.Printf(" 🔗 Using system %s from PATH: %s\n", b.toolName, toolPath)
fmt.Printf(" ✅ System %s configured (mvx will use system PATH)\n", b.toolName)
return nil
}
return fmt.Errorf("MVX_USE_SYSTEM_%s=true but system %s not available", strings.ToUpper(b.toolName), b.toolName)
}
// Create installation directory
installDir, err := b.CreateInstallDir(version, "")
if err != nil {
return InstallError(b.toolName, version, fmt.Errorf("failed to create install directory: %w", err))
}
// Get download URL
downloadURL := getDownloadURL(version)
// Print download message
b.PrintDownloadMessage(version)
// Download the file
archivePath, err := b.Download(downloadURL, version, cfg)
if err != nil {
return InstallError(b.toolName, version, err)
}
defer os.Remove(archivePath) // Clean up downloaded file
// Extract the file
if err := b.Extract(archivePath, installDir); err != nil {
return InstallError(b.toolName, version, err)
}
// Verify installation was successful using tool's Verify method
if tool, err := b.manager.GetTool(b.toolName); err == nil {
if verifier, hasVerify := tool.(interface {
Verify(string, config.ToolConfig) error
}); hasVerify {
if err := verifier.Verify(version, cfg); err != nil {
// Installation verification failed, clean up the installation directory
fmt.Printf(" ❌ %s installation verification failed: %v\n", b.toolName, err)
fmt.Printf(" 🧹 Cleaning up failed installation directory...\n")
// if removeErr := os.RemoveAll(installDir); removeErr != nil {
// fmt.Printf(" ⚠️ Warning: failed to clean up installation directory: %v\n", removeErr)
// }
return InstallError(b.toolName, version, fmt.Errorf("installation verification failed: %w", err))
}
fmt.Printf(" ✅ %s %s installation verification successful\n", b.toolName, version)
}
}
return nil
}
// StandardVerify provides standard verification for tools with simple version commands
func (b *BaseTool) StandardVerify(version string, cfg config.ToolConfig, getPath func(string, config.ToolConfig) (string, error), binaryName string, versionArgs []string) error {
binPath, err := getPath(version, cfg)
if err != nil {
return VerifyError(b.toolName, version, fmt.Errorf("failed to get binary path: %w", err))
}
if err := b.VerifyBinary(binPath, binaryName, version, versionArgs); err != nil {
return VerifyError(b.toolName, version, err)
}
return nil
}
// detectFileExtensionFromURL detects the correct file extension from a download URL
// This handles both direct URLs and redirect URLs (like Java's Disco API)
func detectFileExtensionFromURL(downloadURL string) string {
// First try direct URL suffix detection
if strings.HasSuffix(downloadURL, ExtZip) {
return ExtZip
}
if strings.HasSuffix(downloadURL, ExtTarXz) {
return ExtTarXz
}
if strings.HasSuffix(downloadURL, ExtTarGz) {
return ExtTarGz
}
// For redirect URLs (like Java Disco API), try to extract filename from URL path
// Example: https://github.com/adoptium/temurin22-binaries/releases/download/jdk-22.0.2%2B9/OpenJDK22U-jdk_x64_windows_hotspot_22.0.2_9.zip
if parsed, err := url.Parse(downloadURL); err == nil {
// Extract filename from URL path
pathParts := strings.Split(parsed.Path, "/")
if len(pathParts) > 0 {
filename := pathParts[len(pathParts)-1]
// URL decode the filename in case it's encoded
if decoded, err := url.QueryUnescape(filename); err == nil {
filename = decoded
}
// Check file extension in the filename
if strings.HasSuffix(strings.ToLower(filename), ".zip") {
return ExtZip
}
if strings.HasSuffix(strings.ToLower(filename), ".tar.xz") {
return ExtTarXz
}
if strings.HasSuffix(strings.ToLower(filename), ".tar.gz") || strings.HasSuffix(strings.ToLower(filename), ".tgz") {
return ExtTarGz
}
}
}
// Default fallback
return ExtTarGz
}
// StandardVerifyWithConfig provides standard verification using VerificationConfig
func (b *BaseTool) StandardVerifyWithConfig(version string, cfg config.ToolConfig, verifyConfig VerificationConfig) error {
return b.VerifyWithConfig(version, cfg, verifyConfig)
}
// InstalledVersion holds info about an installed tool version
type InstalledVersion struct {
Version string
Distribution string
Path string
}
// ListInstalledVersions returns all installed versions for this tool and distribution.
// If distribution is empty, returns all distributions.
func (b *BaseTool) ListInstalledVersions(distribution string) []InstalledVersion {
toolsDir := b.manager.GetToolsDir()
toolDir := filepath.Join(toolsDir, b.toolName)
entries, err := os.ReadDir(toolDir)
if err != nil {
return nil
}
var installed []InstalledVersion
for _, entry := range entries {
if !entry.IsDir() {
continue
}
name := entry.Name()
versionPart, distPart, hasDistribution := strings.Cut(name, "@")
if !hasDistribution {
versionPart = name
distPart = ""
}
if distribution != "" && distPart != distribution {
continue
}
installed = append(installed, InstalledVersion{
Version: versionPart,
Distribution: distPart,
Path: filepath.Join(toolDir, name),
})
}
return installed
}
// StandardIsInstalled provides standard installation check for tools
func (b *BaseTool) StandardIsInstalled(versionSpec string, cfg config.ToolConfig, getPath func(string, config.ToolConfig) (string, error)) bool {
if UseSystemTool(b.toolName) {
if _, err := exec.LookPath(b.GetBinaryName()); err == nil {
util.LogVerbose("System %s is available in PATH (MVX_USE_SYSTEM_%s=true)", b.toolName, strings.ToUpper(b.toolName))
return true
}
util.LogVerbose("System %s not available: not found in environment variables or PATH", b.toolName)
return false
}
tool, err := b.manager.GetTool(b.toolName)
if err != nil {
util.LogVerbose("Failed to get tool %s: %v", b.toolName, err)
return false
}
spec, err := version.ParseSpec(versionSpec)
if err != nil {
util.LogVerbose("Failed to parse version spec %q: %v", versionSpec, err)
return false
}
targetVersion, resolveErr := b.resolveTargetVersion(tool, spec, versionSpec, cfg)
if resolveErr != nil {
util.LogVerbose("Failed to resolve target version for %s %s: %v", b.toolName, versionSpec, resolveErr)
}
installed := b.ListInstalledVersions(cfg.Distribution)
type installedCandidate struct {
info InstalledVersion
parsed *version.Version
}
var candidates []installedCandidate
for _, inst := range installed {
parsed, err := version.ParseVersion(inst.Version)
if err != nil {
util.LogVerbose("Failed to parse installed version %s: %v", inst.Version, err)
continue
}
if spec.Matches(parsed) {
if spec.Constraint == "latest" && resolveErr == nil && targetVersion != "" && inst.Version != targetVersion {
continue
}
candidates = append(candidates, installedCandidate{info: inst, parsed: parsed})
}
}
// Sort in descending order (newest first) to check best matches first
sort.Slice(candidates, func(i, j int) bool {
return candidates[i].parsed.Compare(candidates[j].parsed) > 0
})
// Check candidates in order, return immediately on first valid installation
for _, candidate := range candidates {
util.LogVerbose(" Checking installed version: %s (%s) at %s", candidate.info.Version, candidate.info.Distribution, candidate.info.Path)
candidateCfg := cfg
candidateCfg.Version = candidate.info.Version
if candidate.info.Distribution != "" {
candidateCfg.Distribution = candidate.info.Distribution
}
binPath, err := getPath(candidate.info.Version, candidateCfg)
if err != nil {
util.LogVerbose("Failed to compute binary path for %s %s: %v", b.toolName, candidate.info.Version, err)
continue
}
if !b.IsInstalled(binPath) {
util.LogVerbose("Binary for %s %s not found at %s", b.toolName, candidate.info.Version, binPath)
continue
}
// Skip verification during IsInstalled check for performance
// Binary existence is sufficient - verification happens during Install/Verify
// This avoids running "java -version", "mvn --version", etc. on every startup
// Found a valid installation - return immediately
util.LogVerbose("Using previously installed %s %s (%s)", b.toolName, candidate.info.Version, candidate.info.Distribution)
return true
}
if resolveErr != nil {
return false
}
if targetVersion == "" {
util.LogVerbose("Resolved target version for %s %s is empty", b.toolName, versionSpec)
return false
}
installCfg := cfg
installCfg.Version = targetVersion
util.LogVerbose("%s version %s not installed, attempting automatic installation", b.toolName, targetVersion)
if err := tool.Install(targetVersion, installCfg); err != nil {
util.LogVerbose("Automatic installation of %s %s failed: %v", b.toolName, targetVersion, err)
return false
}
if err := tool.Verify(targetVersion, installCfg); err != nil {
util.LogVerbose("Verification after installing %s %s failed: %v", b.toolName, targetVersion, err)
return false
}
b.clearPathCache()
util.LogVerbose("Successfully installed %s %s on demand", b.toolName, targetVersion)
return true
}
func (b *BaseTool) resolveTargetVersion(tool Tool, spec *version.Spec, versionSpec string, cfg config.ToolConfig) (string, error) {
resolveCfg := cfg
resolveCfg.Version = versionSpec
if resolved, err := b.manager.ResolveVersion(b.toolName, resolveCfg); err == nil && resolved != "" {
if parsed, parseErr := version.ParseVersion(resolved); parseErr == nil {
if spec.Constraint == "latest" || spec.Matches(parsed) {
return resolved, nil
}
} else {
return resolved, nil
}
}
available, err := tool.ListVersions()
if err != nil {
return "", err
}
resolved, err := spec.Resolve(available)
if err != nil {
return "", err
}
return resolved, nil
}
// StandardGetPath provides standard path resolution with system tool support
func (b *BaseTool) GetPath(version string, cfg config.ToolConfig, getInstalledPath func(string, config.ToolConfig) (string, error)) (string, error) {
return b.StandardGetPath(version, cfg, getInstalledPath)
}
// StandardGetPath provides standard path resolution with system tool support
func (b *BaseTool) StandardGetPath(version string, cfg config.ToolConfig, getInstalledPath func(string, config.ToolConfig) (string, error)) (string, error) {
// Check cache first
cacheKey := b.getCacheKey(version, cfg, "getPath")
if cachedPath, cachedErr, found := b.getCachedPath(cacheKey); found {
return cachedPath, cachedErr
}
// Check if we should use system tool instead of mvx-managed tool
if UseSystemTool(b.toolName) {
// Try primary binary name in PATH
if _, err := exec.LookPath(b.GetBinaryName()); err == nil {
util.LogVerbose("Using system %s from PATH (MVX_USE_SYSTEM_%s=true)", b.toolName, strings.ToUpper(b.toolName))
b.setCachedPath(cacheKey, "", nil)
return "", nil
}
systemErr := SystemToolError(b.toolName, fmt.Errorf("MVX_USE_SYSTEM_%s=true but system %s not available", strings.ToUpper(b.toolName), b.toolName))
b.setCachedPath(cacheKey, "", systemErr)
return "", systemErr
}
// Use mvx-managed tool path
path, err := getInstalledPath(version, cfg)
b.setCachedPath(cacheKey, path, err)
return path, err
}