Skip to content

Commit 92dd27c

Browse files
igor-sirotincopybara-github
authored andcommitted
feat: --<lang>_prefix cli option (#24824)
Closes #23509 # Description - Add per-plugin `--<lang>_prefix=COMMAND` flag to `protoc`, allowing a plugin to be invoked through a user-supplied command wrapper. - `<lang>` matches the plugin used by `--<lang>_out`, so different plugins can use different wrappers in a single invocation. - protoc executes `COMMAND <plugin>`; COMMAND's first token is resolved via the search path (PATH), the value is tokenized on whitespace into argv, and quotes are rejected at parse time. Use a wrapper script for more complex invocations. - Wrapper still honours custom plugin paths set with `--plugin`. - Cross-platform tests (POSIX shell scripts; Windows `.bat`) cover happy-path invocation, argument forwarding, PATH-based resolution, missing executable, duplicate flags, empty values, and quote rejection. # Naming Earlier revisions of this PR used a single global `--plugin-command-prefix` flag. Per #23509 (comment), this PR now uses per-plugin `--<lang>_prefix` to match the existing `--<lang>_out` / `--<lang>_opt` convention. # Testing I've tested this in https://github.com/status-im/status-go with this command in `messaging/layers/encryption/`: ``` protoc --go_prefix="go tool" --go_out=. ./messaging/layers/encryption/protocol_message.proto ``` Closes #24824 COPYBARA_INTEGRATE_REVIEW=#24824 from igor-sirotin:main d68d588 PiperOrigin-RevId: 917294550
1 parent ea4cdef commit 92dd27c

5 files changed

Lines changed: 309 additions & 28 deletions

File tree

‎src/google/protobuf/compiler/command_line_interface.cc‎

Lines changed: 53 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -300,10 +300,12 @@ void AddDefaultProtoPaths(
300300

301301
std::string PluginName(absl::string_view plugin_prefix,
302302
absl::string_view directive) {
303-
// Assuming the directive starts with "--" and ends with "_out" or "_opt",
304-
// strip the "--" and "_out/_opt" and add the plugin prefix.
303+
// Assuming the directive starts with "--" and ends with one of "_out",
304+
// "_opt", or "_prefix", strip the "--" and the trailing "_..." segment and
305+
// add the plugin prefix.
306+
size_t suffix_start = directive.find_last_of('_');
305307
return absl::StrCat(plugin_prefix, "gen-",
306-
directive.substr(2, directive.size() - 6));
308+
directive.substr(2, suffix_start - 2));
307309
}
308310

309311
bool GetBootstrapParam(const std::string& parameter) {
@@ -2586,6 +2588,28 @@ CommandLineInterface::InterpretArgument(const std::string& name,
25862588
parameters->append(",");
25872589
}
25882590
parameters->append(value);
2591+
} else if (absl::StartsWith(name, "--") &&
2592+
absl::EndsWith(name, "_prefix")) {
2593+
std::string plugin_name = PluginName(plugin_prefix_, name);
2594+
if (plugin_command_prefixes_.find(plugin_name) !=
2595+
plugin_command_prefixes_.end()) {
2596+
std::cerr << name << " may only be passed once." << std::endl;
2597+
return PARSE_ARGUMENT_FAIL;
2598+
}
2599+
if (value.find_first_of("\"'") != std::string::npos) {
2600+
std::cerr << name
2601+
<< ": quotes are not supported in the value. Use a "
2602+
"wrapper script for more complex invocations."
2603+
<< std::endl;
2604+
return PARSE_ARGUMENT_FAIL;
2605+
}
2606+
std::vector<std::string> tokens = absl::StrSplit(
2607+
value, absl::ByAnyChar(" \t"), absl::SkipWhitespace());
2608+
if (tokens.empty()) {
2609+
std::cerr << name << " requires a non-empty value." << std::endl;
2610+
return PARSE_ARGUMENT_FAIL;
2611+
}
2612+
plugin_command_prefixes_[plugin_name] = std::move(tokens);
25892613
} else {
25902614
std::cerr << "Unknown flag: " << name << std::endl;
25912615
return PARSE_ARGUMENT_FAIL;
@@ -2717,7 +2741,15 @@ Parse PROTO_FILES and generate output based on the options given:
27172741
Additionally, EXECUTABLE may be of the form
27182742
NAME=PATH, in which case the given plugin name
27192743
is mapped to the given executable even if
2720-
the executable's own name differs.)";
2744+
the executable's own name differs.
2745+
--<lang>_prefix=COMMAND Runs the plugin used by --<lang>_out via
2746+
COMMAND. protoc executes "COMMAND <plugin>"
2747+
instead of invoking the plugin binary directly.
2748+
COMMAND's first token is resolved via the
2749+
search path (PATH). The value is split into
2750+
argv tokens on whitespace; quotes are not
2751+
supported. Use a wrapper script for more
2752+
complex invocations.)";
27212753
}
27222754

27232755
for (const auto& kv : generators_by_flag_name_) {
@@ -3073,10 +3105,24 @@ bool CommandLineInterface::GeneratePluginOutput(
30733105
// Invoke the plugin.
30743106
Subprocess subprocess;
30753107

3076-
if (plugins_.count(plugin_name) > 0) {
3077-
subprocess.Start(plugins_[plugin_name], Subprocess::EXACT_NAME);
3108+
const auto plugin_it = plugins_.find(plugin_name);
3109+
const bool has_registered_path = plugin_it != plugins_.end();
3110+
const std::string executable =
3111+
has_registered_path ? plugin_it->second : plugin_name;
3112+
3113+
const auto prefix_it = plugin_command_prefixes_.find(plugin_name);
3114+
if (prefix_it == plugin_command_prefixes_.end()) {
3115+
subprocess.Start(executable, has_registered_path ? Subprocess::EXACT_NAME
3116+
: Subprocess::SEARCH_PATH);
30783117
} else {
3079-
subprocess.Start(plugin_name, Subprocess::SEARCH_PATH);
3118+
// When a prefix is provided, we always execute the prefix first and pass
3119+
// the plugin executable as an argument. If a custom path was registered, we
3120+
// pass that path so the prefix does not need to search for the binary.
3121+
const std::vector<std::string>& prefix_tokens = prefix_it->second;
3122+
std::vector<std::string> args(prefix_tokens.begin() + 1,
3123+
prefix_tokens.end());
3124+
args.push_back(executable);
3125+
subprocess.Start(prefix_tokens.front(), Subprocess::SEARCH_PATH, args);
30803126
}
30813127

30823128
std::string communicate_error;

‎src/google/protobuf/compiler/command_line_interface.h‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -393,6 +393,11 @@ class PROTOC_EXPORT CommandLineInterface {
393393

394394
// See AllowPlugins(). If this is empty, plugins aren't allowed.
395395
std::string plugin_prefix_;
396+
// Optional per-plugin prefix command used to invoke a plugin. Populated from
397+
// --<lang>_prefix. The key is the resolved plugin name (e.g.
398+
// "protoc-gen-foo"), the value is the prefix command split into argv tokens.
399+
absl::flat_hash_map<std::string, std::vector<std::string>>
400+
plugin_command_prefixes_;
396401

397402
// Maps specific plugin names to files. When executing a plugin, this map
398403
// is searched first to find the plugin executable. If not found here, the

‎src/google/protobuf/compiler/command_line_interface_unittest.cc‎

Lines changed: 196 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616
#include <cstddef>
1717
#include <cstdint>
18+
#include <cstdlib>
1819

1920
#include <gmock/gmock.h>
2021
#include "absl/log/absl_check.h"
@@ -576,6 +577,201 @@ TEST_F(CommandLineInterfaceTest, GeneratorAndPlugin) {
576577
ExpectGenerated("test_plugin", "", "foo.proto", "Foo");
577578
}
578579

580+
TEST_F(CommandLineInterfaceTest, PluginPrefixInvokesWrapper) {
581+
CreateTempFile("foo.proto",
582+
"syntax = \"proto2\";\n"
583+
"message Foo {}\n");
584+
585+
std::string wrapper_path;
586+
#ifdef _WIN32
587+
const std::string wrapper_name = "plugin_wrapper.bat";
588+
CreateTempFile(wrapper_name,
589+
"@echo off\r\n"
590+
"echo wrapped > \"%~dp0wrapper_invoked.txt\"\r\n"
591+
"\"%~1\"\r\n"
592+
"exit /b %errorlevel%\r\n");
593+
wrapper_path = absl::StrCat(temp_directory(), "/", wrapper_name);
594+
#else
595+
const std::string wrapper_name = "plugin_wrapper.sh";
596+
CreateTempFile(wrapper_name,
597+
"#!/bin/sh\n"
598+
"LOG_DIR=$(cd \"$(dirname \"$0\")\" && pwd)\n"
599+
"echo wrapped > \"${LOG_DIR}/wrapper_invoked.txt\"\n"
600+
"exec \"$@\"\n");
601+
wrapper_path = absl::StrCat(temp_directory(), "/", wrapper_name);
602+
ASSERT_EQ(0, chmod(wrapper_path.c_str(), 0777));
603+
#endif
604+
605+
Run(absl::StrCat("protocol_compiler --plug_prefix=", wrapper_path,
606+
" --plug_out=$tmpdir --proto_path=$tmpdir foo.proto"));
607+
608+
ExpectNoErrors();
609+
ExpectGenerated("test_plugin", "", "foo.proto", "Foo");
610+
ExpectFileContentContainsSubstring("wrapper_invoked.txt", "wrapped");
611+
}
612+
613+
TEST_F(CommandLineInterfaceTest, PluginPrefixForwardsArguments) {
614+
CreateTempFile("foo.proto",
615+
"syntax = \"proto2\";\n"
616+
"message Foo {}\n");
617+
618+
// Wrapper records the prefix-supplied args, then invokes the plugin
619+
// (the final argv element appended by protoc).
620+
std::string wrapper_path;
621+
#ifdef _WIN32
622+
// Batch %1/%2/... tokenize on '=' (and ',' ';'), which would split
623+
// "--bar=baz" into two parameters. Record the raw, un-split argument tail
624+
// via %* instead, and take the last token (the plugin path appended by
625+
// protoc) to invoke.
626+
CreateTempFile("plugin_wrapper_args.bat",
627+
"@echo off\r\n"
628+
// %* is the raw, untokenized arg tail; %~dp0 is the script's
629+
// own dir, so the record lands where the test can read it.
630+
"echo %*>>\"%~dp0wrapper_argv.txt\"\r\n"
631+
// Start clean before recovering the plugin path.
632+
"set \"plugin=\"\r\n"
633+
// Loop leaves %%A holding the last token: the plugin path
634+
// protoc appended (positional %1/%2 are unreliable here).
635+
"for %%A in (%*) do set \"plugin=%%A\"\r\n"
636+
// Run the plugin
637+
"\"%plugin%\"\r\n"
638+
"exit /b %errorlevel%\r\n");
639+
wrapper_path = absl::StrCat(temp_directory(), "/plugin_wrapper_args.bat");
640+
#else
641+
CreateTempFile("plugin_wrapper_args.sh",
642+
"#!/bin/sh\n"
643+
// Record every argument (prefix tokens + appended plugin
644+
// path), one per line, where the test can read it.
645+
"for arg in \"$@\"; do\n"
646+
" printf '%s\\n' \"$arg\" >> \"$tmpdir/wrapper_argv.txt\"\n"
647+
"done\n"
648+
// Drop the two prefix tokens; what remains is the plugin path.
649+
"shift 2\n"
650+
// Exec the plugin
651+
"exec \"$@\"\n");
652+
wrapper_path = absl::StrCat(temp_directory(), "/plugin_wrapper_args.sh");
653+
ASSERT_EQ(0, chmod(wrapper_path.c_str(), 0777));
654+
#endif
655+
656+
// Pass the prefix value as a single argv element so the embedded spaces
657+
// form multiple tokens (Run() splits on whitespace; RunWithArgs does not).
658+
RunWithArgs({
659+
"protocol_compiler",
660+
absl::StrCat("--plug_prefix=", wrapper_path, " --foo --bar=baz"),
661+
"--plug_out=$tmpdir",
662+
"--proto_path=$tmpdir",
663+
"foo.proto",
664+
});
665+
666+
ExpectNoErrors();
667+
ExpectGenerated("test_plugin", "", "foo.proto", "Foo");
668+
ExpectFileContentContainsSubstring("wrapper_argv.txt", "--foo");
669+
ExpectFileContentContainsSubstring("wrapper_argv.txt", "--bar=baz");
670+
}
671+
672+
TEST_F(CommandLineInterfaceTest, PluginPrefixFromSearchPath) {
673+
CreateTempFile("foo.proto",
674+
"syntax = \"proto2\";\n"
675+
"message Foo {}\n");
676+
677+
#ifdef _WIN32
678+
const std::string wrapper_basename = "plugin_wrapper_searchpath.bat";
679+
CreateTempFile(wrapper_basename,
680+
"@echo off\r\n"
681+
"echo wrapped > \"%~dp0wrapper_invoked.txt\"\r\n"
682+
"\"%~1\"\r\n"
683+
"exit /b %errorlevel%\r\n");
684+
const char path_separator = ';';
685+
#else
686+
const std::string wrapper_basename = "plugin_wrapper_searchpath.sh";
687+
CreateTempFile(wrapper_basename,
688+
"#!/bin/sh\n"
689+
"echo wrapped > \"$tmpdir/wrapper_invoked.txt\"\n"
690+
"exec \"$@\"\n");
691+
ASSERT_EQ(0,
692+
chmod(absl::StrCat(temp_directory(), "/", wrapper_basename).c_str(),
693+
0777));
694+
const char path_separator = ':';
695+
#endif
696+
697+
// Prepend the temp directory to PATH so the wrapper can be located by
698+
// basename only (Subprocess uses execvp / SEARCH_PATH for the prefix).
699+
const char* old_path_cstr = getenv("PATH");
700+
const std::string old_path = old_path_cstr ? old_path_cstr : "";
701+
const std::string new_path =
702+
absl::StrCat(temp_directory(), std::string(1, path_separator), old_path);
703+
#ifdef _WIN32
704+
_putenv_s("PATH", new_path.c_str());
705+
#else
706+
setenv("PATH", new_path.c_str(), 1);
707+
#endif
708+
709+
Run(absl::StrCat("protocol_compiler --plug_prefix=", wrapper_basename,
710+
" --plug_out=$tmpdir --proto_path=$tmpdir foo.proto"));
711+
712+
#ifdef _WIN32
713+
_putenv_s("PATH", old_path.c_str());
714+
#else
715+
setenv("PATH", old_path.c_str(), 1);
716+
#endif
717+
718+
ExpectNoErrors();
719+
ExpectGenerated("test_plugin", "", "foo.proto", "Foo");
720+
ExpectFileContentContainsSubstring("wrapper_invoked.txt", "wrapped");
721+
}
722+
723+
TEST_F(CommandLineInterfaceTest, PluginPrefixRejectsEmptyValue) {
724+
CreateTempFile("foo.proto",
725+
"syntax = \"proto2\";\n"
726+
"message Foo {}\n");
727+
728+
Run("protocol_compiler --plug_prefix= "
729+
"--plug_out=$tmpdir --proto_path=$tmpdir foo.proto");
730+
731+
ExpectErrorSubstring("--plug_prefix");
732+
ExpectErrorSubstring("non-empty value");
733+
}
734+
735+
TEST_F(CommandLineInterfaceTest, PluginPrefixRejectsDuplicate) {
736+
CreateTempFile("foo.proto",
737+
"syntax = \"proto2\";\n"
738+
"message Foo {}\n");
739+
740+
Run("protocol_compiler --plug_prefix=foo --plug_prefix=bar "
741+
"--plug_out=$tmpdir --proto_path=$tmpdir foo.proto");
742+
743+
ExpectErrorSubstring("--plug_prefix");
744+
ExpectErrorSubstring("only be passed once");
745+
}
746+
747+
TEST_F(CommandLineInterfaceTest, PluginPrefixRejectsQuotes) {
748+
CreateTempFile("foo.proto",
749+
"syntax = \"proto2\";\n"
750+
"message Foo {}\n");
751+
752+
RunWithArgs({
753+
"protocol_compiler",
754+
"--plug_prefix=\"my cmd\"",
755+
"--plug_out=$tmpdir",
756+
"--proto_path=$tmpdir",
757+
"foo.proto",
758+
});
759+
760+
ExpectErrorSubstring("--plug_prefix");
761+
ExpectErrorSubstring("quotes are not supported");
762+
}
763+
764+
TEST_F(CommandLineInterfaceTest, PluginPrefixMissingExecutable) {
765+
CreateTempFile("foo.proto",
766+
"syntax = \"proto2\";\n"
767+
"message Foo {}\n");
768+
769+
Run("protocol_compiler --plug_prefix=/nonexistent/path/to/wrapper "
770+
"--plug_out=$tmpdir --proto_path=$tmpdir foo.proto");
771+
772+
ExpectErrorSubstring("Plugin failed");
773+
}
774+
579775
TEST_F(CommandLineInterfaceTest, GeneratorAndPlugin_DescriptorSetIn) {
580776
// Invoke a generator and a plugin at the same time.
581777

0 commit comments

Comments
 (0)