返回 last30days-skill
python.go
根目录 / mcp / internal / engine / python.go
1 package engine
2
3 import (
4 "context"
5 "fmt"
6 "io"
7 "os"
8 "os/exec"
9 "path/filepath"
10 "runtime"
11 "sort"
12 "strconv"
13 "strings"
14 "time"
15 )
16
17 // PythonEnvOverride selects an interpreter without changing the host PATH.
18 const PythonEnvOverride = "LAST30DAYS_PYTHON"
19
20 func resolvePython(override string) (string, error) {
21 return resolvePythonContext(context.Background(), override)
22 }
23
24 func resolvePythonContext(ctx context.Context, override string) (string, error) {
25 return resolvePythonWithCandidates(ctx, override, pythonCandidates)
26 }
27
28 func resolvePythonWithCandidates(ctx context.Context, override string, candidatesInDir func(string) []string) (string, error) {
29 // Preserve the trusted injection seam used by embedded callers and tests.
30 if override != "" {
31 return override, nil
32 }
33 ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
34 defer cancel()
35 if candidate, configured := os.LookupEnv(PythonEnvOverride); configured {
36 if candidate == "" {
37 return "", fmt.Errorf("engine: %s is set but empty", PythonEnvOverride)
38 }
39 path, err := discoveryOperation(ctx, func() (string, error) { return exec.LookPath(candidate) })
40 if err == nil && !filepath.IsAbs(path) {
41 err = fmt.Errorf("relative executable paths are not allowed")
42 }
43 if err == nil {
44 err = checkPythonVersion(ctx, path)
45 }
46 if err != nil {
47 return "", fmt.Errorf("engine: %s=%q: %w; need Python %s+, install from %s", PythonEnvOverride, candidate, err, MinPythonVersion, PythonInstallURL)
48 }
49 return path, nil
50 }
51 var failures []string
52 for _, dir := range filepath.SplitList(os.Getenv("PATH")) {
53 if !filepath.IsAbs(dir) {
54 continue
55 }
56 candidates, err := discoveryOperation(ctx, func() ([]string, error) { return candidatesInDir(dir), nil })
57 if err != nil {
58 break
59 }
60 for _, candidate := range candidates {
61 if ctx.Err() != nil {
62 break
63 }
64 path, err := discoveryOperation(ctx, func() (string, error) { return exec.LookPath(candidate) })
65 if err == nil {
66 err = checkPythonVersion(ctx, path)
67 }
68 if err == nil {
69 return path, nil
70 }
71 failures = append(failures, fmt.Sprintf("%s: %v", candidate, err))
72 }
73 }
74 if err := ctx.Err(); err != nil {
75 return "", fmt.Errorf("engine: python discovery interrupted (need Python %s+; set %s to a compatible executable); checked: %s: %w", MinPythonVersion, PythonEnvOverride, strings.Join(failures, "; "), err)
76 }
77 return "", fmt.Errorf("engine: no compatible %s on PATH (need Python %s+; set %s to a compatible executable, or install from %s); checked: %s", DefaultPythonBinary, MinPythonVersion, PythonEnvOverride, PythonInstallURL, strings.Join(failures, "; "))
78 }
79
80 // Windows filenames are case-insensitive, so Python3.exe and python3.EXE must
81 // match the same candidate rules as python3.exe.
82 var caseInsensitiveNames = runtime.GOOS == "windows"
83
84 func pythonStem(name string) string {
85 if caseInsensitiveNames {
86 name = strings.ToLower(name)
87 }
88 return strings.TrimSuffix(name, ".exe")
89 }
90
91 // Keep PATH precedence, prefer python3 in each directory, then versioned names.
92 // Discover version suffixes rather than freezing the list at today's release.
93 // Empty and relative PATH entries are excluded even with GODEBUG=execerrdot=0.
94 func pythonCandidates(pathValue string) []string {
95 var candidates []string
96 seen := map[string]bool{}
97 for _, dir := range filepath.SplitList(pathValue) {
98 if !filepath.IsAbs(dir) {
99 continue
100 }
101 entries, err := os.ReadDir(dir)
102 if err != nil {
103 continue
104 }
105 var names []string
106 for _, entry := range entries {
107 if entry.IsDir() {
108 continue
109 }
110 name := entry.Name()
111 stem := pythonStem(name)
112 if stem == "python3" || stem == "python" {
113 names = append(names, name)
114 continue
115 }
116 if strings.HasPrefix(stem, "python3.") {
117 minor, err := strconv.Atoi(strings.TrimPrefix(stem, "python3."))
118 if err == nil && minor >= 12 {
119 names = append(names, name)
120 }
121 }
122 }
123 sort.SliceStable(names, func(i, j int) bool {
124 rank := func(name string) int {
125 stem := pythonStem(name)
126 if stem == "python3" {
127 return 1000000
128 }
129 if stem == "python" {
130 return -1
131 }
132 minor, _ := strconv.Atoi(strings.TrimPrefix(stem, "python3."))
133 return minor
134 }
135 return rank(names[i]) > rank(names[j])
136 })
137 for _, name := range names {
138 candidate := filepath.Join(dir, name)
139 if !seen[candidate] {
140 candidates = append(candidates, candidate)
141 seen[candidate] = true
142 }
143 }
144 }
145 return candidates
146 }
147
148 func checkPythonVersion(ctx context.Context, path string) error {
149 probeCtx, cancel := context.WithTimeout(ctx, 2*time.Second)
150 defer cancel()
151 // Avoid site initialization and PYTHON* environment overrides during discovery.
152 cmd := exec.CommandContext(probeCtx, path, "-I", "-S", "-c", "import sys; print('%d.%d' % sys.version_info[:2])")
153 cmd.WaitDelay = 100 * time.Millisecond
154 stdout := newHeadBuffer(maxPythonProbeOutputBytes)
155 cmd.Stdout = stdout
156 cmd.Stderr = io.Discard
157 err := cmd.Run()
158 if probeCtx.Err() != nil {
159 return probeCtx.Err()
160 }
161 if stdout.Truncated() {
162 return fmt.Errorf("version probe output exceeded %d bytes", maxPythonProbeOutputBytes)
163 }
164 if err != nil {
165 return fmt.Errorf("version probe failed: %w", err)
166 }
167 raw := strings.TrimSpace(string(stdout.Bytes()))
168 parts := strings.Split(raw, ".")
169 if len(parts) != 2 {
170 return fmt.Errorf("invalid Python version response")
171 }
172 major, majorErr := strconv.Atoi(parts[0])
173 minor, minorErr := strconv.Atoi(parts[1])
174 if majorErr != nil || minorErr != nil || major != 3 || minor < 12 {
175 display := raw
176 if len(display) > 64 {
177 display = display[:64] + "..."
178 }
179 return fmt.Errorf("incompatible Python version %q", display)
180 }
181 return nil
182 }
183
184 // Filesystem calls cannot be interrupted by context. A buffered worker lets the
185 // caller honor cancellation without waiting for a stalled mount. Discovery is
186 // sequential, so at most one filesystem operation is left pending per request.
187 func discoveryOperation[T any](ctx context.Context, operation func() (T, error)) (T, error) {
188 type result struct {
189 value T
190 err error
191 }
192 if err := ctx.Err(); err != nil {
193 var zero T
194 return zero, err
195 }
196 done := make(chan result, 1)
197 go func() { value, err := operation(); done <- result{value, err} }()
198 select {
199 case <-ctx.Done():
200 var zero T
201 return zero, ctx.Err()
202 case r := <-done:
203 return r.value, r.err
204 }
205 }
206
206 lines GO