template.js
This file
Path
lib/methods/template.js
149 lines · 4.7 KiB · JavaScript
Last changed by
Do not set `undefined` properties on the return value (#992)ehmickybefore adoption0d33b6d
History of this fileTake it
Rename files (#977)ehmickybefore adoption4b2e316
line 1why, one step back1import {ChildProcess} from 'node:child_process';Refactor logic and rename some variables (#983)ehmickybefore adoptionbd3b478
line 2why, one step back2import isPlainObject from 'is-plain-obj';Rename files (#977)ehmickybefore adoption4b2e316
lines 3–4why, one step back3import {isUint8Array, uint8ArrayToString} from '../utils/uint-array.js';4Add more code comments (#984)ehmickybefore adoptionfdd8a9f
line 5why, one step back5// Check whether the template string syntax is being usedRename files (#977)ehmickybefore adoption4b2e316
lines 6–7why, one step back6export const isTemplateString = templates => Array.isArray(templates) && Array.isArray(templates.raw);7Add more code comments (#984)ehmickybefore adoptionfdd8a9f
line 8why, one step back8// Convert execa`file ...commandArguments` to execa(file, commandArguments)Rename files (#977)ehmickybefore adoption4b2e316
lines 9–12why, one step back9export 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 back13 tokens = parseTemplate({14 templates,15 expressions,16 tokens,17 index,18 template,19 });Rename files (#977)ehmickybefore adoption4b2e316
lines 20–25why, one step back20 }2122 if (tokens.length === 0) {23 throw new TypeError('Template script must not be empty');24 }25Upgrade xo (#980)ehmickybefore adoptionccfa412
lines 26–27why, one step back26 const [file, ...commandArguments] = tokens;27 return [file, commandArguments, {}];Rename files (#977)ehmickybefore adoption4b2e316
lines 28–110why, one step back28};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];78 if (nextRawCharacter === 'u' && rawTemplate[rawIndex + 2] === '{') {79 rawIndex = rawTemplate.indexOf('}', rawIndex + 3);80 } else {81 rawIndex += ESCAPE_LENGTH[nextRawCharacter] ?? 1;82 }83 }84 }8586 const trailingWhitespaces = templateStart === template.length;87 if (!trailingWhitespaces) {88 nextTokens.push(template.slice(templateStart));89 }9091 return {nextTokens, leadingWhitespaces, trailingWhitespaces};92};9394const DELIMITERS = new Set([' ', '\t', '\r', '\n']);9596// Number of characters in backslash escape sequences: \0 \xXX or \uXXXX97// \cX is allowed in RegExps but not in strings98// Octal sequences are not allowed in strict mode99const ESCAPE_LENGTH = {x: 3, u: 5};100101const concatTokens = (tokens, nextTokens, isSeparated) => isSeparated102 || tokens.length === 0103 || nextTokens.length === 0104 ? [...tokens, ...nextTokens]105 : [106 ...tokens.slice(0, -1),107 `${tokens.at(-1)}${nextTokens[0]}`,108 ...nextTokens.slice(1),109 ];110Add more code comments (#984)ehmickybefore adoptionfdd8a9f
line 111why, one step back111// Handle `${expression}` inside the template string syntaxRename files (#977)ehmickybefore adoption4b2e316
lines 112–122why, one step back112const parseExpression = expression => {113 const typeOfExpression = typeof expression;114115 if (typeOfExpression === 'string') {116 return expression;117 }118119 if (typeOfExpression === 'number') {120 return String(expression);121 }122Do not set `undefined` properties on the return value (#992)ehmickybefore adoption0d33b6d
line 123why, one step back123 if (isPlainObject(expression) && ('stdout' in expression || 'isMaxBuffer' in expression)) {Refactor logic and rename some variables (#983)ehmickybefore adoptionbd3b478
lines 124–125why, one step back124 return getSubprocessResult(expression);125 }Rename files (#977)ehmickybefore adoption4b2e316
line 126why, one step back126Refactor logic and rename some variables (#983)ehmickybefore adoptionbd3b478
lines 127–129why, one step back127 if (expression instanceof ChildProcess || Object.prototype.toString.call(expression) === '[object Promise]') {128 // eslint-disable-next-line no-template-curly-in-string129 throw new TypeError('Unexpected subprocess in template expression. Please use ${await subprocess} instead of ${subprocess}.');Rename files (#977)ehmickybefore adoption4b2e316
lines 130–134why, one step back130 }131132 throw new TypeError(`Unexpected "${typeOfExpression}" in template expression`);133};134Refactor logic and rename some variables (#983)ehmickybefore adoptionbd3b478
lines 135–149why, one step back135const getSubprocessResult = ({stdout}) => {136 if (typeof stdout === 'string') {137 return stdout;138 }139140 if (isUint8Array(stdout)) {141 return uint8ArrayToString(stdout);142 }143144 if (stdout === undefined) {145 throw new TypeError('Missing result.stdout in template expression. This is probably due to the previous subprocess\' "stdout" option.');146 }147148 throw new TypeError(`Unexpected "${typeof stdout}" stdout in template expression`);149};