1
0
mirror of https://github.com/laurent22/joplin.git synced 2024-12-24 10:27:10 +02:00
joplin/packages/utils/splitCommandString.ts

75 lines
1.3 KiB
TypeScript
Raw Normal View History

// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
export default (command: string, options: any = null) => {
options = options || {};
if (!('handleEscape' in options)) {
options.handleEscape = true;
}
const args = [];
let state = 'start';
let current = '';
let quote = '"';
let escapeNext = false;
for (let i = 0; i < command.length; i++) {
const c = command[i];
if (state === 'quotes') {
if (c !== quote) {
current += c;
} else {
args.push(current);
current = '';
state = 'start';
}
continue;
}
if (escapeNext) {
current += c;
escapeNext = false;
continue;
}
if (c === '\\' && options.handleEscape) {
escapeNext = true;
continue;
}
if (c === '"' || c === '\'') {
state = 'quotes';
quote = c;
continue;
}
if (state === 'arg') {
if (c === ' ' || c === '\t') {
args.push(current);
current = '';
state = 'start';
} else {
current += c;
}
continue;
}
if (c !== ' ' && c !== '\t') {
state = 'arg';
current += c;
}
}
if (state === 'quotes') {
throw new Error(`Unclosed quote in command line: ${command}`);
}
if (current !== '') {
args.push(current);
}
if (args.length <= 0) {
throw new Error('Empty command line');
}
return args;
};