Correctly generate code if package name is empty.

Fixes #306.
This commit is contained in:
Mitar 2018-10-04 21:25:13 -07:00 committed by Stanley Cheung
parent c727bcc6df
commit a312d85d38
1 changed files with 16 additions and 5 deletions

View File

@ -303,11 +303,12 @@ void PrintCommonJsMessagesDeps(Printer* printer, const FileDescriptor* file) {
string package = file->package(); string package = file->package();
vars["package_name"] = package; vars["package_name"] = package;
printer->Print(vars, "const proto = {};\n");
if (!package.empty()) { if (!package.empty()) {
size_t offset = 0; size_t offset = 0;
size_t dotIndex = package.find('.'); size_t dotIndex = package.find('.');
printer->Print(vars, "const proto = {};\n");
while (dotIndex != string::npos) { while (dotIndex != string::npos) {
vars["current_package_ns"] = package.substr(0, dotIndex); vars["current_package_ns"] = package.substr(0, dotIndex);
printer->Print(vars, "proto.$current_package_ns$ = {};\n"); printer->Print(vars, "proto.$current_package_ns$ = {};\n");
@ -325,9 +326,15 @@ void PrintCommonJsMessagesDeps(Printer* printer, const FileDescriptor* file) {
} }
vars["filename"] = filename; vars["filename"] = filename;
printer->Print( if (!package.empty()) {
vars, printer->Print(
"proto.$package_name$ = require('./$filename$_pb.js');\n\n"); vars,
"proto.$package_name$ = require('./$filename$_pb.js');\n\n");
} else {
printer->Print(
vars,
"const proto = require('./$filename$_pb.js');\n\n");
}
} }
void PrintES6Imports(Printer* printer, const FileDescriptor* file) { void PrintES6Imports(Printer* printer, const FileDescriptor* file) {
@ -946,7 +953,11 @@ class GrpcCodeGenerator : public CodeGenerator {
printer.Print("}); // goog.scope\n\n"); printer.Print("}); // goog.scope\n\n");
break; break;
case ImportStyle::COMMONJS: case ImportStyle::COMMONJS:
printer.Print(vars, "module.exports = proto.$package$;\n\n"); if (!vars["package"].empty()) {
printer.Print(vars, "module.exports = proto.$package$;\n\n");
} else {
printer.Print(vars, "module.exports = proto;\n\n");
}
break; break;
case ImportStyle::TYPESCRIPT: case ImportStyle::TYPESCRIPT:
break; break;