| 519 | // Splits the text parts with POSIX quote removal and inserts the values |
| 520 | // between them. |
| 521 | const parseTemplate = ( |
| 522 | texts: ReadonlyArray<string>, |
| 523 | values: ReadonlyArray<TemplateExpression> |
| 524 | ): Result.Result<Array<Word>, CommandLineError> => { |
| 525 | const words: Array<Word> = [] |
| 526 | // The current word, empty until it starts. An opened quote adds "". |
| 527 | let word: Array<Word> = [] |
| 528 | // The current word is unquoted literal text, so it can be the name of a |
| 529 | // variable assignment. |
| 530 | let plain = true |
| 531 | let braceDepth = 0 |
| 532 | let quote: "'" | "\"" | undefined = undefined |
| 533 | let quotePart = 0 |
| 534 | let part = 0 |
| 535 | |
| 536 | const error = ( |
| 537 | reason: CommandLineError["reason"], |
| 538 | message: string, |
| 539 | at = part |
| 540 | ): Result.Result<never, CommandLineError> => |
| 541 | Result.fail(new CommandLineError({ reason, message: `${message} in template part ${at}` })) |
| 542 | |
| 543 | const endWord = (): void => { |
| 544 | if (word.length === 0) return |
| 545 | const value = word.map(unwrap).join("") |
| 546 | words.push( |
| 547 | word.length === 1 && Redacted.isRedacted(word[0]) |
| 548 | ? word[0] |
| 549 | : word.some(Redacted.isRedacted) |
| 550 | ? Redacted.make(value) |
| 551 | : value |
| 552 | ) |
| 553 | word = [] |
| 554 | plain = true |
| 555 | braceDepth = 0 |
| 556 | } |
| 557 | |
| 558 | const scan = (text: string): Result.Result<never, CommandLineError> | undefined => { |
| 559 | for (let i = 0; i < text.length; i++) { |
| 560 | const char = text[i] |
| 561 | const next = text[i + 1] |
| 562 | if (quote === "'") { |
| 563 | if (char === "'") quote = undefined |
| 564 | else word.push(char) |
| 565 | } else if (quote === "\"") { |
| 566 | if (char === "\"") { |
| 567 | quote = undefined |
| 568 | } else if (char === "\\" && next !== undefined && "$`\"\\\n".includes(next)) { |
| 569 | if (next !== "\n") word.push(next) |
| 570 | i++ |
| 571 | } else if (char === "`") { |
| 572 | return error("UnsupportedSyntax", "Command substitution needs a shell") |
| 573 | } else if (char === "$" && next !== undefined && quotedExpansionStart.test(next)) { |
| 574 | return error("UnsupportedSyntax", `The expansion "$${next}" needs a shell`) |
| 575 | } else { |
| 576 | word.push(char) |
| 577 | } |
| 578 | } else if (isBlank(char)) { |