From 1270562ed3c2c3e465a22e2d72f618b51f88b77f Mon Sep 17 00:00:00 2001 From: Timo Stamm Date: Mon, 28 Oct 2024 15:22:02 +0100 Subject: [PATCH] Support target prefix in plugin option rewrite_imports (#998) --- .../src/rewrite_imports.test.ts | 28 +++++++++++++++++++ packages/protoplugin/src/parameter.ts | 10 ++++--- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/packages/protoplugin-test/src/rewrite_imports.test.ts b/packages/protoplugin-test/src/rewrite_imports.test.ts index 33508c34b..ac47ae874 100644 --- a/packages/protoplugin-test/src/rewrite_imports.test.ts +++ b/packages/protoplugin-test/src/rewrite_imports.test.ts @@ -47,6 +47,34 @@ describe("rewrite_imports", function () { "Foo", ]); }); + test("should rewrite to target with package prefix", async () => { + const lines = await testGenerate( + "target=ts,rewrite_imports=@scope/pkg:npm:@scope/pkg", + (f) => { + const Foo = f.import("Foo", "@scope/pkg"); + f.print`${Foo}`; + }, + ); + expect(lines).toStrictEqual([ + 'import { Foo } from "npm:@scope/pkg";', + "", + "Foo", + ]); + }); + test("should rewrite to target with package prefix and subpath", async () => { + const lines = await testGenerate( + "target=ts,rewrite_imports=@scope/pkg/subpath:npm:@scope/pkg/subpath", + (f) => { + const Foo = f.import("Foo", "@scope/pkg/subpath"); + f.print`${Foo}`; + }, + ); + expect(lines).toStrictEqual([ + 'import { Foo } from "npm:@scope/pkg/subpath";', + "", + "Foo", + ]); + }); async function testGenerate( parameter: string, diff --git a/packages/protoplugin/src/parameter.ts b/packages/protoplugin/src/parameter.ts index 6401539a6..cbceaaa72 100644 --- a/packages/protoplugin/src/parameter.ts +++ b/packages/protoplugin/src/parameter.ts @@ -164,15 +164,17 @@ export function parseParameter( } break; case "rewrite_imports": { - const parts = value.split(":"); - if (parts.length !== 2) { + const i = value.indexOf(":"); + if (i < 0) { throw new PluginOptionError( raw, "must be in the form of :", ); } - const [pattern, target] = parts; - rewriteImports.push({ pattern, target }); + rewriteImports.push({ + pattern: value.substring(0, i), + target: value.substring(i + 1), + }); // rewrite_imports can be noisy and is more of an implementation detail // so we strip it out of the preamble sanitize = true;