Skip to content

Commit

Permalink
优化:命令行解析优化
Browse files Browse the repository at this point in the history
  • Loading branch information
modstart committed Dec 16, 2024
1 parent 3eb40b4 commit 617cfde
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 29 deletions.
46 changes: 46 additions & 0 deletions electron/lib/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,52 @@ export const MemoryCacheUtil = {
export const ShellUtil = {
quotaPath(p: string) {
return `"${p}"`
},
parseCommandArgs(command: string) {
let args = []
let arg = ''
let quote = ''
let escape = false
for (let i = 0; i < command.length; i++) {
const c = command[i]
if (escape) {
arg += c
escape = false
continue
}
if ('\\' === c) {
escape = true
arg += c
continue
}
if ('' === quote && (' ' === c || '\t' === c)) {
if (arg) {
args.push(arg)
arg = ''
}
continue
}
if ('' === quote && ('"' === c || "'" === c)) {
quote = c
arg += c
continue
}
if ('"' === quote && '"' === c) {
quote = ''
arg += c
continue
}
if ("'" === quote && "'" === c) {
quote = ''
arg += c
continue
}
arg += c
}
if (arg) {
args.push(arg)
}
return args
}
}

Expand Down
31 changes: 2 additions & 29 deletions electron/mapi/app/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,38 +4,11 @@ import {exec as _exec, spawn} from "node:child_process";
import {isLinux, isMac, isWin, platformArch, platformName, platformUUID, platformVersion} from "../../lib/env";
import {Log} from "../log/index";
import iconv from "iconv-lite";
import {StrUtil} from "../../lib/util";
import {ShellUtil, StrUtil} from "../../lib/util";
import {AppConfig} from "../../../src/config";

const exec = util.promisify(_exec)

const commandSplit = (command: string) => {
// split command with space, but ignore space in quotes
const args = []
let arg = ''
let quote = ''
for (let i = 0; i < command.length; i++) {
const c = command[i]
if (c === ' ' && !quote) {
if (arg) {
args.push(arg)
arg = ''
}
continue
}
if (c === '"' || c === "'") {
if (quote && quote === c) {
quote = ''
continue
}
quote = c
continue
}
arg += c
}
return args
}

const outputStringConvert = (outputEncoding: 'utf8' | 'cp936', data: any) => {
if (!data) {
return ''
Expand Down Expand Up @@ -90,7 +63,7 @@ const spawnShell = async (command: string | string[], option: {
commandEntry = command[0]
args = command.slice(1)
} else {
args = commandSplit(command)
args = ShellUtil.parseCommandArgs(command)
commandEntry = args.shift() as string
}
Log.info('App.spawnShell', {
Expand Down

0 comments on commit 617cfde

Please sign in to comment.