diff --git a/protobuf-codegen/Cargo.toml b/protobuf-codegen/Cargo.toml index ff6332b57..cf1d01e34 100644 --- a/protobuf-codegen/Cargo.toml +++ b/protobuf-codegen/Cargo.toml @@ -23,7 +23,7 @@ once_cell = "1.10.0" tempfile = "3" protobuf = { path = "../protobuf", version = "=4.0.0-alpha.0" } -protobuf-parse = { path = "../protobuf-parse", version = "=4.0.0-alpha.0" } +protobuf-parse = { path = "../protobuf-parse", version = "=4.0.0-alpha.1" } [[bin]] diff --git a/protobuf-parse/Cargo.toml b/protobuf-parse/Cargo.toml index e79976bd9..bf02b5b62 100644 --- a/protobuf-parse/Cargo.toml +++ b/protobuf-parse/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "protobuf-parse" -version = "4.0.0-alpha.0" +version = "4.0.0-alpha.1" edition = "2021" authors = ["Stepan Koltsov "] license = "MIT" diff --git a/protobuf-parse/src/parser.rs b/protobuf-parse/src/parser.rs index e642ab4c8..34e82a92f 100644 --- a/protobuf-parse/src/parser.rs +++ b/protobuf-parse/src/parser.rs @@ -1,3 +1,4 @@ +use std::collections::HashMap; use std::collections::HashSet; use std::ffi::OsStr; use std::ffi::OsString; @@ -21,6 +22,7 @@ pub struct Parser { pub(crate) protoc: Option, pub(crate) protoc_extra_args: Vec, pub(crate) capture_stderr: bool, + pub(crate) custom_embedded: HashMap, } impl Parser { @@ -97,6 +99,19 @@ impl Parser { self } + /// Adds an embedded `.proto` file to the parser. + /// + /// This allows the parser to use `.proto` files provided as in-memory + /// strings rather than reading them from disk. + pub fn add_custom_embedded( + &mut self, + name: impl Into, + content: impl Into, + ) -> &mut Self { + self.custom_embedded.insert(name.into(), content.into()); + self + } + /// Parse `.proto` files and typecheck them using pure Rust parser of `protoc` command. pub fn parse_and_typecheck(&self) -> anyhow::Result { match &self.which_parser { diff --git a/protobuf-parse/src/pure/parse_and_typecheck.rs b/protobuf-parse/src/pure/parse_and_typecheck.rs index 4101c4be7..0da400945 100644 --- a/protobuf-parse/src/pure/parse_and_typecheck.rs +++ b/protobuf-parse/src/pure/parse_and_typecheck.rs @@ -1,3 +1,4 @@ +use std::collections::HashMap; use std::fmt; use std::fs; use std::io; @@ -53,6 +54,7 @@ where { parsed_files: IndexMap, resolver: R, + custom_embedded: HashMap, } impl Run @@ -144,7 +146,19 @@ where return self.add_file_content(protobuf_path, &resolved); } - let embedded = match protobuf_path.to_str() { + let protobuf_path_str = protobuf_path.to_str(); + + if let Some(content) = self.custom_embedded.get(protobuf_path_str) { + return self.add_file_content( + protobuf_path, + &ResolvedProtoFile { + path: protobuf_path_str.to_string(), + content: content.as_bytes().to_vec(), + }, + ); + } + + let embedded = match protobuf_path_str { "rustproto.proto" => Some(proto::RUSTPROTO_PROTO), "google/protobuf/any.proto" => Some(proto::ANY_PROTO), "google/protobuf/api.proto" => Some(proto::API_PROTO), @@ -253,6 +267,7 @@ pub fn parse_and_typecheck(parser: &Parser) -> anyhow::Result