-
-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathpython.ts
338 lines (302 loc) · 11 KB
/
python.ts
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
import assert from "assert"
import { homedir } from "os"
import { dirname, join, parse as pathParse } from "path"
import { getExecOutput } from "@actions/exec"
import ciInfo from "ci-info"
const { GITHUB_ACTIONS } = ciInfo
import { info, notice, warning } from "ci-log"
import { addPath } from "envosman"
import { execa } from "execa"
import { readdir } from "fs/promises"
import memoize from "memoizee"
import { pathExists } from "path-exists"
import { addExeExt } from "patha"
import { installAptPack } from "setup-apt"
import { installBrewPack } from "setup-brew"
import which from "which"
import { rcOptions } from "../cli-options.js"
import { hasDnf } from "../utils/env/hasDnf.js"
import { isArch } from "../utils/env/isArch.js"
import { isUbuntu } from "../utils/env/isUbuntu.js"
import type { InstallationInfo } from "../utils/setup/setupBin.js"
import { setupChocoPack } from "../utils/setup/setupChocoPack.js"
import { setupDnfPack } from "../utils/setup/setupDnfPack.js"
import { setupPacmanPack } from "../utils/setup/setupPacmanPack.js"
import { hasPipx, setupPipPackSystem, setupPipPackWithPython } from "../utils/setup/setupPipPack.js"
import { isBinUptoDate } from "../utils/setup/version.js"
import { unique } from "../utils/std/index.js"
import { getVersionDefault, isMinVersion } from "../versions/versions.js"
export async function setupPython(
version: string,
setupDir: string,
arch: string,
): Promise<InstallationInfo & { bin: string }> {
const installInfo = await findOrSetupPython(version, setupDir, arch)
assert(installInfo.bin !== undefined)
const foundPython = installInfo.bin
// setup pip
const foundPip = await findOrSetupPip(foundPython)
if (foundPip === undefined) {
throw new Error("pip was not installed correctly")
}
await setupPipx(foundPython)
await setupWheel(foundPython)
return installInfo as InstallationInfo & { bin: string }
}
async function setupPipx(foundPython: string) {
try {
if (!(await hasPipx(foundPython))) {
try {
await setupPipPackWithPython(foundPython, "pipx", undefined, { upgrade: true, usePipx: false })
} catch (err) {
if (setupPipPackSystem("pipx", false) === null) {
throw new Error(`pipx was not installed correctly ${err}`)
}
}
}
await execa(foundPython, ["-m", "pipx", "ensurepath"], { stdio: "inherit" })
await setupVenv(foundPython)
} catch (err) {
notice(`Failed to install pipx: ${(err as Error).toString()}. Ignoring...`)
}
}
async function setupVenv(foundPython: string) {
try {
await setupPipPackWithPython(foundPython, "venv", undefined, { upgrade: false, usePipx: false })
} catch (err) {
info(`Failed to install venv: ${(err as Error).toString()}. Ignoring...`)
}
}
/** Setup wheel and setuptools */
async function setupWheel(foundPython: string) {
try {
await setupPipPackWithPython(foundPython, "setuptools", undefined, {
upgrade: true,
isLibrary: true,
usePipx: false,
})
await setupPipPackWithPython(foundPython, "wheel", undefined, { upgrade: false, isLibrary: true, usePipx: false })
} catch (err) {
info(`Failed to install setuptools/wheel: ${(err as Error).toString()}. Ignoring...`)
}
}
async function findOrSetupPython(givenVersion: string, setupDir: string, arch: string): Promise<InstallationInfo> {
// if a version range specified, use the default version, and later check the range
const version = isMinVersion(givenVersion) ? "" : givenVersion
let installInfo: InstallationInfo | undefined
let foundPython = await findPython(setupDir)
if (foundPython !== undefined) {
const binDir = dirname(foundPython)
installInfo = { bin: foundPython, installDir: binDir, binDir }
} else {
// if python is not found, try to install it
if (GITHUB_ACTIONS) {
// install python in GitHub Actions
try {
info("Installing python in GitHub Actions")
const { setupActionsPython } = await import("./actions_python.js")
await setupActionsPython(version, setupDir, arch)
foundPython = await findPython(setupDir)
if (foundPython === undefined) {
throw new Error("Python binary could not be found")
}
const binDir = dirname(foundPython)
installInfo = { bin: foundPython, installDir: binDir, binDir }
} catch (err) {
warning((err as Error).toString())
}
}
if (installInfo === undefined) {
// install python via system package manager
installInfo = await setupPythonSystem(setupDir, version)
}
}
if (foundPython === undefined || installInfo.bin === undefined) {
foundPython = await findPython(setupDir)
if (foundPython === undefined) {
throw new Error("Python binary could not be found")
}
installInfo = { bin: foundPython, installDir: dirname(foundPython), binDir: dirname(foundPython) }
}
return installInfo
}
async function setupPythonSystem(setupDir: string, version: string) {
let installInfo: InstallationInfo | undefined
switch (process.platform) {
case "win32": {
if (setupDir) {
await setupChocoPack("python3", version, [`--params=/InstallDir:${setupDir}`])
} else {
await setupChocoPack("python3", version)
}
// Adding the bin dir to the path
const bin = await findPython(setupDir)
if (bin === undefined) {
throw new Error("Python binary could not be found")
}
const binDir = dirname(bin)
/** The directory which the tool is installed to */
await addPath(binDir, rcOptions)
installInfo = { installDir: binDir, binDir, bin }
break
}
case "darwin": {
installInfo = await installBrewPack("python3", version)
// add the python and pip binaries to the path
const brewPythonPrefix: {
stdout: string
stderr: string
} = await execa("brew", ["--prefix", "python"], { stdio: "pipe" })
const brewPythonBin = join(brewPythonPrefix.stdout, "libexec", "bin")
await addPath(brewPythonBin, rcOptions)
break
}
case "linux": {
if (isArch()) {
installInfo = await setupPacmanPack("python", version)
} else if (hasDnf()) {
installInfo = await setupDnfPack([{ name: "python3", version }])
} else if (isUbuntu()) {
installInfo = await installAptPack([{ name: "python3", version }, { name: "python-is-python3" }])
} else {
throw new Error("Unsupported linux distributions")
}
break
}
default: {
throw new Error("Unsupported platform")
}
}
return installInfo
}
async function findPython(binDir?: string) {
for (const pythonBin of ["python", "python3"]) {
// eslint-disable-next-line no-await-in-loop
const foundPython = await isPythonUpToDate(pythonBin, binDir)
if (foundPython !== undefined) {
return foundPython
}
}
// On Windows, search in C:\PythonXX
if (process.platform === "win32") {
const rootDir = pathParse(homedir()).root
// find all directories in rootDir using readdir
const pythonDirs = (await readdir(rootDir)).filter((dir) => dir.startsWith("Python"))
for (const pythonDir of pythonDirs) {
for (const pythonBin of ["python3", "python"]) {
// eslint-disable-next-line no-await-in-loop
const foundPython = await isPythonUpToDate(pythonBin, join(rootDir, pythonDir))
if (foundPython !== undefined) {
return foundPython
}
}
}
}
return undefined
}
async function isPythonUpToDate(candidate: string, binDir?: string) {
try {
const targetVersion = getVersionDefault("python")
if (binDir !== undefined) {
const pythonBinPath = join(binDir, addExeExt(candidate))
if (await pathExists(pythonBinPath) && await isBinUptoDate(pythonBinPath, targetVersion!)) {
return pythonBinPath
}
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
const pythonBinPaths = (await which(candidate, { nothrow: true, all: true })) ?? []
for (const pythonBinPath of pythonBinPaths) {
// eslint-disable-next-line no-await-in-loop
if (await isBinUptoDate(pythonBinPath, targetVersion!)) {
return pythonBinPath
}
}
} catch {
// fall through
}
return undefined
}
async function findOrSetupPip(foundPython: string) {
const maybePip = await findPip()
if (maybePip === undefined) {
// install pip if not installed
info("pip was not found. Installing pip")
await setupPip(foundPython)
return findPip() // recurse to check if pip is on PATH and up-to-date
}
return maybePip
}
async function findPip() {
for (const pipCandidate of ["pip3", "pip"]) {
// eslint-disable-next-line no-await-in-loop
const maybePip = await isPipUptoDate(pipCandidate)
if (maybePip !== undefined) {
return maybePip
}
}
return undefined
}
async function isPipUptoDate(pip: string) {
try {
const targetVersion = getVersionDefault("pip")
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
const pipPaths = (await which(pip, { nothrow: true, all: true })) ?? []
for (const pipPath of pipPaths) {
// eslint-disable-next-line no-await-in-loop
if (await isBinUptoDate(pipPath, targetVersion!)) {
return pipPath
}
}
} catch {
// fall through
}
return undefined
}
async function setupPip(foundPython: string) {
const upgraded = await ensurePipUpgrade(foundPython)
if (!upgraded) {
// ensure that pip is installed on Linux (happens when python is found but pip not installed)
await setupPipPackSystem("pip")
// upgrade pip
await ensurePipUpgrade(foundPython)
}
}
async function ensurePipUpgrade(foundPython: string) {
try {
await execa(foundPython, ["-m", "ensurepip", "-U", "--upgrade"], { stdio: "inherit" })
return true
} catch (err1) {
info((err1 as Error).toString())
try {
// ensure pip is disabled on Ubuntu
await execa(foundPython, ["-m", "pip", "install", "--upgrade", "pip"], { stdio: "inherit" })
return true
} catch (err2) {
info((err2 as Error).toString())
// pip module not found
}
}
// all methods failed
return false
}
async function addPythonBaseExecPrefix_(python: string) {
const dirs: string[] = []
// detection based on the platform
if (process.platform === "linux") {
dirs.push("/home/runner/.local/bin/")
} else if (process.platform === "darwin") {
dirs.push("/usr/local/bin/")
}
// detection using python.sys
const base_exec_prefix = (await getExecOutput(`${python} -c "import sys;print(sys.base_exec_prefix);"`)).stdout.trim()
// any of these are possible depending on the operating system!
dirs.push(join(base_exec_prefix, "Scripts"), join(base_exec_prefix, "Scripts", "bin"), join(base_exec_prefix, "bin"))
// remove duplicates
return unique(dirs)
}
/**
* Add the base exec prefix to the PATH. This is required for Conan, Meson, etc. to work properly.
*
* The answer is cached for subsequent calls
*/
export const addPythonBaseExecPrefix = memoize(addPythonBaseExecPrefix_, { promise: true })