Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Honor experimental editions in the preamble generated by @bufbuild/protoplugin #644

Merged
merged 3 commits into from
Dec 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
211 changes: 211 additions & 0 deletions packages/protoplugin-test/src/file-preamble.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,211 @@
// Copyright 2021-2023 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import { describe, expect, test } from "@jest/globals";
import { UpstreamProtobuf } from "upstream-protobuf";
import { CodeGeneratorRequest } from "@bufbuild/protobuf";
import type { Schema } from "@bufbuild/protoplugin";
import { createEcmaScriptPlugin } from "@bufbuild/protoplugin";

describe("file preamble", () => {
test("contains plugin name and version", async () => {
const lines = await testGenerate(
{
"x.proto": `syntax="proto3";`,
},
{
pluginName: "pi-plugin",
pluginVersion: "v3.14159",
},
);
expect(lines).toContain("// @generated by pi-plugin v3.14159");
});

test("contains plugin options", async () => {
const lines = await testGenerate(
{
"x.proto": `syntax="proto3";`,
},
{
parameter: "foo=bar,baz",
},
);
expect(lines).toContain(
`// @generated by test v1 with parameter "foo=bar,baz"`,
);
});

test("elides rewrite_imports plugin option", async () => {
const lines = await testGenerate(
{
"x.proto": `syntax="proto3";`,
},
{
parameter:
"foo,rewrite_imports=./test/*_pb.js:@buf/test,rewrite_imports=./test/*_web.js:@buf/web,bar",
},
);
expect(lines).toContain(
`// @generated by test v1 with parameter "foo,bar"`,
);
});

test("contains source file info for proto3", async () => {
const lines = await testGenerate({
"x.proto": `syntax="proto3";`,
});
expect(lines).toContain("// @generated from file x.proto (syntax proto3)");
});

test("contains eslint-disable annotation", async () => {
const lines = await testGenerate({
"x.proto": `syntax="proto3";`,
});
expect(lines).toContain("/* eslint-disable */");
});

test("contains ts-nocheck annotation by default", async () => {
const lines = await testGenerate({
"x.proto": `syntax="proto3";`,
});
expect(lines).toContain("// @ts-nocheck");
});

test("does not contain ts-nocheck annotation when turned off", async () => {
const lines = await testGenerate(
{
"x.proto": `syntax="proto3";`,
},
{
parameter: "ts_nocheck=false",
},
);
expect(lines).not.toContain("// @ts-nocheck");
});

test("contains source file info for proto2", async () => {
const lines = await testGenerate({
"x.proto": `syntax="proto2";`,
});
expect(lines).toContain("// @generated from file x.proto (syntax proto2)");
});

test("contains source file info for edition 2023", async () => {
const lines = await testGenerate({
"x.proto": `edition="2023";`,
});
expect(lines).toContain("// @generated from file x.proto (edition 2023)");
});

test("contains syntax comments", async () => {
const lines = await testGenerate({
"x.proto": `
// comment above...
// ... the syntax declaration
syntax="proto3";
`,
});
const firstLines = lines.slice(
0,
lines.indexOf("// @generated by test v1"),
);
expect(firstLines).toStrictEqual([
"// comment above...",
"// ... the syntax declaration",
"",
]);
});

test("contains syntax comments with edition 2023", async () => {
const lines = await testGenerate({
"x.proto": `
// comment above...
// ... the syntax declaration
edition="2023";
`,
});
const firstLines = lines.slice(
0,
lines.indexOf("// @generated by test v1"),
);
expect(firstLines).toStrictEqual([
"// comment above...",
"// ... the syntax declaration",
"",
]);
});

test("contains package comments", async () => {
const lines = await testGenerate({
"x.proto": `
syntax="proto3";

// comment above...
// ... the package declaration
package foo;
`,
});
const lastLines = lines.slice(lines.indexOf("// @ts-nocheck"));
expect(lastLines).toStrictEqual([
"// @ts-nocheck",
"",
"// comment above...",
"// ... the package declaration",
"",
"const placeholder = 1; // ensure file is not considered empty",
]);
});

// test helper to generate just a file with a preamble for each input proto file
async function testGenerate(
protoFiles: Record<string, string>,
opt?: { parameter?: string; pluginName?: string; pluginVersion?: string },
) {
const plugin = createEcmaScriptPlugin({
name: opt?.pluginName ?? "test",
version: opt?.pluginVersion ?? "v1",
generateTs: generateFileWithPreamble,
generateJs: generateFileWithPreamble,
generateDts: generateFileWithPreamble,
parseOption: () => {
// accept all options
},
});

function generateFileWithPreamble(
schema: Schema,
target: "js" | "ts" | "dts",
) {
for (const file of schema.files) {
const f = schema.generateFile(`${file.name}.${target}`);
f.preamble(file);
f.print(
"const placeholder = 1; // ensure file is not considered empty",
);
}
}

const upstream = new UpstreamProtobuf();
const req = CodeGeneratorRequest.fromBinary(
await upstream.createCodeGeneratorRequest(protoFiles, {
parameter: opt?.parameter,
}),
);
expect(req.protoFile.length).toBe(1);
const res = plugin.run(req);
expect(res.file.length).toBeGreaterThanOrEqual(1);
const content = res.file[0]?.content ?? "";
return content.trim().split("\n");
}
});
121 changes: 1 addition & 120 deletions packages/protoplugin-test/src/transpile.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,7 @@
// limitations under the License.

import { describe, expect, test } from "@jest/globals";
import {
CodeGeneratorRequest,
Edition,
FileDescriptorProto,
} from "@bufbuild/protobuf";
import type { DescFile, FeatureSet } from "@bufbuild/protobuf";
import { CodeGeneratorRequest } from "@bufbuild/protobuf";
import { createEcmaScriptPlugin } from "@bufbuild/protoplugin";
import type { Schema } from "@bufbuild/protoplugin/ecmascript";

Expand Down Expand Up @@ -107,120 +102,6 @@ describe("transpile", function () {
]);
});

describe("file preamble", () => {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure why those tests where here. Moved to a different file and increased coverage.

const fileObj: DescFile = {
kind: "file",
name: "test",
syntax: "proto3",
edition: Edition.EDITION_PROTO3,
messages: [],
deprecated: false,
enums: [],
extensions: [],
services: [],
proto: new FileDescriptorProto(),
toString() {
return "fake DescFile";
},
getPackageComments() {
return {
leadingDetached: [],
sourcePath: [],
leading: undefined,
trailing: undefined,
};
},
getSyntaxComments() {
return {
leadingDetached: [],
sourcePath: [],
leading: undefined,
trailing: undefined,
};
},
getFeatures(): FeatureSet & Required<FeatureSet> {
return null as unknown as FeatureSet & Required<FeatureSet>;
},
};
test("generates correctly", () => {
const linesOf = transpile((schema) => {
const f = schema.generateFile("test.ts");
f.preamble(fileObj);
f.print("export const t = 1;");
});
expect(linesOf("test.ts")).toStrictEqual([
'// @generated by test-plugin v99.0.0 with parameter "target=ts+js+dts"',
"// @generated from file test.proto (syntax proto3)",
"/* eslint-disable */",
"// @ts-nocheck",
"",
"export const t = 1;",
]);
expect(linesOf("test.d.ts")).toStrictEqual([
'// @generated by test-plugin v99.0.0 with parameter "target=ts+js+dts"',
"// @generated from file test.proto (syntax proto3)",
"/* eslint-disable */",
"// @ts-nocheck",
"",
"export declare const t = 1;",
]);
});
test("strips all rewrite_imports if present", () => {
const linesOf = transpile(
(schema) => {
const f = schema.generateFile("test.ts");
f.preamble(fileObj);
f.print("export const t = 1;");
},
"target=ts+js+dts,rewrite_imports=./test/*_pb.js:@buf/test,rewrite_imports=./test/*_web.js:@buf/web,keep_empty_files=true,foo,bar=",
() => {
/* custom parse fn to allow for custom options without erroring*/
},
);

expect(linesOf("test.ts")).toStrictEqual([
'// @generated by test-plugin v99.0.0 with parameter "target=ts+js+dts,keep_empty_files=true,foo,bar="',
"// @generated from file test.proto (syntax proto3)",
"/* eslint-disable */",
"// @ts-nocheck",
"",
"export const t = 1;",
]);
expect(linesOf("test.d.ts")).toStrictEqual([
'// @generated by test-plugin v99.0.0 with parameter "target=ts+js+dts,keep_empty_files=true,foo,bar="',
"// @generated from file test.proto (syntax proto3)",
"/* eslint-disable */",
"// @ts-nocheck",
"",
"export declare const t = 1;",
]);
});
test("does not print parameters if empty", () => {
const linesOf = transpile((schema) => {
const f = schema.generateFile("test.ts");
f.preamble(fileObj);
f.print("export const t = 1;");
}, "rewrite_imports=./test/*_pb.js:@buf/test");

expect(linesOf("test.js")).toStrictEqual([
"// @generated by test-plugin v99.0.0",
"// @generated from file test.proto (syntax proto3)",
"/* eslint-disable */",
"// @ts-nocheck",
"",
"export const t = 1;",
]);
expect(linesOf("test.d.ts")).toStrictEqual([
"// @generated by test-plugin v99.0.0",
"// @generated from file test.proto (syntax proto3)",
"/* eslint-disable */",
"// @ts-nocheck",
"",
"export declare const t = 1;",
]);
});
});

test("unknown type is not inferred correctly", () => {
const linesOf = transpile((schema) => {
const f = schema.generateFile("test.ts");
Expand Down
20 changes: 19 additions & 1 deletion packages/protoplugin/src/ecmascript/gencommon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
DescMethod,
DescOneof,
DescService,
Edition,
LongType,
ScalarType,
} from "@bufbuild/protobuf";
Expand Down Expand Up @@ -67,7 +68,24 @@ export function makeFilePreamble(
if (file.proto.package !== undefined) {
builder.push(`package ${file.proto.package}, `);
}
builder.push(`syntax ${file.syntax})\n`);
switch (file.edition) {
case Edition.EDITION_PROTO2:
builder.push(`syntax proto2)\n`);
break;
case Edition.EDITION_PROTO3:
builder.push(`syntax proto3)\n`);
break;
default: {
const editionString = Edition[file.edition] as string | undefined;
if (typeof editionString == "string") {
const e = editionString.replace("EDITION_", "").toLowerCase();
builder.push(`edition ${e})\n`);
} else {
builder.push(`unknown edition\n`);
}
break;
}
}
builder.push("/* eslint-disable */\n");
if (tsNoCheck) {
builder.push("// @ts-nocheck\n");
Expand Down