-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathbuild-bootstrap-python.mjs
More file actions
351 lines (307 loc) · 12.1 KB
/
Copy pathbuild-bootstrap-python.mjs
File metadata and controls
351 lines (307 loc) · 12.1 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
#!/usr/bin/env node
/**
* Build a minimal bootstrap Python environment with pygit2 for Comfy Desktop.
*
* Downloads python-build-standalone (stripped), installs pygit2 using the
* just-extracted interpreter, and aggressively strips unnecessary files to
* produce a ~50 MB environment that provides git operations via pygit2.
*
* No system Python is required to run this script — the downloaded standalone
* interpreter is used for all Python invocations.
*
* Usage:
* node build-bootstrap-python.mjs [--output DIR] [--platform PLATFORM]
*
* Platforms: win-x64, mac-arm64, linux-x64
*/
import { spawnSync } from 'node:child_process'
import { createWriteStream } from 'node:fs'
import fs from 'node:fs/promises'
import os from 'node:os'
import path from 'node:path'
import { Readable } from 'node:stream'
import { pipeline } from 'node:stream/promises'
// Match the standalone environment versions
const PYTHON_VERSION = '3.13.12'
const PBS_RELEASE = '20260211'
// uv is bundled so adopted-install flows (and any future bootstrap-driven
// venv ops) have a managed package installer without depending on a system
// uv or installing one into the user's environment. Pinned; bump together
// with a new bootstrap-v* release tag.
const UV_VERSION = '0.11.18'
const PLATFORM_MAP = {
'win-x64': {
archive: `cpython-${PYTHON_VERSION}+${PBS_RELEASE}-x86_64-pc-windows-msvc-install_only_stripped.tar.gz`,
pythonBin: 'python.exe',
// uv release asset + the binary name inside it, plus where it lands in
// the bootstrap env. Windows zip is flat; unix tarballs put binaries
// under a uv-<triple>/ subdir.
uvAsset: 'uv-x86_64-pc-windows-msvc.zip',
uvBinName: 'uv.exe',
uvArchiveSubdir: null,
uvDestRel: 'uv.exe', // next to python.exe at env root
},
'mac-arm64': {
archive: `cpython-${PYTHON_VERSION}+${PBS_RELEASE}-aarch64-apple-darwin-install_only_stripped.tar.gz`,
pythonBin: path.join('bin', 'python3'),
uvAsset: 'uv-aarch64-apple-darwin.tar.gz',
uvBinName: 'uv',
uvArchiveSubdir: 'uv-aarch64-apple-darwin',
uvDestRel: path.join('bin', 'uv'), // next to bin/python3
},
'linux-x64': {
archive: `cpython-${PYTHON_VERSION}+${PBS_RELEASE}-x86_64-unknown-linux-gnu-install_only_stripped.tar.gz`,
pythonBin: path.join('bin', 'python3'),
uvAsset: 'uv-x86_64-unknown-linux-gnu.tar.gz',
uvBinName: 'uv',
uvArchiveSubdir: 'uv-x86_64-unknown-linux-gnu',
uvDestRel: path.join('bin', 'uv'),
},
}
const PBS_URL_BASE = `https://github.com/astral-sh/python-build-standalone/releases/download/${PBS_RELEASE}`
const UV_URL_BASE = `https://github.com/astral-sh/uv/releases/download/${UV_VERSION}`
const STRIP_DIRS = new Set([
'test', 'tests', '__pycache__',
'idle_test', 'idlelib', 'tkinter', 'turtledemo',
'ensurepip', 'venv',
'lib2to3', 'pydoc_data',
'unittest',
'tcl', 'tk',
'libs',
])
const STRIP_TOP_LEVEL = [
/^pip$/i, /^pip-.*/i, /^setuptools$/i, /^setuptools-.*/i,
/^_distutils_hack$/i, /^distutils$/i,
/^pkg_resources$/i,
]
const STRIP_EXTENSIONS = ['.pyc', '.pyo', '.a', '.lib']
const STRIP_FILES = new Set([
'tcl86t.dll', 'tk86t.dll', 'sqlite3.dll',
'_testcapi.pyd', '_tkinter.pyd', '_sqlite3.pyd',
])
function detectPlatform() {
const sys = process.platform
if (sys === 'win32') return 'win-x64'
if (sys === 'darwin') return 'mac-arm64'
if (sys === 'linux') return 'linux-x64'
throw new Error(`Unsupported platform: ${sys} ${process.arch}`)
}
function parseArgs(argv) {
const args = { output: 'bootstrap-python', platform: null }
for (let i = 0; i < argv.length; i++) {
const a = argv[i]
if (a === '--output') args.output = argv[++i]
else if (a === '--platform') args.platform = argv[++i]
else if (a === '-h' || a === '--help') {
console.log('Usage: node build-bootstrap-python.mjs [--output DIR] [--platform PLATFORM]')
process.exit(0)
}
}
return args
}
async function downloadFile(url, dest) {
console.log(`Downloading ${url}`)
const res = await fetch(url, { redirect: 'follow' })
if (!res.ok || !res.body) {
throw new Error(`Download failed: ${res.status} ${res.statusText}`)
}
await pipeline(Readable.fromWeb(res.body), createWriteStream(dest))
const stat = await fs.stat(dest)
console.log(` -> ${(stat.size / 1048576).toFixed(1)} MB`)
}
function extractArchive(archivePath, destDir) {
// `tar -xf` (no -z) auto-detects format on every platform: gzip tarballs
// (PBS + uv unix assets) and zip archives (uv Windows asset, via the
// bsdtar/libarchive that ships as tar.exe on Windows 10+). tar.exe is
// available on every supported builder.
const result = spawnSync('tar', ['-xf', archivePath, '-C', destDir], { stdio: 'inherit' })
if (result.error) throw result.error
if (result.status !== 0) throw new Error(`archive extraction failed (status ${result.status})`)
}
async function installUv(plat, platInfo, envDir, tmpdir) {
console.log(`Installing uv ${UV_VERSION}...`)
const archivePath = path.join(tmpdir, platInfo.uvAsset)
await downloadFile(`${UV_URL_BASE}/${platInfo.uvAsset}`, archivePath)
const uvExtractDir = path.join(tmpdir, 'uv-extract')
await fs.mkdir(uvExtractDir, { recursive: true })
extractArchive(archivePath, uvExtractDir)
const srcBin = platInfo.uvArchiveSubdir
? path.join(uvExtractDir, platInfo.uvArchiveSubdir, platInfo.uvBinName)
: path.join(uvExtractDir, platInfo.uvBinName)
if (!(await isFile(srcBin))) {
throw new Error(`uv binary not found at expected path after extract: ${srcBin}`)
}
const destBin = path.join(envDir, platInfo.uvDestRel)
await fs.mkdir(path.dirname(destBin), { recursive: true })
await fs.copyFile(srcBin, destBin)
if (plat !== 'win-x64') {
await fs.chmod(destBin, 0o755)
}
// Smoke-test the installed binary. Failing here surfaces a corrupt /
// wrong-arch uv before it ships, instead of a runtime error on user
// machines. Include `.error.message` because a launch failure (ENOENT /
// EACCES / wrong arch) leaves status=null and stdout/stderr=undefined.
const versionRes = spawnSync(destBin, ['--version'], { stdio: 'pipe', encoding: 'utf8' })
if (versionRes.status !== 0) {
const detail = versionRes.error?.message || versionRes.stderr || versionRes.stdout || `exit status ${versionRes.status}`
throw new Error(`uv --version failed: ${detail}`)
}
console.log(` ${versionRes.stdout.trim()} -> ${destBin}`)
}
async function findSitePackages(envDir) {
// Windows-style layout (Lib/site-packages)
const winSp = path.join(envDir, 'Lib', 'site-packages')
if (await isDir(winSp)) return winSp
// Unix-style layout (lib/python3.X/site-packages)
const libDir = path.join(envDir, 'lib')
if (await isDir(libDir)) {
for (const entry of await fs.readdir(libDir)) {
if (entry.startsWith('python')) {
const sp = path.join(libDir, entry, 'site-packages')
if (await isDir(sp)) return sp
}
}
}
return null
}
async function isDir(p) {
try { return (await fs.stat(p)).isDirectory() } catch { return false }
}
async function isFile(p) {
try { return (await fs.stat(p)).isFile() } catch { return false }
}
async function stripEnvironment(envDir) {
let removed = 0
// Remove directories by name anywhere in the tree (bottom-up)
async function walkDirsBottomUp(dir) {
const entries = await fs.readdir(dir, { withFileTypes: true })
for (const e of entries) {
const full = path.join(dir, e.name)
if (e.isDirectory()) {
if (STRIP_DIRS.has(e.name)) {
await fs.rm(full, { recursive: true, force: true })
removed++
} else {
await walkDirsBottomUp(full)
}
}
}
}
await walkDirsBottomUp(envDir)
// Remove specific top-level packages from site-packages
const sitePackages = await findSitePackages(envDir)
if (sitePackages) {
for (const entry of await fs.readdir(sitePackages)) {
if (STRIP_TOP_LEVEL.some((re) => re.test(entry))) {
await fs.rm(path.join(sitePackages, entry), { recursive: true, force: true })
removed++
}
}
}
// Remove files by extension and by name
async function walkFiles(dir) {
const entries = await fs.readdir(dir, { withFileTypes: true })
for (const e of entries) {
const full = path.join(dir, e.name)
if (e.isDirectory()) {
await walkFiles(full)
} else if (e.isFile()) {
if (STRIP_EXTENSIONS.some((ext) => e.name.endsWith(ext)) || STRIP_FILES.has(e.name)) {
await fs.unlink(full)
removed++
}
}
}
}
await walkFiles(envDir)
// Remove share/ and include/ directories at top level
for (const sub of ['share', 'include']) {
const full = path.join(envDir, sub)
if (await isDir(full)) {
await fs.rm(full, { recursive: true, force: true })
removed++
}
}
console.log(` Stripped ${removed} items`)
}
async function getDirSizeMb(p) {
let total = 0
async function walk(dir) {
const entries = await fs.readdir(dir, { withFileTypes: true })
for (const e of entries) {
const full = path.join(dir, e.name)
if (e.isDirectory()) await walk(full)
else if (e.isFile()) total += (await fs.stat(full)).size
}
}
await walk(p)
return total / 1048576
}
function runPython(pythonPath, args, opts = {}) {
const result = spawnSync(pythonPath, args, { stdio: opts.capture ? 'pipe' : 'inherit', encoding: 'utf8' })
if (result.error) throw result.error
return result
}
async function main() {
const args = parseArgs(process.argv.slice(2))
const plat = args.platform || detectPlatform()
const platInfo = PLATFORM_MAP[plat]
if (!platInfo) throw new Error(`Unknown platform: ${plat}`)
const outputDir = path.join(args.output, plat)
console.log(`Building bootstrap Python for ${plat}`)
console.log(` Python ${PYTHON_VERSION}, PBS release ${PBS_RELEASE}`)
// Clean output
if (await isDir(outputDir)) await fs.rm(outputDir, { recursive: true, force: true })
const tmpdir = await fs.mkdtemp(path.join(os.tmpdir(), 'bootstrap-py-'))
try {
const archivePath = path.join(tmpdir, platInfo.archive)
await downloadFile(`${PBS_URL_BASE}/${platInfo.archive}`, archivePath)
console.log('Extracting...')
extractArchive(archivePath, tmpdir)
const extracted = path.join(tmpdir, 'python')
if (!(await isDir(extracted))) {
throw new Error(`Expected 'python/' directory in archive, not found in ${tmpdir}`)
}
const pythonPath = path.join(extracted, platInfo.pythonBin)
if (plat !== 'win-x64') {
await fs.chmod(pythonPath, 0o755)
}
console.log('Installing pygit2...')
const installRes = runPython(pythonPath, ['-m', 'pip', 'install', '--no-cache-dir', 'pygit2'])
if (installRes.status !== 0) throw new Error('pip install pygit2 failed')
const verifyRes = runPython(pythonPath, ['-c', "import pygit2; print(f'pygit2 {pygit2.__version__}')"], { capture: true })
if (verifyRes.status !== 0) {
console.error(`ERROR: pygit2 import failed: ${verifyRes.stderr}`)
process.exit(1)
}
console.log(` ${verifyRes.stdout.trim()}`)
console.log('Stripping unnecessary files...')
const preSize = await getDirSizeMb(extracted)
await stripEnvironment(extracted)
const postSize = await getDirSizeMb(extracted)
console.log(` ${preSize.toFixed(1)} MB -> ${postSize.toFixed(1)} MB`)
const verifyRes2 = runPython(pythonPath, ['-c', "import pygit2; print('OK')"], { capture: true })
if (verifyRes2.status !== 0) {
console.error(`ERROR: pygit2 broken after stripping: ${verifyRes2.stderr}`)
process.exit(1)
}
// uv lands after stripping so the strip rules don't touch the binary.
await installUv(plat, platInfo, extracted, tmpdir)
await fs.mkdir(path.dirname(outputDir), { recursive: true })
await fs.rename(extracted, outputDir).catch(async (err) => {
// Cross-device rename can fail; fall back to copy.
if (err.code === 'EXDEV') {
await fs.cp(extracted, outputDir, { recursive: true })
} else {
throw err
}
})
console.log(`\nBootstrap Python ready: ${outputDir} (${(await getDirSizeMb(outputDir)).toFixed(1)} MB)`)
} finally {
await fs.rm(tmpdir, { recursive: true, force: true })
}
}
main().catch((err) => {
console.error(err)
process.exit(1)
})