testApplyPatchTakesEscapesEitherWay

tcmts.cli.main.testApplyPatchTakesEscapesEitherWay · #fdiq4rlz · term

In code, a patch's old that's there only with its escapes taken the other way (a line break for \n, a bare backtick for \`, ${ for \${, as JSON makes easy) is found that way when that's once, with new written alike, and said; found more than once so, or taken both ways where new has one, it isn't; a page's text is as written.

import { applyPatch } from "#codebase/tcmts/cli/main";
import assert from "node:assert/strict";

export const testApplyPatchTakesEscapesEitherWay = () => {
  // the source: `a\nb \`c\` \${d}` and a line break
  const src = "export const G = `a\\nb \\`c\\` \\${d}\nnext`;\n";
  const ok = (old: string, nu: string) => {
    const r = applyPatch(src, [{ old, new: nu }], false, 0, "x.ts");
    assert.ok("text" in r, JSON.stringify(r));
    return r;
  };
  const line = ok("a\nb", "A\nB");
  assert.equal(line.text, src.replace("a\\nb", "A\\nB"));
  assert.match(line.notes![0]!, /\\n as the source has it, the two characters backslash and n/);
  assert.equal(ok("`c`", "`e`").text, src.replace("\\`c\\`", "\\`e\\`"));
  assert.equal(ok("${d}", "${f}").text, src.replace("\\${d}", "\\${f}"));
  // a line break that's one in the source stays one
  assert.equal(ok("${d}\nnext", "${e}\nlast").text, src.replace("\\${d}\nnext", "\\${e}\nlast"));
  // as written, nothing to say
  assert.equal(ok("\\`c\\`", "\\`e\\`").notes, undefined);
  const problem = (r: ReturnType<typeof applyPatch>) => (r as { problem: string }).problem;
  // a backtick taken both ways: how to write new's isn't known
  assert.match(
    problem(applyPatch(src, [{ old: "\\`c`", new: "\\`e`" }], false, 0, "x.ts")),
    /in some places and not others/,
  );
  assert.match(
    problem(
      applyPatch(
        "const a = `x\\ny`; const b = `x\\ny`;",
        [{ old: "x\ny", new: "z" }],
        false,
        0,
        "x.ts",
      ),
    ),
    /not found as written: "x\\ny"; found 2 times with \\n as the source has it/,
  );
  assert.match(problem(applyPatch(src, [{ old: "a\nb", new: "x" }])), /^not found/);
}

uses