Skip to content
Myr

template.js

This file

Path

lib/arguments/template.js

133 lines · 4.0 KiB · JavaScript

Last changed by

Add support for transforms with `execaSync()` (#945)ehmickybefore adoptionc5f9f09

History of this file

Take it

Add support for transforms with `execaSync()` (#945)ehmickybefore adoptionc5f9f09

lines 1–2why, one step back
1import {isUint8Array, uint8ArrayToString} from '../stdio/uint-array.js';
2import {isSubprocess} from '../utils.js';

Allow template strings with all methods (#933)ehmickybefore adoption8074d85

lines 3–133why, one step back
3
4export const isTemplateString = templates => Array.isArray(templates) && Array.isArray(templates.raw);56export const parseTemplates = (templates, expressions) => {7 let tokens = [];89 for (const [index, template] of templates.entries()) {10 tokens = parseTemplate({templates, expressions, tokens, index, template});11 }1213 if (tokens.length === 0) {14 throw new TypeError('Template script must not be empty');15 }1617 const [file, ...args] = tokens;18 return [file, args, {}];19};2021const parseTemplate = ({templates, expressions, tokens, index, template}) => {22 if (template === undefined) {23 throw new TypeError(`Invalid backslash sequence: ${templates.raw[index]}`);24 }2526 const {nextTokens, leadingWhitespaces, trailingWhitespaces} = splitByWhitespaces(template, templates.raw[index]);27 const newTokens = concatTokens(tokens, nextTokens, leadingWhitespaces);2829 if (index === expressions.length) {30 return newTokens;31 }3233 const expression = expressions[index];34 const expressionTokens = Array.isArray(expression)35 ? expression.map(expression => parseExpression(expression))36 : [parseExpression(expression)];37 return concatTokens(newTokens, expressionTokens, trailingWhitespaces);38};3940// Like `string.split(/[ \t\r\n]+/)` except newlines and tabs are:41// - ignored when input as a backslash sequence like: `echo foo\n bar`42// - not ignored when input directly43// The only way to distinguish those in JavaScript is to use a tagged template and compare:44// - the first array argument, which does not escape backslash sequences45// - its `raw` property, which escapes them46const splitByWhitespaces = (template, rawTemplate) => {47 if (rawTemplate.length === 0) {48 return {nextTokens: [], leadingWhitespaces: false, trailingWhitespaces: false};49 }5051 const nextTokens = [];52 let templateStart = 0;53 const leadingWhitespaces = DELIMITERS.has(rawTemplate[0]);5455 for (56 let templateIndex = 0, rawIndex = 0;57 templateIndex < template.length;58 templateIndex += 1, rawIndex += 159 ) {60 const rawCharacter = rawTemplate[rawIndex];61 if (DELIMITERS.has(rawCharacter)) {62 if (templateStart !== templateIndex) {63 nextTokens.push(template.slice(templateStart, templateIndex));64 }6566 templateStart = templateIndex + 1;67 } else if (rawCharacter === '\\') {68 const nextRawCharacter = rawTemplate[rawIndex + 1];69 if (nextRawCharacter === 'u' && rawTemplate[rawIndex + 2] === '{') {70 rawIndex = rawTemplate.indexOf('}', rawIndex + 3);71 } else {72 rawIndex += ESCAPE_LENGTH[nextRawCharacter] ?? 1;73 }74 }75 }7677 const trailingWhitespaces = templateStart === template.length;78 if (!trailingWhitespaces) {79 nextTokens.push(template.slice(templateStart));80 }8182 return {nextTokens, leadingWhitespaces, trailingWhitespaces};83};8485const DELIMITERS = new Set([' ', '\t', '\r', '\n']);8687// Number of characters in backslash escape sequences: \0 \xXX or \uXXXX88// \cX is allowed in RegExps but not in strings89// Octal sequences are not allowed in strict mode90const ESCAPE_LENGTH = {x: 3, u: 5};9192const concatTokens = (tokens, nextTokens, isSeparated) => isSeparated93 || tokens.length === 094 || nextTokens.length === 095 ? [...tokens, ...nextTokens]96 : [97 ...tokens.slice(0, -1),98 `${tokens.at(-1)}${nextTokens[0]}`,99 ...nextTokens.slice(1),100 ];101102const parseExpression = expression => {103 const typeOfExpression = typeof expression;104105 if (typeOfExpression === 'string') {106 return expression;107 }108109 if (typeOfExpression === 'number') {110 return String(expression);111 }112113 if (114 typeOfExpression === 'object'115 && expression !== null116 && !isSubprocess(expression)117 && 'stdout' in expression118 ) {119 const typeOfStdout = typeof expression.stdout;120121 if (typeOfStdout === 'string') {122 return expression.stdout;123 }124125 if (isUint8Array(expression.stdout)) {126 return uint8ArrayToString(expression.stdout);127 }128129 throw new TypeError(`Unexpected "${typeOfStdout}" stdout in template expression`);130 }131132 throw new TypeError(`Unexpected "${typeOfExpression}" in template expression`);133};