build-exe-for-python-sdk.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. /**
  2. * Build the dsh executables and development Node carrier for the Python runtime wheel. The fixed
  3. * `@yao-pkg/pkg --sea` route, deploy flags, and artifact layout are owned by
  4. * .agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md.
  5. * The staged closure is symlink-free, and whole-tree assets cover Cordis's
  6. * runtime imports that pkg cannot discover statically.
  7. */
  8. import { spawn } from 'node:child_process'
  9. import { existsSync, statSync } from 'node:fs'
  10. import { chmod, copyFile, cp, lstat, mkdir, readFile, readdir, realpath, rm, writeFile } from 'node:fs/promises'
  11. import { basename, dirname, join, resolve, sep } from 'node:path'
  12. import { parseArgs } from 'node:util'
  13. import { resolveLinuxNodePtyAddon } from './build-exe-for-python-sdk-native-pty.ts'
  14. const root = resolve(import.meta.dirname, '..')
  15. /** The closure manifest whose dependencies define the executable. */
  16. const DEPLOY_ROOT_PACKAGE = 'dsh-python-runtime-closure'
  17. /** The sole application launcher inside the deployed closure. */
  18. const ENTRY_BIN = 'node_modules/@deepseek-ai/dsh/lib/bin.js'
  19. /** Python-visible executable basename. */
  20. const OUTPUT_BASENAME = 'deepseek-harness-sdk-runtime'
  21. /** Default Node major; SEA mode requires at least Node 22. */
  22. const DEFAULT_NODE_RANGE = 'node24'
  23. /** Pinned for reproducible builds. */
  24. const PKG_SPEC = '@yao-pkg/pkg@6.21.0'
  25. const OUT_DIR = 'dist-exe'
  26. /** Python package destination; created when absent. */
  27. const PYTHON_RUNTIME_DIR = 'python/sdk-runtime/src/deepseek_harness_runtime/runtime'
  28. /** The deployed closure doubles as the node-mode carrier. */
  29. const PYTHON_NODE_SUBDIR = 'node'
  30. /** Legacy deploy may hoist peer-specialized workspace packages back here. */
  31. const DEPLOY_SOURCE_NODE_MODULES = 'python/sdk-runtime/node_modules'
  32. /** Documentation excluded from the generated runtime directory. */
  33. const DEPLOY_ONLY_DOCS = ['README.md', 'README.zh.md', 'README.i18n.yaml']
  34. /**
  35. * Whole-tree assets cover Cordis's runtime bare-package imports, which pkg's
  36. * static analysis cannot see. Package manifests are explicit because bare-name
  37. * resolution depends on them.
  38. */
  39. const ASSET_GLOBS = [
  40. 'package.json',
  41. 'node_modules/**/*.js',
  42. 'node_modules/**/*.cjs',
  43. 'node_modules/**/*.mjs',
  44. 'node_modules/**/package.json',
  45. 'node_modules/**/*.json',
  46. 'node_modules/**/*.md',
  47. 'node_modules/**/*.dylib',
  48. 'node_modules/**/*.dll',
  49. 'node_modules/**/*.node',
  50. 'node_modules/**/*.so',
  51. 'node_modules/**/*.so.*',
  52. 'node_modules/**/*.wasm',
  53. 'node_modules/**/*.yaml',
  54. 'node_modules/**/*.yml',
  55. ]
  56. const PLATFORMS = ['linux', 'macos'] as const
  57. const ARCHES = ['x64', 'arm64'] as const
  58. type Platform = (typeof PLATFORMS)[number]
  59. type Arch = (typeof ARCHES)[number]
  60. function isPlatform(value: string): value is Platform {
  61. return (PLATFORMS as readonly string[]).includes(value)
  62. }
  63. function isArch(value: string): value is Arch {
  64. return (ARCHES as readonly string[]).includes(value)
  65. }
  66. /**
  67. * A parsed pkg target triple, constructed from `--targets` or the host.
  68. */
  69. class Target {
  70. private constructor(
  71. /** pkg Node range (`node<major>`). */
  72. readonly nodeRange: string,
  73. /**
  74. * pkg platform tag. Windows is a documented non-goal
  75. * (.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md).
  76. */
  77. readonly platform: Platform,
  78. /** pkg CPU tag. */
  79. readonly arch: Arch,
  80. ) {}
  81. /** The pkg `--targets` spec string `<nodeRange>-<platform>-<arch>`. */
  82. get spec(): string {
  83. return `${this.nodeRange}-${this.platform}-${this.arch}`
  84. }
  85. /**
  86. * Parse one target spec, rejecting malformed triples and unsupported platform or architecture.
  87. * @param spec - the raw triple, e.g. `node24-linux-x64`.
  88. * @returns the parsed target.
  89. */
  90. static parse(spec: string): Target {
  91. const parts = spec.split('-')
  92. const [nodeRange, platform, arch] = parts
  93. if (parts.length !== 3 || nodeRange === undefined || platform === undefined || arch === undefined) {
  94. throw new Error(`build-exe-for-python-sdk: target ${JSON.stringify(spec)} must be <nodeRange>-<platform>-<arch>, e.g. node24-linux-x64.`)
  95. }
  96. if (!/^node\d+$/.test(nodeRange)) {
  97. throw new Error(`build-exe-for-python-sdk: target ${JSON.stringify(spec)}: node range must look like node24, got ${JSON.stringify(nodeRange)}.`)
  98. }
  99. if (!isPlatform(platform)) {
  100. throw new Error(`build-exe-for-python-sdk: target ${JSON.stringify(spec)}: platform must be one of ${PLATFORMS.join(', ')}, got ${JSON.stringify(platform)}.`)
  101. }
  102. if (!isArch(arch)) {
  103. throw new Error(`build-exe-for-python-sdk: target ${JSON.stringify(spec)}: arch must be one of ${ARCHES.join(', ')}, got ${JSON.stringify(arch)}.`)
  104. }
  105. return new Target(nodeRange, platform, arch)
  106. }
  107. /**
  108. * Resolve the host-platform default on Node 24.
  109. * @returns the host target; throws on an unsupported host platform or arch.
  110. */
  111. static host(): Target {
  112. const platform = process.platform === 'darwin' ? 'macos' : process.platform === 'linux' ? 'linux' : undefined
  113. if (platform === undefined) {
  114. throw new Error(`build-exe-for-python-sdk: unsupported host platform ${process.platform}; pass --targets explicitly.`)
  115. }
  116. const arch = process.arch === 'x64' || process.arch === 'arm64' ? process.arch : undefined
  117. if (arch === undefined) {
  118. throw new Error(`build-exe-for-python-sdk: unsupported host arch ${process.arch}; pass --targets explicitly.`)
  119. }
  120. return new Target(DEFAULT_NODE_RANGE, platform, arch)
  121. }
  122. }
  123. /**
  124. * Validated CLI configuration; construction owns help and parse-error exits.
  125. */
  126. class BuildCli {
  127. private constructor(
  128. /** Build targets; defaults to the host platform only. */
  129. readonly targets: readonly Target[],
  130. /** Skip step 1 (`pnpm run build`); lib/ artifacts must already exist. */
  131. readonly skipBuild: boolean,
  132. /** Print every command and config patch instead of executing. */
  133. readonly dryRun: boolean,
  134. ) {}
  135. /**
  136. * Parse argv. Help exits 0; malformed flags exit 1; invalid or colliding
  137. * targets throw.
  138. * @param argv - the raw arguments (`process.argv.slice(2)`).
  139. * @returns the parsed, validated configuration.
  140. */
  141. static parse(argv: string[]): BuildCli {
  142. let values: ReturnType<typeof BuildCli.parseRaw>
  143. try {
  144. values = BuildCli.parseRaw(argv)
  145. } catch (error) {
  146. console.error(`build-exe-for-python-sdk: ${error instanceof Error ? error.message : String(error)}\n`)
  147. console.error(BuildCli.usage())
  148. process.exit(1)
  149. }
  150. if (values.help) {
  151. console.log(BuildCli.usage())
  152. process.exit(0)
  153. }
  154. const targets = values.targets === undefined
  155. ? [Target.host()]
  156. : values.targets.split(',').map(part => part.trim()).filter(part => part !== '').map(spec => Target.parse(spec))
  157. if (targets.length === 0) throw new Error('build-exe-for-python-sdk: --targets is empty.')
  158. const seen = new Set<string>()
  159. for (const target of targets) {
  160. const key = `${target.platform}-${target.arch}`
  161. if (seen.has(key)) {
  162. throw new Error(`build-exe-for-python-sdk: duplicate platform-arch ${key} in --targets; canonical product names would collide.`)
  163. }
  164. seen.add(key)
  165. }
  166. return new BuildCli(targets, values['skip-build'], values['dry-run'])
  167. }
  168. private static parseRaw(argv: string[]) {
  169. return parseArgs({
  170. args: argv,
  171. options: {
  172. 'targets': { type: 'string' },
  173. 'skip-build': { type: 'boolean', default: false },
  174. 'dry-run': { type: 'boolean', default: false },
  175. 'help': { type: 'boolean', default: false },
  176. },
  177. }).values
  178. }
  179. private static usage(): string {
  180. return [
  181. 'Usage: pnpm exec tsx scripts/build-exe-for-python-sdk.ts [flags]',
  182. '',
  183. ' --targets=<t1,t2,...> pkg targets, e.g. node24-linux-x64,node24-linux-arm64,node24-macos-arm64.',
  184. ' Default: the host platform only (on node24).',
  185. ' --skip-build skip `pnpm run build` (lib/ artifacts must already exist).',
  186. ' --dry-run print every command and config patch without executing.',
  187. ' --help print this help.',
  188. '',
  189. `Build route: ${PKG_SPEC} --sea; see .agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md.`,
  190. `Stages the node carrier in ${PYTHON_RUNTIME_DIR}/${PYTHON_NODE_SUBDIR} and writes executables to ${OUT_DIR}/.`,
  191. ].join('\n')
  192. }
  193. }
  194. function pnpmBin(): string {
  195. return process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm'
  196. }
  197. /**
  198. * Render a command for logs and errors, quoting arguments with spaces.
  199. * @param command - the executable.
  200. * @param args - its arguments.
  201. * @returns the printable command line.
  202. */
  203. function formatCommand(command: string, args: string[]): string {
  204. return [command, ...args].map(part => (part.includes(' ') ? JSON.stringify(part) : part)).join(' ')
  205. }
  206. /**
  207. * Sequential build pipeline. Subprocesses inherit stdio and errors include
  208. * the command; dry runs print commands and filesystem changes.
  209. */
  210. class SingleExeBuild {
  211. /**
  212. * The cleared deploy target, pkg input, and Python node-mode carrier.
  213. */
  214. readonly staging = resolve(root, PYTHON_RUNTIME_DIR, PYTHON_NODE_SUBDIR)
  215. private readonly outDir = resolve(root, OUT_DIR)
  216. constructor(private readonly cli: BuildCli) {}
  217. /** Verify the closure before compiling or packaging. */
  218. async verifyClosure(): Promise<void> {
  219. await this.run('runtime dependency closure', pnpmBin(), ['run', 'verify-runtime-closure'])
  220. }
  221. /** Build all package artifacts unless `--skip-build` was passed. */
  222. async build(): Promise<void> {
  223. if (this.cli.skipBuild) {
  224. console.log('build-exe-for-python-sdk: skipping pnpm run build (--skip-build)')
  225. return
  226. }
  227. await this.run('build', pnpmBin(), ['run', 'build'])
  228. }
  229. /** Clear and deploy the runtime closure into the node carrier. */
  230. async deployStaging(): Promise<void> {
  231. if (this.staging === root || root.startsWith(this.staging + sep)) {
  232. throw new Error(`build-exe-for-python-sdk: refusing to clear staging dir ${this.staging}: it contains the repo root.`)
  233. }
  234. if (this.cli.dryRun) console.log(`build-exe-for-python-sdk: [dry-run] rm -rf ${this.staging}`)
  235. else await rm(this.staging, { recursive: true, force: true })
  236. await this.run('deploy', pnpmBin(), [
  237. '--filter',
  238. DEPLOY_ROOT_PACKAGE,
  239. 'deploy',
  240. '--legacy',
  241. '--prod',
  242. '--config.node-linker=hoisted',
  243. '--config.auto-install-peers=false',
  244. '--config.link-workspace-packages=true',
  245. this.staging,
  246. ])
  247. await this.restoreLegacyHoists()
  248. await this.materializeStagedLinks()
  249. if (this.cli.dryRun) {
  250. for (const name of DEPLOY_ONLY_DOCS) console.log(`build-exe-for-python-sdk: [dry-run] rm -f ${join(this.staging, name)}`)
  251. } else {
  252. await Promise.all(DEPLOY_ONLY_DOCS.map(name => rm(join(this.staging, name), { force: true })))
  253. }
  254. }
  255. /**
  256. * Restore direct packages that pnpm's legacy hoister places beside the deploy
  257. * source instead of in the target. The runtime manifest supplies every peer,
  258. * so package-local node_modules trees are omitted to preserve one flat Cordis
  259. * instance and a symlink-free packaged payload.
  260. */
  261. private async restoreLegacyHoists(): Promise<void> {
  262. if (this.cli.dryRun) {
  263. console.log('build-exe-for-python-sdk: [dry-run] restore direct dependencies omitted by legacy deploy')
  264. return
  265. }
  266. const manifestPath = join(this.staging, 'package.json')
  267. const manifest = JSON.parse(await readFile(manifestPath, 'utf8')) as {
  268. dependencies?: Record<string, string>
  269. }
  270. const sourceNodeModules = resolve(root, DEPLOY_SOURCE_NODE_MODULES)
  271. const restored: string[] = []
  272. for (const dependency of Object.keys(manifest.dependencies ?? {}).sort()) {
  273. const destination = join(this.staging, 'node_modules', dependency)
  274. if (existsSync(destination)) continue
  275. const source = join(sourceNodeModules, dependency)
  276. if (!existsSync(source)) {
  277. throw new Error(
  278. `build-exe-for-python-sdk: deployed dependency ${dependency} is absent from both ${destination} and ${source}.`,
  279. )
  280. }
  281. await mkdir(dirname(destination), { recursive: true })
  282. const nestedNodeModules = join(source, 'node_modules')
  283. await cp(source, destination, {
  284. recursive: true,
  285. dereference: true,
  286. filter: path => path !== nestedNodeModules && !path.startsWith(nestedNodeModules + sep),
  287. })
  288. restored.push(dependency)
  289. }
  290. const stillMissing = Object.keys(manifest.dependencies ?? {})
  291. .filter(dependency => !existsSync(join(this.staging, 'node_modules', dependency)))
  292. if (stillMissing.length > 0) {
  293. throw new Error(`build-exe-for-python-sdk: staged dependencies remain missing: ${stillMissing.join(', ')}.`)
  294. }
  295. if (restored.length > 0) {
  296. console.log(`build-exe-for-python-sdk: restored legacy deploy hoists: ${restored.join(', ')}`)
  297. }
  298. }
  299. /** Replace deploy-time package links with files and reject any remaining link. */
  300. private async materializeStagedLinks(): Promise<void> {
  301. if (this.cli.dryRun) {
  302. console.log('build-exe-for-python-sdk: [dry-run] materialize staged package links')
  303. return
  304. }
  305. const nodeModules = join(this.staging, 'node_modules')
  306. let remaining = await this.findSymlink(nodeModules)
  307. while (remaining !== undefined) {
  308. const segments = remaining.slice(nodeModules.length + 1).split(sep)
  309. const binIndex = segments.lastIndexOf('.bin')
  310. if (binIndex >= 0) {
  311. await rm(join(nodeModules, ...segments.slice(0, binIndex + 1)), { recursive: true, force: true })
  312. remaining = await this.findSymlink(nodeModules)
  313. continue
  314. }
  315. const destination = remaining
  316. const source = await realpath(destination)
  317. const nestedNodeModules = join(source, 'node_modules')
  318. await rm(destination, { recursive: true, force: true })
  319. await cp(source, destination, {
  320. recursive: true,
  321. dereference: true,
  322. filter: path => path !== nestedNodeModules && !path.startsWith(nestedNodeModules + sep),
  323. })
  324. remaining = await this.findSymlink(nodeModules)
  325. }
  326. }
  327. /** Return the first symbolic link below a directory, if one exists. */
  328. private async findSymlink(directory: string): Promise<string | undefined> {
  329. for (const entry of await readdir(directory, { withFileTypes: true })) {
  330. const path = join(directory, entry.name)
  331. const metadata = await lstat(path)
  332. if (metadata.isSymbolicLink()) return path
  333. if (metadata.isDirectory()) {
  334. const nested = await this.findSymlink(path)
  335. if (nested !== undefined) return nested
  336. }
  337. }
  338. return undefined
  339. }
  340. /** Add the executable entry and pkg assets to the staged manifest. */
  341. async injectPkgConfig(): Promise<void> {
  342. const patch = { bin: ENTRY_BIN, pkg: { assets: ASSET_GLOBS } }
  343. const manifestPath = join(this.staging, 'package.json')
  344. if (this.cli.dryRun) {
  345. console.log(`build-exe-for-python-sdk: [dry-run] patch ${manifestPath} with ${JSON.stringify(patch)}`)
  346. return
  347. }
  348. if (!existsSync(manifestPath)) {
  349. throw new Error(`build-exe-for-python-sdk: ${manifestPath} missing — pnpm deploy did not produce a staged package.`)
  350. }
  351. if (!existsSync(join(this.staging, ENTRY_BIN))) {
  352. throw new Error(`build-exe-for-python-sdk: ${join(this.staging, ENTRY_BIN)} missing — run without --skip-build so lib/ artifacts exist.`)
  353. }
  354. const manifest = JSON.parse(await readFile(manifestPath, 'utf8')) as Record<string, unknown>
  355. await writeFile(manifestPath, `${JSON.stringify({ ...manifest, ...patch }, null, 2)}\n`)
  356. console.log(`build-exe-for-python-sdk: injected pkg config into ${manifestPath}`)
  357. }
  358. /**
  359. * Package one target; SEA mode accepts one target per invocation.
  360. * @param target - the pkg target triple to build.
  361. * @returns the executable and ripgrep sidecar paths, plus the macOS spawn helper path when required.
  362. */
  363. async pack(target: Target): Promise<string[]> {
  364. const product = join(this.outDir, `${OUTPUT_BASENAME}-${target.platform}-${target.arch}`)
  365. await this.prepareNativePty(target)
  366. if (!this.cli.dryRun) await mkdir(this.outDir, { recursive: true })
  367. await this.run(`pkg ${target.spec}`, pnpmBin(), [
  368. 'dlx',
  369. PKG_SPEC,
  370. this.staging,
  371. '--sea',
  372. '--targets',
  373. target.spec,
  374. '--output',
  375. product,
  376. ])
  377. if (!this.cli.dryRun && !existsSync(product)) {
  378. throw new Error(`build-exe-for-python-sdk: product ${product} is missing after the pkg run; inspect ${this.outDir}.`)
  379. }
  380. const ripgrep = await this.copyRipgrepSidecar(target, product)
  381. if (target.platform !== 'macos') return [product, ripgrep]
  382. const spawnHelper = `${product}-spawn-helper`
  383. const source = join(this.staging, 'node_modules', 'node-pty', 'prebuilds', `darwin-${target.arch}`, 'spawn-helper')
  384. if (this.cli.dryRun) {
  385. console.log(`build-exe-for-python-sdk: [dry-run] cp ${source} ${spawnHelper}`)
  386. } else {
  387. await copyFile(source, spawnHelper)
  388. await chmod(spawnHelper, 0o755)
  389. }
  390. return [product, ripgrep, spawnHelper]
  391. }
  392. /** Copy the target ripgrep binary beside the executable so Node can spawn it outside pkg's virtual filesystem. */
  393. private async copyRipgrepSidecar(target: Target, product: string): Promise<string> {
  394. const platform = target.platform === 'macos' ? 'darwin' : target.platform
  395. const source = join(
  396. this.staging,
  397. 'node_modules',
  398. '@vscode',
  399. `ripgrep-${platform}-${target.arch}`,
  400. 'bin',
  401. 'rg',
  402. )
  403. const destination = `${product}-rg`
  404. if (this.cli.dryRun) {
  405. console.log(`build-exe-for-python-sdk: [dry-run] cp ${source} ${destination}`)
  406. return destination
  407. }
  408. if (!existsSync(source)) {
  409. throw new Error(`build-exe-for-python-sdk: target ripgrep binary is missing at ${source}.`)
  410. }
  411. await copyFile(source, destination)
  412. await chmod(destination, 0o755)
  413. return destination
  414. }
  415. /**
  416. * Put the target node-pty addon in the staged closure. The release workflow
  417. * provides a manylinux build; ordinary installs use node-pty's target prebuild.
  418. * @param target - the pkg target whose native addon is being staged.
  419. */
  420. private async prepareNativePty(target: Target): Promise<void> {
  421. const stagedBuild = join(this.staging, 'node_modules', 'node-pty', 'build')
  422. if (this.cli.dryRun) console.log(`build-exe-for-python-sdk: [dry-run] rm -rf ${stagedBuild}`)
  423. else await rm(stagedBuild, { recursive: true, force: true })
  424. if (target.platform !== 'linux') return
  425. const packageDirectory = join(
  426. root,
  427. 'packages',
  428. 'subprocess',
  429. 'subprocess-local',
  430. 'node_modules',
  431. 'node-pty',
  432. )
  433. const destination = join(stagedBuild, 'Release', 'pty.node')
  434. const source = resolveLinuxNodePtyAddon(packageDirectory, target.arch)
  435. if (this.cli.dryRun) {
  436. console.log(`build-exe-for-python-sdk: [dry-run] cp ${source} ${destination}`)
  437. return
  438. }
  439. const host = Target.host()
  440. if (target.platform !== host.platform || target.arch !== host.arch) {
  441. throw new Error(
  442. 'build-exe-for-python-sdk: build the Linux runtime on its target architecture; '
  443. + `target ${target.platform}-${target.arch} does not match host ${host.platform}-${host.arch}.`,
  444. )
  445. }
  446. await mkdir(dirname(destination), { recursive: true })
  447. await copyFile(source, destination)
  448. }
  449. /**
  450. * Print each product path and, outside dry-run mode, its size.
  451. * @param products - the product paths returned by {@link pack}.
  452. */
  453. printProducts(products: string[]): void {
  454. console.log(this.cli.dryRun ? 'build-exe-for-python-sdk: [dry-run] would produce:' : 'build-exe-for-python-sdk: products:')
  455. for (const path of products) {
  456. if (this.cli.dryRun) {
  457. console.log(` ${path}`)
  458. continue
  459. }
  460. const megabytes = statSync(path).size / (1024 * 1024)
  461. console.log(` ${path} (${megabytes.toFixed(1)} MB)`)
  462. }
  463. }
  464. /**
  465. * Copy each product into the Python runtime package. The deployed node
  466. * carrier is already in place, and `dist-exe/` retains upload copies.
  467. * @param products - the product paths returned by {@link pack}.
  468. */
  469. async syncToPythonRuntime(products: string[]): Promise<void> {
  470. const destDir = resolve(root, PYTHON_RUNTIME_DIR)
  471. if (this.cli.dryRun) {
  472. for (const path of products) {
  473. console.log(`build-exe-for-python-sdk: [dry-run] cp ${path} ${join(destDir, basename(path))}`)
  474. }
  475. return
  476. }
  477. await mkdir(destDir, { recursive: true })
  478. for (const path of products) {
  479. const destination = join(destDir, basename(path))
  480. await copyFile(path, destination)
  481. await chmod(destination, statSync(path).mode & 0o777)
  482. console.log(`build-exe-for-python-sdk: synced ${destination}`)
  483. }
  484. }
  485. /**
  486. * Run one subprocess with inherited stdio. Spawn and non-zero-exit errors
  487. * include the command; dry runs only print it.
  488. * @param label - the step name used in logs and error messages.
  489. * @param command - the executable.
  490. * @param args - its arguments.
  491. */
  492. private async run(label: string, command: string, args: string[]): Promise<void> {
  493. const printable = formatCommand(command, args)
  494. if (this.cli.dryRun) {
  495. console.log(`build-exe-for-python-sdk: [dry-run] ${printable}`)
  496. return
  497. }
  498. console.log(`build-exe-for-python-sdk: ${label}: ${printable}`)
  499. await new Promise<void>((resolvePromise, reject) => {
  500. const child = spawn(command, args, {
  501. cwd: root,
  502. stdio: 'inherit',
  503. // Artifact builds must not mutate or validate a developer's Git hooks.
  504. env: { ...process.env, CI: 'true' },
  505. })
  506. child.once('error', (error) => {
  507. reject(new Error(`build-exe-for-python-sdk: ${label} failed to spawn: ${error.message} (${printable})`))
  508. })
  509. child.once('exit', (code, signal) => {
  510. if (code === 0) {
  511. resolvePromise()
  512. return
  513. }
  514. const cause = code === null ? `signal ${signal ?? 'unknown'}` : `exit code ${code}`
  515. reject(new Error(`build-exe-for-python-sdk: ${label} failed (${cause}): ${printable}`))
  516. })
  517. })
  518. }
  519. }
  520. async function main(): Promise<void> {
  521. const cli = BuildCli.parse(process.argv.slice(2))
  522. const pipeline = new SingleExeBuild(cli)
  523. console.log(`build-exe-for-python-sdk: targets: ${cli.targets.map(target => target.spec).join(', ')}`)
  524. console.log(`build-exe-for-python-sdk: staging: ${pipeline.staging}`)
  525. await pipeline.verifyClosure()
  526. await pipeline.build()
  527. await pipeline.deployStaging()
  528. await pipeline.injectPkgConfig()
  529. const products: string[] = []
  530. for (const target of cli.targets) products.push(...await pipeline.pack(target))
  531. pipeline.printProducts(products)
  532. await pipeline.syncToPythonRuntime(products)
  533. }
  534. await main()