Skip to content
Myr

template.js

This file

Path

lib/methods/template.js

153 lines · 4.8 KiB · JavaScript

Last changed by

Fixes argument parsing for escaped newlines (#1176)Aaron Dandybefore adoption2aa3b0c

History of this file

Take it

Rename files (#977)ehmickybefore adoption4b2e316

line 1why, one step back
1import {ChildProcess} from 'node:child_process';

Refactor logic and rename some variables (#983)ehmickybefore adoptionbd3b478

line 2why, one step back
2import isPlainObject from 'is-plain-obj';

Rename files (#977)ehmickybefore adoption4b2e316

lines 3–4why, one step back
3import {isUint8Array, uint8ArrayToString} from '../utils/uint-array.js';
4

Add more code comments (#984)ehmickybefore adoptionfdd8a9f

line 5why, one step back
5// Check whether the template string syntax is being used

Rename files (#977)ehmickybefore adoption4b2e316

lines 6–7why, one step back
6export const isTemplateString = templates => Array.isArray(templates) && Array.isArray(templates.raw);
7

Add more code comments (#984)ehmickybefore adoptionfdd8a9f

line 8why, one step back
8// Convert execa`file ...commandArguments` to execa(file, commandArguments)

Rename files (#977)ehmickybefore adoption4b2e316

lines 9–12why, one step back
9export const parseTemplates = (templates, expressions) => {
10 let tokens = [];1112 for (const [index, template] of templates.entries()) {

Upgrade xo (#980)ehmickybefore adoptionccfa412

lines 13–19why, one step back
13 tokens = parseTemplate({
14 templates,15 expressions,16 tokens,17 index,18 template,19 });

Rename files (#977)ehmickybefore adoption4b2e316

lines 20–25why, one step back
20 }
2122 if (tokens.length === 0) {23 throw new TypeError('Template script must not be empty');24 }25

Upgrade xo (#980)ehmickybefore adoptionccfa412

lines 26–27why, one step back
26 const [file, ...commandArguments] = tokens;
27 return [file, commandArguments, {}];

Rename files (#977)ehmickybefore adoption4b2e316

lines 28–77why, one step back
28};
2930const parseTemplate = ({templates, expressions, tokens, index, template}) => {31 if (template === undefined) {32 throw new TypeError(`Invalid backslash sequence: ${templates.raw[index]}`);33 }3435 const {nextTokens, leadingWhitespaces, trailingWhitespaces} = splitByWhitespaces(template, templates.raw[index]);36 const newTokens = concatTokens(tokens, nextTokens, leadingWhitespaces);3738 if (index === expressions.length) {39 return newTokens;40 }4142 const expression = expressions[index];43 const expressionTokens = Array.isArray(expression)44 ? expression.map(expression => parseExpression(expression))45 : [parseExpression(expression)];46 return concatTokens(newTokens, expressionTokens, trailingWhitespaces);47};4849// Like `string.split(/[ \t\r\n]+/)` except newlines and tabs are:50// - ignored when input as a backslash sequence like: `echo foo\n bar`51// - not ignored when input directly52// The only way to distinguish those in JavaScript is to use a tagged template and compare:53// - the first array argument, which does not escape backslash sequences54// - its `raw` property, which escapes them55const splitByWhitespaces = (template, rawTemplate) => {56 if (rawTemplate.length === 0) {57 return {nextTokens: [], leadingWhitespaces: false, trailingWhitespaces: false};58 }5960 const nextTokens = [];61 let templateStart = 0;62 const leadingWhitespaces = DELIMITERS.has(rawTemplate[0]);6364 for (65 let templateIndex = 0, rawIndex = 0;66 templateIndex < template.length;67 templateIndex += 1, rawIndex += 168 ) {69 const rawCharacter = rawTemplate[rawIndex];70 if (DELIMITERS.has(rawCharacter)) {71 if (templateStart !== templateIndex) {72 nextTokens.push(template.slice(templateStart, templateIndex));73 }7475 templateStart = templateIndex + 1;76 } else if (rawCharacter === '\\') {77 const nextRawCharacter = rawTemplate[rawIndex + 1];

Fixes argument parsing for escaped newlines (#1176)Aaron Dandybefore adoption2aa3b0c

lines 78–82why, one step back
78 if (nextRawCharacter === '\n') {
79 // Handles escaped newlines in templates80 templateIndex -= 1;81 rawIndex += 1;82 } else if (nextRawCharacter === 'u' && rawTemplate[rawIndex + 2] === '{') {

Rename files (#977)ehmickybefore adoption4b2e316

lines 83–114why, one step back
83 rawIndex = rawTemplate.indexOf('}', rawIndex + 3);
84 } else {85 rawIndex += ESCAPE_LENGTH[nextRawCharacter] ?? 1;86 }87 }88 }8990 const trailingWhitespaces = templateStart === template.length;91 if (!trailingWhitespaces) {92 nextTokens.push(template.slice(templateStart));93 }9495 return {nextTokens, leadingWhitespaces, trailingWhitespaces};96};9798const DELIMITERS = new Set([' ', '\t', '\r', '\n']);99100// Number of characters in backslash escape sequences: \0 \xXX or \uXXXX101// \cX is allowed in RegExps but not in strings102// Octal sequences are not allowed in strict mode103const ESCAPE_LENGTH = {x: 3, u: 5};104105const concatTokens = (tokens, nextTokens, isSeparated) => isSeparated106 || tokens.length === 0107 || nextTokens.length === 0108 ? [...tokens, ...nextTokens]109 : [110 ...tokens.slice(0, -1),111 `${tokens.at(-1)}${nextTokens[0]}`,112 ...nextTokens.slice(1),113 ];114

Add more code comments (#984)ehmickybefore adoptionfdd8a9f

line 115why, one step back
115// Handle `${expression}` inside the template string syntax

Rename files (#977)ehmickybefore adoption4b2e316

lines 116–126why, one step back
116const parseExpression = expression => {
117 const typeOfExpression = typeof expression;118119 if (typeOfExpression === 'string') {120 return expression;121 }122123 if (typeOfExpression === 'number') {124 return String(expression);125 }126

Do not set `undefined` properties on the return value (#992)ehmickybefore adoption0d33b6d

line 127why, one step back
127 if (isPlainObject(expression) && ('stdout' in expression || 'isMaxBuffer' in expression)) {

Refactor logic and rename some variables (#983)ehmickybefore adoptionbd3b478

lines 128–129why, one step back
128 return getSubprocessResult(expression);
129 }

Rename files (#977)ehmickybefore adoption4b2e316

line 130why, one step back
130

Refactor logic and rename some variables (#983)ehmickybefore adoptionbd3b478

lines 131–133why, one step back
131 if (expression instanceof ChildProcess || Object.prototype.toString.call(expression) === '[object Promise]') {
132 // eslint-disable-next-line no-template-curly-in-string133 throw new TypeError('Unexpected subprocess in template expression. Please use ${await subprocess} instead of ${subprocess}.');

Rename files (#977)ehmickybefore adoption4b2e316

lines 134–138why, one step back
134 }
135136 throw new TypeError(`Unexpected "${typeOfExpression}" in template expression`);137};138

Refactor logic and rename some variables (#983)ehmickybefore adoptionbd3b478

lines 139–153why, one step back
139const getSubprocessResult = ({stdout}) => {
140 if (typeof stdout === 'string') {141 return stdout;142 }143144 if (isUint8Array(stdout)) {145 return uint8ArrayToString(stdout);146 }147148 if (stdout === undefined) {149 throw new TypeError('Missing result.stdout in template expression. This is probably due to the previous subprocess\' "stdout" option.');150 }151152 throw new TypeError(`Unexpected "${typeof stdout}" stdout in template expression`);153};