| 31 | const cache = new Map(); |
| 32 | |
| 33 | export function resolvePython({ repo = null, control = null, env = process.env, platform = process.platform, exists = existsSync, starts = pythonStarts, useCache = true } = {}) { |
| 34 | const key = JSON.stringify([repo, control?.python ?? null, env.STRATA_PYTHON, env.STRATA_NATIVE_PYTHON, platform]); |
| 35 | if (useCache && cache.has(key)) return cache.get(key); |
| 36 | const found = (() => { |
| 37 | const explicit = env.STRATA_PYTHON || env.STRATA_NATIVE_PYTHON; |
| 38 | if (explicit) return { command: explicit, args: [], source: 'environment' }; |
| 39 | if (control?.python) return { command: control.python, args: [], source: 'bundled' }; |
| 40 | if (repo) { |
| 41 | const venv = venvPython(repo, platform); |
| 42 | if (exists(venv)) return { command: venv, args: [], source: 'venv' }; |
| 43 | } |
| 44 | if (platform === 'win32') { |
| 45 | if (starts('py', ['-3'])) return { command: 'py', args: ['-3'], source: 'py launcher' }; |
| 46 | if (starts('python.exe')) return { command: 'python.exe', args: [], source: 'PATH' }; |
| 47 | return { command: 'python.exe', args: [], source: 'fallback' }; |
| 48 | } |
| 49 | for (const brew of ['/opt/homebrew/bin/python3.11', '/opt/homebrew/bin/python3.10']) { |
| 50 | if (exists(brew)) return { command: brew, args: [], source: 'homebrew' }; |
| 51 | } |
| 52 | return { command: 'python3', args: [], source: 'PATH' }; |
| 53 | })(); |
| 54 | // A failed lookup (the fallback) is not cached: the person may install Python and retry. |
| 55 | if (useCache && found.source !== 'fallback') cache.set(key, found); |
| 56 | return found; |
| 57 | } |
| 58 | |
| 59 | /** A shell-ready command prefix such as `"py" -3`, for the few places that run a command string. */ |
| 60 | export function shellPrefix(python) { |