-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprovider.go
More file actions
862 lines (731 loc) · 24.7 KB
/
provider.go
File metadata and controls
862 lines (731 loc) · 24.7 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
// Package python implements the Python runtime provider for dtvem
package python
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
goruntime "runtime"
"sort"
"strconv"
"strings"
"time"
"github.com/dtvem/dtvem/src/internal/config"
"github.com/dtvem/dtvem/src/internal/constants"
"github.com/dtvem/dtvem/src/internal/download"
"github.com/dtvem/dtvem/src/internal/runtime"
"github.com/dtvem/dtvem/src/internal/shim"
"github.com/dtvem/dtvem/src/internal/ui"
)
// Provider implements the runtime.Provider interface for Python
type Provider struct {
// Configuration and state will go here
}
// NewProvider creates a new Python runtime provider
func NewProvider() *Provider {
return &Provider{}
}
// Name returns the runtime name
func (p *Provider) Name() string {
return "python"
}
// DisplayName returns the human-readable name
func (p *Provider) DisplayName() string {
return "Python"
}
// Shims returns the list of shim executables for Python
func (p *Provider) Shims() []string {
return []string{"python", "python3", "pip", "pip3"}
}
// Install downloads and installs a specific version
// downloadAndExtract downloads and extracts the Python archive
func (p *Provider) downloadAndExtract(version, downloadURL, archiveName string) (extractDir string, cleanup func(), err error) {
ui.Progress("Downloading from %s", downloadURL)
// Create temporary directory
tempDir := filepath.Join(os.TempDir(), fmt.Sprintf("dtvem-python-%s", version))
if err := os.MkdirAll(tempDir, 0755); err != nil {
return "", nil, fmt.Errorf("failed to create temp directory: %w", err)
}
cleanupFunc := func() { _ = os.RemoveAll(tempDir) }
// Download archive
archivePath := filepath.Join(tempDir, archiveName)
if err := download.File(downloadURL, archivePath); err != nil {
cleanupFunc()
return "", nil, fmt.Errorf("failed to download: %w", err)
}
// Extract archive
extractDir = filepath.Join(tempDir, "extracted")
spinner := ui.NewSpinner("Extracting archive...")
spinner.Start()
var extractErr error
if strings.HasSuffix(archiveName, ".zip") {
extractErr = download.ExtractZip(archivePath, extractDir)
} else if strings.HasSuffix(archiveName, ".tar.gz") {
extractErr = download.ExtractTarGz(archivePath, extractDir)
} else {
extractErr = fmt.Errorf("unsupported archive format: %s", archiveName)
}
if extractErr != nil {
spinner.Error("Extraction failed")
cleanupFunc()
return "", nil, fmt.Errorf("failed to extract: %w", extractErr)
}
spinner.Success("Extraction complete")
return extractDir, cleanupFunc, nil
}
// determineSourceDir determines the source directory from extracted archive
func determineSourceDir(extractDir string) string {
if goruntime.GOOS == constants.OSWindows {
// Windows embeddable: files are in extractDir root
return extractDir
}
// Unix python-build-standalone: files are in python/ subdirectory
pythonSubdir := filepath.Join(extractDir, "python")
if _, err := os.Stat(pythonSubdir); err == nil {
return pythonSubdir
}
// Fallback: use extractDir if python/ doesn't exist
return extractDir
}
// installPipIfNeeded installs pip on Windows or shows success message on Unix
func (p *Provider) installPipIfNeeded(version string) {
if goruntime.GOOS == constants.OSWindows {
// Windows embeddable packages need pip installed
pipSpinner := ui.NewSpinner("Installing pip...")
pipSpinner.Start()
if err := p.installPip(version); err != nil {
pipSpinner.Warning("Failed to install pip")
ui.Info("To install pip manually:")
ui.Info(" 1. Download: %s", p.getPipURL(version))
ui.Info(" 2. Run: python get-pip.py")
} else {
pipSpinner.Success("pip installed successfully")
}
} else {
// python-build-standalone includes pip
ui.Success("pip included")
}
}
func (p *Provider) Install(version string) error {
ui.Debug("Starting Python installation for version %s", version)
// Ensure dtvem directories exist
if err := config.EnsureDirectories(); err != nil {
return fmt.Errorf("failed to create dtvem directories: %w", err)
}
// Check if already installed
if installed, _ := p.IsInstalled(version); installed {
return fmt.Errorf("Python %s is already installed", version)
}
ui.Header("Installing Python v%s...", version)
// Get platform-specific download URL
downloadURL, archiveName, err := p.getDownloadURL(version)
if err != nil {
return fmt.Errorf("failed to get download URL: %w", err)
}
ui.Debug("Download URL: %s", downloadURL)
ui.Debug("Archive name: %s", archiveName)
// Download and extract
extractDir, cleanup, err := p.downloadAndExtract(version, downloadURL, archiveName)
if err != nil {
return err
}
defer cleanup()
// Determine source directory
sourceDir := determineSourceDir(extractDir)
ui.Debug("Source directory: %s", sourceDir)
// Get install path and move files
installPath := config.RuntimeVersionPath("python", version)
ui.Debug("Install path: %s", installPath)
if err := os.MkdirAll(filepath.Dir(installPath), 0755); err != nil {
return fmt.Errorf("failed to create install directory: %w", err)
}
ui.Debug("Moving files from %s to %s", sourceDir, installPath)
if err := os.Rename(sourceDir, installPath); err != nil {
return fmt.Errorf("failed to move to install location: %w", err)
}
// Create shims
shimSpinner := ui.NewSpinner("Creating shims...")
shimSpinner.Start()
if err := p.createShims(); err != nil {
shimSpinner.Error("Failed to create shims")
return fmt.Errorf("failed to create shims: %w", err)
}
shimSpinner.Success("Shims created")
ui.Success("Python v%s installed successfully", version)
ui.Info("Location: %s", installPath)
// Install/verify pip
p.installPipIfNeeded(version)
return nil
}
// getDownloadURL returns the download URL and archive name for a given version
func (p *Provider) getDownloadURL(version string) (string, string, error) {
// Determine platform and architecture
platform := goruntime.GOOS
arch := goruntime.GOARCH
// Construct download URL based on platform
var archiveName string
var downloadURL string
switch platform {
case constants.OSWindows:
// Use embeddable package for Windows from python.org
// Format: python-3.11.0-embed-amd64.zip
var pythonArch string
if arch == constants.ArchAMD64 {
pythonArch = constants.ArchAMD64
} else if arch == constants.ArchARM64 {
pythonArch = constants.ArchARM64
} else {
return "", "", fmt.Errorf("unsupported Windows architecture: %s", arch)
}
archiveName = fmt.Sprintf("python-%s-embed-%s.zip", version, pythonArch)
downloadURL = fmt.Sprintf("https://www.python.org/ftp/python/%s/%s", version, archiveName)
case "darwin", "linux":
// Use python-build-standalone for Unix platforms
// These are prebuilt Python binaries used by pyenv and other tools
return p.getStandaloneBuildURL(version, platform, arch)
default:
return "", "", fmt.Errorf("unsupported platform: %s", platform)
}
return downloadURL, archiveName, nil
}
// getStandaloneBuildURL constructs URL for python-build-standalone releases
func (p *Provider) getStandaloneBuildURL(version, platform, arch string) (string, string, error) {
// Map Go platform/arch to python-build-standalone naming
var pbsPlatform string
var pbsArch string
// Map architecture
switch arch {
case "amd64":
pbsArch = "x86_64"
case "arm64":
pbsArch = "aarch64"
default:
return "", "", fmt.Errorf("unsupported architecture for %s: %s", platform, arch)
}
// Map platform
switch platform {
case "darwin":
pbsPlatform = "apple-darwin"
case "linux":
pbsPlatform = "unknown-linux-gnu"
default:
return "", "", fmt.Errorf("unsupported platform: %s", platform)
}
// python-build-standalone uses a build date in the version
// We need to find the latest build for the requested Python version
// For now, we'll use a known stable build date: 20241016
buildDate := "20241016"
// Construct archive name
// Format: cpython-3.11.0+20241016-x86_64-unknown-linux-gnu-install_only.tar.gz
archiveName := fmt.Sprintf("cpython-%s+%s-%s-%s-install_only.tar.gz",
version, buildDate, pbsArch, pbsPlatform)
// Construct download URL
// https://github.com/indygreg/python-build-standalone/releases/download/20241016/cpython-...tar.gz
downloadURL := fmt.Sprintf("https://github.com/indygreg/python-build-standalone/releases/download/%s/%s",
buildDate, archiveName)
return downloadURL, archiveName, nil
}
// createShims creates shims for Python executables
func (p *Provider) createShims() error {
manager, err := shim.NewManager()
if err != nil {
return err
}
// Get the list of shims for Python
shimNames := shim.RuntimeShims("python")
// Create each shim
return manager.CreateShims(shimNames)
}
// installPip installs pip for Windows embeddable Python packages
func (p *Provider) installPip(version string) error {
pythonPath, err := p.ExecutablePath(version)
if err != nil {
return fmt.Errorf("could not find python executable: %w", err)
}
installPath := config.RuntimeVersionPath("python", version)
// For embeddable packages, we need to:
// 1. Modify python311._pth to enable site-packages
// 2. Download and run get-pip.py
// Step 1: Enable site-packages by uncommenting the import site line
pthFile := filepath.Join(installPath, fmt.Sprintf("python%s._pth", strings.Join(strings.Split(version, ".")[:2], "")))
if err := p.enableSitePackages(pthFile); err != nil {
return fmt.Errorf("failed to enable site-packages: %w", err)
}
// Step 2: Download get-pip.py (use version-specific URL for older Python)
getPipURL := p.getPipURL(version)
getPipPath := filepath.Join(installPath, "get-pip.py")
if err := download.File(getPipURL, getPipPath); err != nil {
return fmt.Errorf("failed to download get-pip.py: %w", err)
}
defer func() { _ = os.Remove(getPipPath) }()
// Step 3: Run get-pip.py
cmd := exec.Command(pythonPath, getPipPath)
cmd.Dir = installPath
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("failed to run get-pip.py: %w\nOutput: %s", err, string(output))
}
return nil
}
// getPipURL returns the appropriate get-pip.py URL for the given Python version.
// Older Python versions (3.8 and below) require version-specific URLs since the
// main get-pip.py no longer supports end-of-life Python versions.
func (p *Provider) getPipURL(version string) string {
parts := strings.Split(version, ".")
if len(parts) >= 2 && parts[0] == "3" {
minor, err := strconv.Atoi(parts[1])
if err == nil && minor <= 8 {
// Use version-specific URL for Python 3.8 and below
return fmt.Sprintf("https://bootstrap.pypa.io/pip/%s.%s/get-pip.py", parts[0], parts[1])
}
}
// Default URL for Python 3.9+
return "https://bootstrap.pypa.io/get-pip.py"
}
// enableSitePackages modifies the ._pth file to enable site-packages
func (p *Provider) enableSitePackages(pthFile string) error {
// Read the file
content, err := os.ReadFile(pthFile)
if err != nil {
return err
}
// Uncomment "import site" line or add it if missing
lines := strings.Split(string(content), "\n")
found := false
for i, line := range lines {
if strings.Contains(line, "import site") {
// Uncomment if commented
lines[i] = "import site"
found = true
break
}
}
// If not found, add it
if !found {
lines = append(lines, "import site")
}
// Write back
newContent := strings.Join(lines, "\n")
return os.WriteFile(pthFile, []byte(newContent), 0644)
}
// Uninstall removes an installed version
func (p *Provider) Uninstall(version string) error {
// TODO: Implement Python uninstallation
return fmt.Errorf("not yet implemented")
}
// ListInstalled returns all installed Python versions
func (p *Provider) ListInstalled() ([]runtime.InstalledVersion, error) {
paths := config.DefaultPaths()
pythonVersionsDir := filepath.Join(paths.Versions, "python")
// Check if directory exists
if _, err := os.Stat(pythonVersionsDir); os.IsNotExist(err) {
return []runtime.InstalledVersion{}, nil
}
// Read directory
entries, err := os.ReadDir(pythonVersionsDir)
if err != nil {
return nil, fmt.Errorf("failed to read versions directory: %w", err)
}
// Build list of installed versions
versions := make([]runtime.InstalledVersion, 0)
for _, entry := range entries {
if entry.IsDir() {
versions = append(versions, runtime.InstalledVersion{
Version: runtime.NewVersion(entry.Name()),
InstallPath: filepath.Join(pythonVersionsDir, entry.Name()),
IsGlobal: false, // TODO: Check if this is the global version
})
}
}
return versions, nil
}
// ListAvailable returns all available Python versions from python.org
func (p *Provider) ListAvailable() ([]runtime.AvailableVersion, error) {
// Fetch directory listing from python.org FTP
url := "https://www.python.org/ftp/python/"
client := &http.Client{
Timeout: 15 * time.Second,
}
resp, err := client.Get(url)
if err != nil {
return nil, fmt.Errorf("failed to fetch version list: %w", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("failed to fetch version list: HTTP %d", resp.StatusCode)
}
// Read the HTML body
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}
// Extract version numbers from directory listing
// Directory names look like: 3.11.0/, 3.12.0/, etc.
versionRegex := regexp.MustCompile(`>(\d+\.\d+\.\d+)/<`)
matches := versionRegex.FindAllStringSubmatch(string(body), -1)
versionMap := make(map[string]bool)
for _, match := range matches {
if len(match) > 1 {
version := match[1]
// Only include Python 3.x versions
if strings.HasPrefix(version, "3.") {
versionMap[version] = true
}
}
}
// Convert map to sorted slice
var versionStrings []string
for version := range versionMap {
versionStrings = append(versionStrings, version)
}
// Sort versions in descending order (newest first)
sort.Slice(versionStrings, func(i, j int) bool {
return versionStrings[i] > versionStrings[j]
})
// Convert to AvailableVersion format
versions := make([]runtime.AvailableVersion, 0, len(versionStrings))
for i, v := range versionStrings {
notes := ""
if i == 0 {
notes = "Latest"
}
versions = append(versions, runtime.AvailableVersion{
Version: runtime.NewVersion(v),
Notes: notes,
})
}
return versions, nil
}
// ExecutablePath returns the path to the Python executable
func (p *Provider) ExecutablePath(version string) (string, error) {
installPath, err := p.InstallPath(version)
if err != nil {
return "", err
}
// Determine executable name and path based on platform
var pythonPath string
if goruntime.GOOS == constants.OSWindows {
// Windows embeddable package has python.exe in root
pythonPath = filepath.Join(installPath, "python.exe")
} else {
// Unix has python in bin/
pythonPath = filepath.Join(installPath, "bin", "python")
}
// Verify executable exists
if _, err := os.Stat(pythonPath); os.IsNotExist(err) {
return "", fmt.Errorf("python executable not found at %s", pythonPath)
}
return pythonPath, nil
}
// IsInstalled checks if a version is installed
func (p *Provider) IsInstalled(version string) (bool, error) {
installPath := config.RuntimeVersionPath("python", version)
_, err := os.Stat(installPath)
if os.IsNotExist(err) {
return false, nil
}
if err != nil {
return false, err
}
return true, nil
}
// GetInstallPath returns the installation directory for a version
func (p *Provider) InstallPath(version string) (string, error) {
return config.RuntimeVersionPath("python", version), nil
}
// GlobalVersion returns the globally configured version
func (p *Provider) GlobalVersion() (string, error) {
return config.GlobalVersion("python")
}
// SetGlobalVersion sets the global default version
func (p *Provider) SetGlobalVersion(version string) error {
return config.SetGlobalVersion("python", version)
}
// GetLocalVersion returns the locally configured version
func (p *Provider) LocalVersion() (string, error) {
// Try to find local version file
version, err := config.ResolveVersion("python")
if err != nil {
return "", err
}
return version, nil
}
// SetLocalVersion sets the local version for current directory
func (p *Provider) SetLocalVersion(version string) error {
return config.SetLocalVersion("python", version)
}
// GetCurrentVersion returns the currently active version
func (p *Provider) CurrentVersion() (string, error) {
return config.ResolveVersion("python")
}
// DetectInstalled scans the system for existing Python installations
func (p *Provider) DetectInstalled() ([]runtime.DetectedVersion, error) {
detected := make([]runtime.DetectedVersion, 0)
seen := make(map[string]bool) // Track unique paths to avoid duplicates
// 1. Check python and python3 in PATH
for _, cmd := range []string{"python", "python3"} {
if pythonPath, err := exec.LookPath(cmd); err == nil {
if version, err := getPythonVersion(pythonPath); err == nil {
if !seen[pythonPath] {
detected = append(detected, runtime.DetectedVersion{
Version: version,
Path: pythonPath,
Source: "system",
Validated: true,
})
seen[pythonPath] = true
}
}
}
}
// 2. Check common installation locations
locations := getPythonInstallLocations()
for _, loc := range locations {
if _, err := os.Stat(loc); err == nil {
if version, err := getPythonVersion(loc); err == nil {
if !seen[loc] {
detected = append(detected, runtime.DetectedVersion{
Version: version,
Path: loc,
Source: "system",
Validated: true,
})
seen[loc] = true
}
}
}
}
// 3. Check pyenv installations
pyenvVersions := findPyenvVersions()
for _, dv := range pyenvVersions {
if !seen[dv.Path] {
detected = append(detected, dv)
seen[dv.Path] = true
}
}
return detected, nil
}
// getPythonVersion runs 'python --version' and returns the version
func getPythonVersion(pythonPath string) (string, error) {
cmd := exec.Command(pythonPath, "--version")
output, err := cmd.Output()
if err != nil {
return "", err
}
version := strings.TrimSpace(string(output))
// Output format: "Python 3.11.0" - extract just the version number
re := regexp.MustCompile(`Python\s+(\d+\.\d+\.\d+)`)
matches := re.FindStringSubmatch(version)
if len(matches) >= 2 {
return matches[1], nil
}
return "", fmt.Errorf("could not parse Python version from: %s", version)
}
// getPythonInstallLocations returns common Python installation paths
func getPythonInstallLocations() []string {
home, _ := os.UserHomeDir()
locations := []string{
// Windows - check multiple Python versions
`C:\Python311\python.exe`,
`C:\Python310\python.exe`,
`C:\Python39\python.exe`,
`C:\Python38\python.exe`,
`C:\Python37\python.exe`,
// macOS (Homebrew and system)
"/usr/local/bin/python3",
"/opt/homebrew/bin/python3",
"/usr/bin/python3",
// Linux
"/usr/bin/python3",
"/usr/local/bin/python3",
}
// Windows - check LocalAppData\Programs\Python
if home != "" {
pythonLocalDir := filepath.Join(home, "AppData", "Local", "Programs", "Python")
if entries, err := os.ReadDir(pythonLocalDir); err == nil {
for _, entry := range entries {
if entry.IsDir() {
pythonExe := filepath.Join(pythonLocalDir, entry.Name(), "python.exe")
locations = append(locations, pythonExe)
}
}
}
// macOS/Linux user installs
locations = append(locations,
filepath.Join(home, ".local", "bin", "python3"),
)
}
return locations
}
// findPyenvVersions scans pyenv directory for installed versions
func findPyenvVersions() []runtime.DetectedVersion {
detected := make([]runtime.DetectedVersion, 0)
home, err := os.UserHomeDir()
if err != nil {
return detected
}
// Check pyenv directory
pyenvDir := filepath.Join(home, ".pyenv", "versions")
if entries, err := os.ReadDir(pyenvDir); err == nil {
versionRegex := regexp.MustCompile(`^\d+\.\d+\.\d+$`)
for _, entry := range entries {
if entry.IsDir() && versionRegex.MatchString(entry.Name()) {
versionDir := filepath.Join(pyenvDir, entry.Name())
// Try both Unix and Windows paths
pythonPaths := []string{
filepath.Join(versionDir, "bin", "python"),
filepath.Join(versionDir, "bin", "python3"),
filepath.Join(versionDir, "python.exe"),
}
for _, pythonPath := range pythonPaths {
if _, err := os.Stat(pythonPath); err == nil {
detected = append(detected, runtime.DetectedVersion{
Version: entry.Name(),
Path: pythonPath,
Source: "pyenv",
Validated: false,
})
break
}
}
}
}
}
// Check Windows pyenv directory
pyenvWinDir := filepath.Join(home, ".pyenv", "pyenv-win", "versions")
if entries, err := os.ReadDir(pyenvWinDir); err == nil {
versionRegex := regexp.MustCompile(`^\d+\.\d+\.\d+`)
for _, entry := range entries {
if entry.IsDir() && versionRegex.MatchString(entry.Name()) {
versionDir := filepath.Join(pyenvWinDir, entry.Name())
pythonPath := filepath.Join(versionDir, "python.exe")
if _, err := os.Stat(pythonPath); err == nil {
detected = append(detected, runtime.DetectedVersion{
Version: entry.Name(),
Path: pythonPath,
Source: "pyenv",
Validated: false,
})
}
}
}
}
return detected
}
// GetGlobalPackages detects globally installed pip packages
func (p *Provider) GlobalPackages(installPath string) ([]string, error) {
// Find pip executable in the installation
pipPath := findPipInInstall(installPath)
if pipPath == "" {
return nil, fmt.Errorf("pip not found in installation")
}
// Run pip list --format=json
cmd := exec.Command(pipPath, "list", "--format=json")
output, err := cmd.Output()
if err != nil {
return nil, fmt.Errorf("failed to list pip packages: %w", err)
}
// Parse JSON output
var packages []struct {
Name string `json:"name"`
Version string `json:"version"`
}
if err := json.Unmarshal(output, &packages); err != nil {
return nil, fmt.Errorf("failed to parse pip list output: %w", err)
}
// Extract package names (exclude pip and setuptools which are built-in)
packageNames := make([]string, 0, len(packages))
for _, pkg := range packages {
name := strings.ToLower(pkg.Name)
if name != "pip" && name != "setuptools" && name != "wheel" {
packageNames = append(packageNames, pkg.Name)
}
}
return packageNames, nil
}
// InstallGlobalPackages reinstalls global packages to a specific version
func (p *Provider) InstallGlobalPackages(version string, packages []string) error {
if len(packages) == 0 {
return nil
}
// Get executable path for this version
execPath, err := p.ExecutablePath(version)
if err != nil {
return err
}
// Find pip in the same installation
installDir := filepath.Dir(execPath)
pipPath := findPipInInstall(installDir)
if pipPath == "" {
return fmt.Errorf("pip not found in installation")
}
// Install all packages at once
args := append([]string{"install"}, packages...)
cmd := exec.Command(pipPath, args...)
// Capture output for errors
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("pip install failed: %w\n%s", err, string(output))
}
return nil
}
// GetManualPackageInstallCommand returns the command for manually installing packages
func (p *Provider) ManualPackageInstallCommand(packages []string) string {
if len(packages) == 0 {
return ""
}
return fmt.Sprintf("pip install %s", strings.Join(packages, " "))
}
// findPipInInstall finds the pip executable in an installation directory
func findPipInInstall(installDir string) string {
// Common locations to check
searchPaths := []string{
installDir, // Same directory
filepath.Join(installDir, "bin"), // Unix bin/
filepath.Join(installDir, "Scripts"), // Python Scripts/ (Windows)
filepath.Join(installDir, "..", "Scripts"), // Alternative Scripts location
}
// On Windows, try with .exe extension
if goruntime.GOOS == constants.OSWindows {
for _, searchPath := range searchPaths {
exePath := filepath.Join(searchPath, "pip.exe")
if _, err := os.Stat(exePath); err == nil {
return exePath
}
}
} else {
// On Unix, check without extension
for _, searchPath := range searchPaths {
execPath := filepath.Join(searchPath, "pip")
if _, err := os.Stat(execPath); err == nil {
return execPath
}
}
}
return ""
}
// ShouldReshimAfter checks if the given command should trigger a reshim.
// Returns true if the command installs or uninstalls packages.
func (p *Provider) ShouldReshimAfter(shimName string, args []string) bool {
// pip, pip3 can install packages with executables
if shimName != "pip" && shimName != "pip3" {
return false
}
// Need at least one argument (the command)
if len(args) == 0 {
return false
}
// Check if this is an install or uninstall command
cmd := args[0]
return cmd == "install" || cmd == "uninstall"
}
// init registers the Python provider on package load
func init() {
if err := runtime.Register(NewProvider()); err != nil {
panic(fmt.Sprintf("failed to register Python provider: %v", err))
}
}