1/* 2 * Copyright (c) 2024 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16import { execSync, spawnSync } from 'node:child_process'; 17import { platform } from 'node:process'; 18import * as path from 'node:path'; 19 20const NODEJS_PROGRAM = 'node'; 21const SHELL_PROGRAM = '/bin/sh'; 22const NODEJS_PRINT_CMD_LINE_ARGS_SCRIPT = 'print_cmd_line_args.js'; 23const BATCH_PRINT_CMD_LINE_ARGS_SCRIPT = 'print_cmd_line_args.bat'; 24const SHELL_PRINT_CMD_LINE_ARGS_SCRIPT = 'print_cmd_line_args.sh'; 25 26export function getCommandLineArguments(cmdLine: string): string[] { 27 28 /* 29 * Note: The platform-specific scripts generally run faster than a NodeJS script, 30 * so use it when possible to increase the overall performance. 31 */ 32 let output = ''; 33 switch (platform) { 34 case 'win32': 35 output = windows(cmdLine); 36 break; 37 case 'linux': 38 case 'cygwin': 39 output = linux(cmdLine); 40 break; 41 default: 42 output = nodeJs(cmdLine); 43 } 44 return JSON.parse(output).args; 45} 46 47function getScriptModulePath(script: string): string { 48 return path.resolve(__dirname, script); 49} 50 51function spawnSyncStdout(command: string): string { 52 return spawnSync(command, { shell: true, encoding: 'utf8' }).stdout; 53} 54 55function execSyncStdout(command: string): string { 56 return execSync(command, { encoding: 'utf-8' }); 57} 58 59function nodeJs(cmdArgs: string): string { 60 return spawnSyncStdout(`${NODEJS_PROGRAM} ${getScriptModulePath(NODEJS_PRINT_CMD_LINE_ARGS_SCRIPT)} ${cmdArgs}`); 61} 62 63function windows(cmdArgs: string): string { 64 return spawnSyncStdout(`${getScriptModulePath(BATCH_PRINT_CMD_LINE_ARGS_SCRIPT)} ${cmdArgs}`); 65} 66 67function linux(cmdArgs: string): string { 68 return execSyncStdout(`${SHELL_PROGRAM} ${getScriptModulePath(SHELL_PRINT_CMD_LINE_ARGS_SCRIPT)} ${cmdArgs}`); 69} 70