Created
June 8, 2021 12:48
-
-
Save robinlinden/08bd4f0762cdc63bdfc48fd258824ab9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <google/protobuf/compiler/code_generator.h> | |
#include <google/protobuf/compiler/command_line_interface.h> | |
#include <google/protobuf/compiler/plugin.h> | |
#include <google/protobuf/compiler/cpp/cpp_helpers.h> | |
#include <google/protobuf/io/printer.h> | |
#include <google/protobuf/io/zero_copy_stream.h> | |
#include <map> | |
#include <memory> | |
#include <string> | |
namespace { | |
void GenerateHeader(auto *printer, auto const &args) { | |
printer->Print(args, | |
"#ifndef C_DTO_$filename_identifier$_H_\n" | |
"#define C_DTO_$filename_identifier$_H_\n" | |
"#endif\n"); | |
} | |
void GenerateSource(auto *printer, auto const &args) { | |
printer->Print(args, | |
"#include \"$filename$.h\"\n"); | |
} | |
class DtoGenerator : public google::protobuf::compiler::CodeGenerator { | |
public: | |
bool Generate(google::protobuf::FileDescriptor const *file, | |
std::string const ¶meter, | |
google::protobuf::compiler::OutputDirectory *out_dir, | |
std::string *err) const { | |
using namespace google::protobuf; | |
std::string basename = compiler::cpp::StripProto(file->name()); | |
basename.append(".c_dto"); | |
std::map<std::string, std::string> args{ | |
{"filename", basename}, | |
{"filename_identifier", compiler::cpp::FilenameIdentifier(file->name())}, | |
}; | |
// Generate header. | |
std::unique_ptr<io::ZeroCopyOutputStream> h_out{out_dir->Open(basename + ".h")}; | |
io::Printer h_printer(h_out.get(), '$'); | |
GenerateHeader(&h_printer, args); | |
// Generate source. | |
std::unique_ptr<io::ZeroCopyOutputStream> c_out{out_dir->Open(basename + ".c")}; | |
io::Printer c_printer(c_out.get(), '$'); | |
GenerateSource(&c_printer, args); | |
return true; | |
} | |
}; | |
} // namespace | |
int main(int argc, char **argv) { | |
DtoGenerator generator{}; | |
if (true) { | |
google::protobuf::compiler::CommandLineInterface cli; | |
cli.RegisterGenerator("--cxx_dto_out", &generator, "Generate C++ dtos."); | |
cli.SetVersionInfo("0.0.1"); | |
return cli.Run(argc, argv); | |
} | |
return google::protobuf::compiler::PluginMain(argc, argv, &generator); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment