|
| 1 | +// Copyright (C) 2025 The Qt Company Ltd. |
| 2 | +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only |
| 3 | + |
| 4 | +import * as path from 'path'; |
| 5 | +import * as childProcess from 'child_process'; |
| 6 | + |
| 7 | +import { IsWindows } from 'qt-lib'; |
| 8 | +import { PySideEnv } from './env'; |
| 9 | + |
| 10 | +export interface PySideCommandBuildOptions { |
| 11 | + useVenv?: boolean; |
| 12 | + cwd?: string; |
| 13 | +} |
| 14 | + |
| 15 | +export class PySideCommandBuilder { |
| 16 | + private readonly _shellPath: string; |
| 17 | + private readonly _shellArgs: string[]; |
| 18 | + private readonly _venvActivationCommand: string; |
| 19 | + |
| 20 | + constructor( |
| 21 | + private readonly _env: PySideEnv, |
| 22 | + private readonly _options?: PySideCommandBuildOptions |
| 23 | + ) { |
| 24 | + this._shellPath = resolveShellPath(); |
| 25 | + this._shellArgs = [IsWindows ? '/c' : '-c']; |
| 26 | + this._venvActivationCommand = resolveVenvActivationCommand(this._env); |
| 27 | + } |
| 28 | + |
| 29 | + get shellPath(): string { |
| 30 | + return this._shellPath; |
| 31 | + } |
| 32 | + |
| 33 | + get shellArgs(): string[] { |
| 34 | + return this._shellArgs; |
| 35 | + } |
| 36 | + |
| 37 | + get venvActivationCommand(): string { |
| 38 | + return this._venvActivationCommand; |
| 39 | + } |
| 40 | + |
| 41 | + public build(command: string) { |
| 42 | + const all: string[] = [command]; |
| 43 | + |
| 44 | + if (this._options?.cwd) { |
| 45 | + all.unshift(`cd ${enclosePath(this._options.cwd)}`); |
| 46 | + } |
| 47 | + |
| 48 | + if (this._options?.useVenv && this._venvActivationCommand) { |
| 49 | + all.unshift(this._venvActivationCommand); |
| 50 | + } |
| 51 | + |
| 52 | + return all.join(' && '); |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +// helpers |
| 57 | +function resolveShellPath(): string { |
| 58 | + if (IsWindows) { |
| 59 | + return process.env.ComSpec ?? 'C:\\Windows\\System32\\cmd.exe'; |
| 60 | + } |
| 61 | + |
| 62 | + const result = childProcess.spawnSync('command -v bash', { shell: true }); |
| 63 | + const found = result.stdout.toString().trim(); |
| 64 | + return result.status === 0 && found ? found : '/bin/bash'; |
| 65 | +} |
| 66 | + |
| 67 | +function resolveVenvActivationCommand(env: PySideEnv): string { |
| 68 | + const bin = env.venvBinPath; |
| 69 | + if (!bin) { |
| 70 | + return ''; |
| 71 | + } |
| 72 | + |
| 73 | + const script = enclosePath( |
| 74 | + path.join(bin, IsWindows ? 'activate.bat' : 'activate') |
| 75 | + ); |
| 76 | + |
| 77 | + return IsWindows ? script : `source ${script}`; |
| 78 | +} |
| 79 | + |
| 80 | +function enclosePath(s: string) { |
| 81 | + return IsWindows ? `"${s}"` : `'${s}'`; |
| 82 | +} |
0 commit comments