-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmanager.go
More file actions
1148 lines (956 loc) · 34.2 KB
/
manager.go
File metadata and controls
1148 lines (956 loc) · 34.2 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
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package tools
import (
"bytes"
"crypto/sha256"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/gnodet/mvx/pkg/config"
"github.com/gnodet/mvx/pkg/util"
"github.com/gnodet/mvx/pkg/version"
)
// VersionCacheEntry represents a cached version resolution
type VersionCacheEntry struct {
ResolvedVersion string `json:"resolved_version"`
Timestamp time.Time `json:"timestamp"`
CacheVersion int `json:"cache_version"` // Version of cache format/logic
}
// Current cache version - increment when resolution logic changes
const versionCacheVersion = 2
// HTTPCacheEntry represents a cached HTTP response (in-memory only)
type HTTPCacheEntry struct {
Body []byte
Timestamp time.Time
}
// DiskCacheEntry represents a cached API response on disk
type DiskCacheEntry struct {
URL string `json:"url"`
Body string `json:"body"` // Base64 encoded for JSON safety
Timestamp time.Time `json:"timestamp"`
}
// Manager handles tool installation and management
type Manager struct {
cacheDir string
tools map[string]Tool
registry *ToolRegistry
versionCache map[string]VersionCacheEntry
installedCache map[string]bool // Cache for IsInstalled checks
pathCache map[string]string // Cache for GetPath results
httpCache map[string]HTTPCacheEntry // In-memory HTTP response cache
cacheMutex sync.RWMutex
httpClient *http.Client
}
var (
// Global singleton instance
globalManager *Manager
managerMutex sync.Mutex
)
// Tool represents a tool that can be installed and managed
type Tool interface {
// Name returns the tool name (e.g., "java", "maven")
GetToolName() string
// GetDisplayName returns the human-readable name for the tool
GetDisplayName() string
// Install downloads and installs the specified version
Install(version string, config config.ToolConfig) error
// IsInstalled checks if the specified version is installed
IsInstalled(version string, config config.ToolConfig) bool
// GetPath returns the binary path for the specified version (for PATH management)
GetPath(version string, config config.ToolConfig) (string, error)
// Verify checks if the installation is working correctly
Verify(version string, config config.ToolConfig) error
// ListVersions returns available versions for installation
ListVersions() ([]string, error)
// URL generation methods
GetDownloadURL(version string) string
// Checksum generation method
GetChecksum(version string, cfg config.ToolConfig, filename string) (ChecksumInfo, error)
// SupportsChecksumVerification returns whether this tool supports checksum verification
SupportsChecksumVerification() bool
// GetBinaryName returns the binary name for the tool
GetBinaryName() string
// GetManager returns the manager instance
GetManager() *Manager
}
// ToolInfoProvider is an optional interface for tools that can provide detailed information
type ToolInfoProvider interface {
// GetToolInfo returns detailed information about the tool
GetToolInfo() (map[string]interface{}, error)
}
// VersionValidator is an optional interface for tools that can validate versions
type VersionValidator interface {
// ValidateVersion checks if a version specification is valid for this tool
ValidateVersion(version, distribution string) error
}
// VersionResolver is an optional interface for tools that can resolve version specifications
type VersionResolver interface {
// ResolveVersion resolves a version specification (e.g., "21", "lts") to a concrete version
ResolveVersion(version, distribution string) (string, error)
}
// DistributionProvider is an optional interface for tools that support multiple distributions
type DistributionProvider interface {
// GetDistributions returns available distributions for this tool
GetDistributions() []Distribution
}
// DistributionVersionProvider is an optional interface for tools that can list versions per distribution
type DistributionVersionProvider interface {
// ListVersionsForDistribution returns available versions for a specific distribution
ListVersionsForDistribution(distribution string) ([]string, error)
}
// DependencyProvider is an optional interface for tools that depend on other tools
type DependencyProvider interface {
// GetDependencies returns a list of tool names that this tool depends on
GetDependencies() []string
}
// EnvironmentProvider is an optional interface for tools that need custom environment setup
type EnvironmentProvider interface {
// SetupEnvironment sets up tool-specific environment variables
// The envManager provides safe environment variable management with special PATH handling
SetupEnvironment(version string, cfg config.ToolConfig, envManager *EnvironmentManager) error
}
// Distribution represents a tool distribution (e.g., Java distributions like Temurin, Zulu)
type Distribution struct {
Name string
DisplayName string
}
// NewManager creates a new tool manager (singleton pattern)
func NewManager() (*Manager, error) {
managerMutex.Lock()
defer managerMutex.Unlock()
// Return existing instance if already created
if globalManager != nil {
return globalManager, nil
}
homeDir, err := os.UserHomeDir()
if err != nil {
return nil, fmt.Errorf("failed to get user home directory: %w", err)
}
cacheDir := filepath.Join(homeDir, ".mvx")
// Create cache directory if it doesn't exist
if err := os.MkdirAll(cacheDir, 0755); err != nil {
return nil, fmt.Errorf("failed to create cache directory %s: %w", cacheDir, err)
}
manager := &Manager{
cacheDir: cacheDir,
tools: make(map[string]Tool),
versionCache: make(map[string]VersionCacheEntry),
installedCache: make(map[string]bool),
pathCache: make(map[string]string),
httpCache: make(map[string]HTTPCacheEntry),
httpClient: &http.Client{
Timeout: getTimeoutFromEnv("MVX_HTTP_TIMEOUT", 120*time.Second), // Default: 2 minutes for slow servers
},
}
// Create registry after manager is initialized (to avoid circular dependency)
manager.registry = NewToolRegistry(manager)
// Load version cache from disk
manager.loadVersionCache()
// Auto-discover and register tools
if err := manager.discoverAndRegisterTools(); err != nil {
return nil, fmt.Errorf("failed to register tools: %w", err)
}
// Store as global singleton
globalManager = manager
return manager, nil
}
// ResetManager resets the global manager instance (for testing purposes)
func ResetManager() {
managerMutex.Lock()
defer managerMutex.Unlock()
globalManager = nil
}
// Get performs an HTTP GET request with verbose logging and multi-level caching
// This centralizes all HTTP requests and provides visibility into API calls
// Caching strategy:
// 1. In-memory cache (5 minutes) - for same execution
// 2. Disk cache (24 hours) - for all metadata APIs, persists across executions
// 3. Network request - if not cached
// Set MVX_FORCE_REFRESH=true to bypass disk cache and force fresh requests
func (m *Manager) Get(url string) (*http.Response, error) {
// Check in-memory cache first (fastest)
m.cacheMutex.RLock()
if cached, ok := m.httpCache[url]; ok {
// Cache valid for 5 minutes
if time.Since(cached.Timestamp) < 5*time.Minute {
m.cacheMutex.RUnlock()
if os.Getenv("MVX_VERBOSE") == "true" {
fmt.Printf("💾 HTTP GET (memory cache): %s\n", url)
}
// Return a fake response with cached body
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewReader(cached.Body)),
Header: make(http.Header),
}, nil
}
}
m.cacheMutex.RUnlock()
// Check disk cache (24 hours, unless MVX_FORCE_REFRESH is set)
// Cache all metadata API responses (Foojay, GitHub, Node.js, Apache)
if os.Getenv("MVX_FORCE_REFRESH") != "true" {
if body, found := m.getDiskCachedResponse(url); found {
if os.Getenv("MVX_VERBOSE") == "true" {
fmt.Printf("💾 HTTP GET (disk cache): %s\n", url)
}
// Also store in memory cache for faster subsequent access
m.cacheMutex.Lock()
m.httpCache[url] = HTTPCacheEntry{
Body: body,
Timestamp: time.Now(),
}
m.cacheMutex.Unlock()
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewReader(body)),
Header: make(http.Header),
}, nil
}
}
// Log the request if verbose mode is enabled
if os.Getenv("MVX_VERBOSE") == "true" {
fmt.Printf("🌐 HTTP GET: %s\n", url)
}
resp, err := m.httpClient.Get(url)
if err != nil {
if os.Getenv("MVX_VERBOSE") == "true" {
fmt.Printf("❌ HTTP GET failed: %s - %v\n", url, err)
}
return nil, err
}
if os.Getenv("MVX_VERBOSE") == "true" {
fmt.Printf("✅ HTTP GET %d: %s\n", resp.StatusCode, url)
}
// Cache successful responses (200 OK)
if resp.StatusCode == 200 {
// Read the body
body, err := io.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return nil, err
}
// Store in memory cache
m.cacheMutex.Lock()
m.httpCache[url] = HTTPCacheEntry{
Body: body,
Timestamp: time.Now(),
}
m.cacheMutex.Unlock()
// Store all metadata API responses in disk cache (24 hours)
// This includes: Foojay, GitHub, Node.js, Apache, etc.
m.setDiskCachedResponse(url, body)
// Return a new response with the body
return &http.Response{
StatusCode: resp.StatusCode,
Body: io.NopCloser(bytes.NewReader(body)),
Header: resp.Header,
Status: resp.Status,
}, nil
}
return resp, nil
}
// RegisterTool registers a tool with the manager
func (m *Manager) RegisterTool(tool Tool) {
m.tools[tool.GetToolName()] = tool
}
// GetTool returns a tool by name
func (m *Manager) GetTool(name string) (Tool, error) {
tool, exists := m.tools[name]
if !exists {
return nil, fmt.Errorf("unknown tool: %s", name)
}
return tool, nil
}
// GetAllTools returns all registered tools
func (m *Manager) GetAllTools() map[string]Tool {
result := make(map[string]Tool)
for name, tool := range m.tools {
result[name] = tool
}
return result
}
// GetToolNames returns the names of all registered tools
func (m *Manager) GetToolNames() []string {
names := make([]string, 0, len(m.tools))
for name := range m.tools {
names = append(names, name)
}
return names
}
// ToolFactory represents a function that creates a tool instance
// This enables dynamic tool registration without modifying the manager code
type ToolFactory func(*Manager) Tool
// toolFactories contains all available tool factories for auto-discovery
// This registry allows tools to be registered dynamically, following the Open/Closed Principle
var toolFactories = map[string]ToolFactory{
ToolJava: func(m *Manager) Tool { return NewJavaTool(m) },
ToolMaven: func(m *Manager) Tool { return NewMavenTool(m) },
ToolMvnd: func(m *Manager) Tool { return NewMvndTool(m) },
ToolNode: func(m *Manager) Tool { return NewNodeTool(m) },
ToolGo: func(m *Manager) Tool { return NewGoTool(m) },
}
// discoverAndRegisterTools automatically discovers and registers all available tools
func (m *Manager) discoverAndRegisterTools() error {
// Register tools from the factory registry
for toolName, factory := range toolFactories {
tool := factory(m)
m.RegisterTool(tool)
util.LogVerbose("Registered tool: %s", toolName)
}
// Future enhancement: could also load tools from configuration files
// This would allow users to register custom tools without code changes
return nil
}
// RegisterToolFactory registers a new tool factory for auto-discovery
// This allows external packages to register their own tools
func RegisterToolFactory(name string, factory ToolFactory) {
toolFactories[name] = factory
}
// GetRegisteredToolFactories returns the names of all registered tool factories
// This is useful for debugging and introspection
func GetRegisteredToolFactories() []string {
names := make([]string, 0, len(toolFactories))
for name := range toolFactories {
names = append(names, name)
}
return names
}
// SearchToolVersions searches for versions of a specific tool with optional filters
func (m *Manager) SearchToolVersions(toolName string, filters []string) ([]string, error) {
tool, err := m.GetTool(toolName)
if err != nil {
return nil, err
}
versions, err := tool.ListVersions()
if err != nil {
return nil, fmt.Errorf("failed to get versions for %s: %w", toolName, err)
}
// Apply filters if provided
if len(filters) > 0 {
filtered := make([]string, 0)
for _, version := range versions {
for _, filter := range filters {
if strings.Contains(strings.ToLower(version), strings.ToLower(filter)) {
filtered = append(filtered, version)
break
}
}
}
return filtered, nil
}
return versions, nil
}
// GetToolInfo returns detailed information about a tool
func (m *Manager) GetToolInfo(toolName string) (map[string]interface{}, error) {
tool, err := m.GetTool(toolName)
if err != nil {
return nil, err
}
// Check if tool implements ToolInfoProvider interface
if infoProvider, ok := tool.(ToolInfoProvider); ok {
return infoProvider.GetToolInfo()
}
// Fallback to basic information
versions, err := tool.ListVersions()
if err != nil {
return nil, fmt.Errorf("failed to get versions for %s: %w", toolName, err)
}
return map[string]interface{}{
"name": toolName,
"versions": versions,
}, nil
}
// ValidateToolVersion validates that a version exists for the given tool
func (m *Manager) ValidateToolVersion(toolName, version, distribution string) error {
tool, err := m.GetTool(toolName)
if err != nil {
return err
}
// Check if tool implements VersionValidator interface
if validator, ok := tool.(VersionValidator); ok {
return validator.ValidateVersion(version, distribution)
}
// Fallback to checking if version exists in available versions
versions, err := tool.ListVersions()
if err != nil {
return fmt.Errorf("failed to get versions for %s: %w", toolName, err)
}
// For version specs like "lts", "latest", etc., we need to resolve them
resolvedVersion, err := m.resolveVersion(toolName, config.ToolConfig{
Version: version,
Distribution: distribution,
})
if err != nil {
return fmt.Errorf("failed to resolve version %s for %s: %w", version, toolName, err)
}
// Check if resolved version exists
for _, v := range versions {
if v == resolvedVersion {
return nil
}
}
return fmt.Errorf("version %s (resolved to %s) not found for tool %s", version, resolvedVersion, toolName)
}
// GetDefaultConcurrency returns the default concurrency level from environment or default
func GetDefaultConcurrency() int {
if concStr := os.Getenv("MVX_PARALLEL_DOWNLOADS"); concStr != "" {
if conc, err := strconv.Atoi(concStr); err == nil && conc > 0 {
return conc
}
}
return 3 // Default to 3 concurrent downloads
}
// EnsureTools ensures all tools from configuration are installed (with parallel downloads)
// This replaces InstallTools and uses EnsureTool for automatic installation
func (m *Manager) EnsureTools(cfg *config.Config, maxConcurrent int) error {
if len(cfg.Tools) == 0 {
return nil
}
if maxConcurrent <= 0 {
maxConcurrent = GetDefaultConcurrency()
}
// Resolve dependency order
orderedTools, err := m.resolveDependencyOrder(cfg)
if err != nil {
return fmt.Errorf("failed to resolve tool dependencies: %w", err)
}
// If only one tool, use sequential
if len(orderedTools) == 1 {
toolName := orderedTools[0]
toolConfig := cfg.Tools[toolName]
_, err := m.EnsureTool(toolName, toolConfig)
if err != nil {
return fmt.Errorf("failed to ensure %s is installed: %w", toolName, err)
}
fmt.Printf("✅ %s is ready\n", toolName)
return nil
}
fmt.Printf("📦 Ensuring %d tools are installed (max %d concurrent)...\n", len(cfg.Tools), maxConcurrent)
// Install tools in dependency order
// Tools with dependencies must be installed sequentially, but independent tools can be parallel
completed := 0
for _, toolName := range orderedTools {
toolConfig := cfg.Tools[toolName]
if _, err := m.EnsureTool(toolName, toolConfig); err != nil {
return fmt.Errorf("failed to ensure %s is installed: %w", toolName, err)
}
completed++
fmt.Printf(" ✅ %s is ready (%d/%d tools)\n", toolName, completed, len(cfg.Tools))
}
fmt.Printf("✅ All %d tools are ready\n", len(cfg.Tools))
return nil
}
// resolveDependencyOrder resolves the installation order for tools based on their dependencies
// Uses a simple topological sort with Kahn's algorithm
func (m *Manager) resolveDependencyOrder(cfg *config.Config) ([]string, error) {
// Build dependency map: tool -> list of dependencies
deps := make(map[string][]string)
for toolName := range cfg.Tools {
deps[toolName] = m.getToolDependencies(toolName, cfg)
}
// Topological sort: process tools with no remaining dependencies first
var result []string
processed := make(map[string]bool)
for len(result) < len(cfg.Tools) {
// Find a tool with all dependencies already processed
found := false
for toolName := range cfg.Tools {
if processed[toolName] {
continue
}
// Check if all dependencies are processed
allDepsProcessed := true
for _, dep := range deps[toolName] {
if !processed[dep] {
allDepsProcessed = false
break
}
}
if allDepsProcessed {
result = append(result, toolName)
processed[toolName] = true
found = true
break
}
}
// If no tool can be processed, we have a circular dependency
if !found {
return nil, fmt.Errorf("circular dependency detected among tools")
}
}
return result, nil
}
// getToolDependencies returns the list of dependencies for a tool that are configured in this project
func (m *Manager) getToolDependencies(toolName string, cfg *config.Config) []string {
tool, err := m.GetTool(toolName)
if err != nil {
return nil
}
depProvider, ok := tool.(DependencyProvider)
if !ok {
return nil
}
// Filter dependencies to only include those configured in this project
var configuredDeps []string
for _, dep := range depProvider.GetDependencies() {
if _, exists := cfg.Tools[dep]; exists {
configuredDeps = append(configuredDeps, dep)
}
}
return configuredDeps
}
// GetToolsNeedingInstallation returns a map of tools that need to be installed
func (m *Manager) GetToolsNeedingInstallation(cfg *config.Config) (map[string]config.ToolConfig, error) {
needInstallation := make(map[string]config.ToolConfig)
for toolName, toolConfig := range cfg.Tools {
tool, err := m.GetTool(toolName)
if err != nil {
return nil, fmt.Errorf("unknown tool %s: %w", toolName, err)
}
// Resolve version specification to concrete version
resolvedVersion, err := m.resolveVersion(toolName, toolConfig)
if err != nil {
return nil, fmt.Errorf("failed to resolve version for %s: %w", toolName, err)
}
// Update config with resolved version for checking
resolvedConfig := toolConfig
resolvedConfig.Version = resolvedVersion
if !tool.IsInstalled(resolvedVersion, resolvedConfig) {
needInstallation[toolName] = resolvedConfig
}
}
return needInstallation, nil
}
// GetCacheDir returns the cache directory path
func (m *Manager) GetCacheDir() string {
return m.cacheDir
}
// GetToolsDir returns the tools directory path
func (m *Manager) GetToolsDir() string {
return filepath.Join(m.cacheDir, "tools")
}
// GetToolDir returns the directory for a specific tool
func (m *Manager) GetToolDir(toolName string) string {
return filepath.Join(m.GetToolsDir(), toolName)
}
// GetToolVersionDir returns the directory for a specific tool version
func (m *Manager) GetToolVersionDir(toolName, version string, distribution string) string {
versionDir := version
if distribution != "" {
versionDir = fmt.Sprintf("%s@%s", version, distribution)
}
return filepath.Join(m.GetToolDir(toolName), versionDir)
}
// getCacheKey generates a cache key for tool operations
func (m *Manager) getCacheKey(toolName, version, distribution string) string {
return fmt.Sprintf("%s:%s:%s", toolName, version, distribution)
}
// isToolInstalled checks if a tool is installed (with caching)
func (m *Manager) isToolInstalled(toolName, version string, cfg config.ToolConfig) bool {
cacheKey := m.getCacheKey(toolName, version, cfg.Distribution)
m.cacheMutex.RLock()
if installed, found := m.installedCache[cacheKey]; found {
m.cacheMutex.RUnlock()
return installed
}
m.cacheMutex.RUnlock()
tool, err := m.GetTool(toolName)
if err != nil {
return false
}
installed := tool.IsInstalled(version, cfg)
m.cacheMutex.Lock()
m.installedCache[cacheKey] = installed
m.cacheMutex.Unlock()
return installed
}
// EnsureTool ensures a tool is installed and returns its binary path.
// This is the main entry point for tool management - it handles:
// - Version resolution (with caching)
// - Installation check (with caching)
// - Auto-installation if needed
// - Path retrieval (with caching)
// All in one atomic, cached operation.
func (m *Manager) EnsureTool(toolName string, cfg config.ToolConfig) (string, error) {
// Resolve version
resolvedVersion, err := m.resolveVersion(toolName, cfg)
if err != nil {
return "", fmt.Errorf("failed to resolve version for %s: %w", toolName, err)
}
resolvedConfig := cfg
resolvedConfig.Version = resolvedVersion
cacheKey := m.getCacheKey(toolName, resolvedVersion, cfg.Distribution)
// Check cache first
m.cacheMutex.RLock()
if path, found := m.pathCache[cacheKey]; found {
m.cacheMutex.RUnlock()
return path, nil
}
m.cacheMutex.RUnlock()
// Get tool instance
tool, err := m.GetTool(toolName)
if err != nil {
return "", err
}
// Check if installed
if !tool.IsInstalled(resolvedVersion, resolvedConfig) {
// Auto-install
util.LogVerbose("Auto-installing %s %s...", toolName, resolvedVersion)
if err := tool.Install(resolvedVersion, resolvedConfig); err != nil {
return "", fmt.Errorf("failed to install %s %s: %w", toolName, resolvedVersion, err)
}
// Verify installation
if err := tool.Verify(resolvedVersion, resolvedConfig); err != nil {
return "", fmt.Errorf("failed to verify %s %s: %w", toolName, resolvedVersion, err)
}
}
// Get path
path, err := tool.GetPath(resolvedVersion, resolvedConfig)
if err != nil {
return "", fmt.Errorf("failed to get path for %s %s: %w", toolName, resolvedVersion, err)
}
// Cache the result
m.cacheMutex.Lock()
m.pathCache[cacheKey] = path
m.installedCache[cacheKey] = true
m.cacheMutex.Unlock()
return path, nil
}
// SetupEnvironment sets up environment variables for installed tools
func (m *Manager) SetupEnvironment(cfg *config.Config) (map[string]string, error) {
// Create environment manager
envManager := NewEnvironmentManager()
// Add system environment variables first (except PATH - we'll handle that after tools)
var systemPath string
for _, envVar := range os.Environ() {
parts := strings.SplitN(envVar, "=", 2)
if len(parts) == 2 {
if parts[0] == "PATH" {
// Store system PATH for later - we want tool paths to take priority
systemPath = parts[1]
} else {
envManager.SetEnv(parts[0], parts[1])
}
}
}
// Override with config environment
for key, value := range cfg.Environment {
envManager.SetEnv(key, value)
}
// Add tool-specific environment variables and PATH entries
for toolName, toolConfig := range cfg.Tools {
// Resolve version
resolvedVersion, err := m.resolveVersion(toolName, toolConfig)
if err != nil {
util.LogVerbose("Skipping tool %s: version resolution failed: %v", toolName, err)
continue // Skip tools with resolution errors
}
resolvedConfig := toolConfig
resolvedConfig.Version = resolvedVersion
// Check if installed (using cache) - this works for both system and mvx-managed tools
if !m.isToolInstalled(toolName, resolvedVersion, resolvedConfig) {
util.LogVerbose("Skipping tool %s: not installed", toolName)
continue // Skip uninstalled tools
}
// Get tool instance
tool, err := m.GetTool(toolName)
if err != nil {
util.LogVerbose("Skipping tool %s: failed to get tool instance: %v", toolName, err)
continue
}
// Get tool path and add to PATH (returns empty string for system tools already in PATH)
toolPath, err := tool.GetPath(resolvedVersion, resolvedConfig)
if err != nil {
util.LogVerbose("Skipping tool %s: failed to get path: %v", toolName, err)
continue
}
// Add tool bin directory to PATH (only if path is not empty)
// For system tools already in PATH, toolPath will be empty and we skip adding it
if toolPath != "" {
envManager.AddToPath(toolPath)
util.LogVerbose("Added %s bin path to PATH: %s", toolName, toolPath)
} else {
util.LogVerbose("System %s is in PATH, not adding to PATH", toolName)
}
// Set tool-specific environment variables (HOME directories, etc.)
// This is important for system tools too - they may need HOME variables set
if envProvider, ok := tool.(EnvironmentProvider); ok {
if err := envProvider.SetupEnvironment(resolvedVersion, resolvedConfig, envManager); err != nil {
util.LogVerbose("Failed to setup environment for %s %s: %v", toolName, resolvedVersion, err)
}
}
}
// Add system PATH directories after tool directories (lower priority)
if systemPath != "" {
for _, dir := range strings.Split(systemPath, string(os.PathListSeparator)) {
if dir != "" {
envManager.AppendToPath(dir)
}
}
}
// Convert environment manager to map
return envManager.ToMap(), nil
}
// SetupProjectEnvironment sets up project-specific environment for tools
func (m *Manager) SetupProjectEnvironment(cfg *config.Config, projectPath string) (map[string]string, error) {
env := make(map[string]string)
// Copy base environment
baseEnv, err := m.SetupEnvironment(cfg)
if err != nil {
return nil, err
}
for key, value := range baseEnv {
env[key] = value
}
return env, nil
}
// ResolveVersion resolves a version specification to a concrete version (public method)
func (m *Manager) ResolveVersion(toolName string, toolConfig config.ToolConfig) (string, error) {
return m.resolveVersion(toolName, toolConfig)
}
// resolveVersion resolves a version specification to a concrete version
func (m *Manager) resolveVersion(toolName string, toolConfig config.ToolConfig) (string, error) {
// Check for environment variable override first
if overrideVersion := getToolVersionOverride(toolName); overrideVersion != "" {
util.LogVerbose("Using version override from %s: %s", getToolVersionOverrideEnvVar(toolName), overrideVersion)
// Fast path: Check if override version is already concrete
if m.isConcreteVersion(toolName, overrideVersion) {
return overrideVersion, nil
}
// If override version needs resolution, use it instead of config version
overrideConfig := toolConfig
overrideConfig.Version = overrideVersion
return m.resolveVersionInternal(toolName, overrideConfig)
}
// Fast path: Check if version is already concrete (no resolution needed)
if m.isConcreteVersion(toolName, toolConfig.Version) {
return toolConfig.Version, nil
}
return m.resolveVersionInternal(toolName, toolConfig)
}
// resolveVersionInternal performs the actual version resolution logic
func (m *Manager) resolveVersionInternal(toolName string, toolConfig config.ToolConfig) (string, error) {
distribution := toolConfig.Distribution
// Check cache first
if cached, found := m.getCachedVersion(toolName, toolConfig.Version, distribution); found {
util.LogVerbose("Using cached version resolution: %s %s (%s) -> %s", toolName, toolConfig.Version, distribution, cached)
return cached, nil
}
util.LogVerbose("Resolving version online: %s %s (%s)", toolName, toolConfig.Version, distribution)
// Get the tool instance
tool, err := m.GetTool(toolName)
if err != nil {
return "", fmt.Errorf("unknown tool: %s", toolName)
}
// Check if tool implements VersionResolver interface
var resolved string
if resolver, ok := tool.(VersionResolver); ok {
resolved, err = resolver.ResolveVersion(toolConfig.Version, distribution)
if err != nil {
return "", err
}
} else {
// Fallback: return version as-is for tools that don't implement VersionResolver
resolved = toolConfig.Version
}
util.LogVerbose("Resolved %s %s (%s) -> %s (caching for 24h)", toolName, toolConfig.Version, distribution, resolved)
// Cache the resolved version
m.setCachedVersion(toolName, toolConfig.Version, distribution, resolved)
return resolved, nil
}
// isConcreteVersion checks if a version specification is already concrete and doesn't need resolution
func (m *Manager) isConcreteVersion(toolName, versionSpec string) bool {
// Handle special cases that always need resolution
switch versionSpec {
case "latest", "lts", "":
return false
}
// Try to parse as version specification
spec, err := version.ParseSpec(versionSpec)
if err != nil {
// If we can't parse it, assume it needs resolution
return false
}
// Only "exact" constraint versions are concrete
// "exact" means full major.minor.patch[-pre][+build] format
return spec.Constraint == "exact"
}
// GetRegistry returns the tool registry
func (m *Manager) GetRegistry() *ToolRegistry {
return m.registry
}
// loadVersionCache loads the version resolution cache from disk
func (m *Manager) loadVersionCache() {
m.cacheMutex.Lock()
defer m.cacheMutex.Unlock()
cacheFile := filepath.Join(m.cacheDir, "version_cache.json")
data, err := os.ReadFile(cacheFile)
if err != nil {
// Cache file doesn't exist or can't be read, start with empty cache
return
}
var cache map[string]VersionCacheEntry
if err := json.Unmarshal(data, &cache); err != nil {
// Invalid cache file, start with empty cache
return
}
// Filter out expired entries (older than 24 hours) and old cache versions
now := time.Now()
for key, entry := range cache {
// Skip entries with old cache version or expired entries
if entry.CacheVersion != versionCacheVersion {
continue
}
if now.Sub(entry.Timestamp) < 24*time.Hour {
m.versionCache[key] = entry
}
}
}
// saveVersionCache saves the version resolution cache to disk
func (m *Manager) saveVersionCache() {
m.cacheMutex.RLock()
defer m.cacheMutex.RUnlock()
cacheFile := filepath.Join(m.cacheDir, "version_cache.json")
data, err := json.MarshalIndent(m.versionCache, "", " ")
if err != nil {
return // Silently fail on cache save errors
}
os.WriteFile(cacheFile, data, 0644)
}
// getCachedVersion retrieves a cached version resolution
func (m *Manager) getCachedVersion(toolName, versionSpec, distribution string) (string, bool) {
m.cacheMutex.RLock()
defer m.cacheMutex.RUnlock()
key := fmt.Sprintf("%s:%s:%s", toolName, versionSpec, distribution)
entry, exists := m.versionCache[key]
if !exists {
return "", false
}
// Check if cache entry is still valid (less than 24 hours old)
if time.Since(entry.Timestamp) > 24*time.Hour {