recital / core / src / tools / command-shorthand.ts
command-shorthand.ts
Raw
/**
 * Copyright (c) 2022 Amorphous
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

import { CommandToken } from '../types'
import { splitLineBySpacesWithQuotes } from './split-line-by-spaces-with-quotes'

export const createCommandObject = (line: string): CommandToken => {
	if (!line.startsWith('$')) {
		throw new Error('$ shorthand must begin with an $ symbol')
	}
	let trimmedCommand = line.substring(1).trim()

	const commandParts = splitLineBySpacesWithQuotes(trimmedCommand).map((arg) => {
		if (arg.startsWith('"') && arg.endsWith('"')) {
			return arg.slice(1, arg.length - 1)
		}
		if (arg.startsWith("'") && arg.endsWith("'")) {
			return arg.slice(1, arg.length - 1)
		}
		return arg
	})

	let [command, ...params] = commandParts

	return {
		type: 'command',
		text: trimmedCommand,
		name: command,
		args: params,
	}
}