Skip to content

Commit

Permalink
Support target prefix in plugin option rewrite_imports (#998)
Browse files Browse the repository at this point in the history
  • Loading branch information
timostamm authored Oct 28, 2024
1 parent f0ca648 commit 1270562
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
28 changes: 28 additions & 0 deletions packages/protoplugin-test/src/rewrite_imports.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
10 changes: 6 additions & 4 deletions packages/protoplugin/src/parameter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,15 +164,17 @@ export function parseParameter<T extends object>(
}
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 <pattern>:<target>",
);
}
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;
Expand Down

0 comments on commit 1270562

Please sign in to comment.