protoc-gen-buffa 0.7.0

protoc plugin for generating Rust code with buffa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
//! protoc plugin for generating Rust code with buffa.
//!
//! This binary follows the protoc plugin protocol:
//! 1. Read a serialized `CodeGeneratorRequest` from stdin.
//! 2. Pass the file descriptors to `buffa-codegen`.
//! 3. Write a serialized `CodeGeneratorResponse` to stdout.
//!
//! Usage:
//!   protoc --buffa_out=. my_service.proto
//!
//! Or with buf:
//!   # buf.gen.yaml
//!   plugins:
//!     - local: protoc-gen-buffa
//!       out: src/gen

use std::io::{self, Read, Write};

use buffa::Message;
use buffa_codegen::generated::compiler::code_generator_response::File as CodeGeneratorResponseFile;
use buffa_codegen::generated::compiler::{CodeGeneratorRequest, CodeGeneratorResponse};
use buffa_codegen::generated::descriptor::Edition;

use buffa_codegen::CodeGenConfig;

const HELP: &str = "\
protoc-gen-buffa — protoc plugin for generating Rust code with buffa.

This binary speaks the protoc plugin protocol: it reads a serialized
CodeGeneratorRequest from stdin and writes a CodeGeneratorResponse to
stdout. It is not intended to be invoked directly. Use it via protoc
or buf (with this binary on PATH):

  protoc --buffa_out=. my_service.proto

  # buf.gen.yaml
  plugins:
    - local: protoc-gen-buffa
      out: src/gen

To point protoc at a binary not on PATH, use
  --plugin=protoc-gen-buffa=/abs/path/to/protoc-gen-buffa

For a generated mod.rs module tree, also configure
protoc-gen-buffa-packaging.

Options are passed as a comma-separated parameter string, e.g.
  --buffa_opt=views=true,json=true,extern_path=.my.pkg=::my_crate

See <https://github.com/anthropics/buffa/blob/main/docs/guide.md> for
the full option list.";

fn main() {
    if let Some(arg) = std::env::args().nth(1) {
        match arg.as_str() {
            "--version" | "-V" => {
                println!("{} {}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));
                return;
            }
            "--help" | "-h" => {
                println!("{HELP}");
                return;
            }
            other => {
                eprintln!(
                    "{}: unrecognized argument {other:?}. This is a protoc \
                     plugin; run with --help for usage.",
                    env!("CARGO_PKG_NAME")
                );
                std::process::exit(2);
            }
        }
    }
    match run() {
        Ok(()) => {}
        Err(e) => {
            // Protocol: write a response with an error string, don't just crash.
            let response = CodeGeneratorResponse {
                error: Some(format!("{}", e)),
                supported_features: Some(feature_flags()),
                ..Default::default()
            };
            write_response(&response).unwrap_or_else(|io_err| {
                eprintln!(
                    "protoc-gen-buffa: failed to write error response: {}",
                    io_err
                );
                std::process::exit(1);
            });
        }
    }
}

fn run() -> Result<(), Box<dyn std::error::Error>> {
    // Read the entire request from stdin.
    let mut input = Vec::new();
    io::stdin().read_to_end(&mut input)?;

    // Decode the CodeGeneratorRequest.
    let request = CodeGeneratorRequest::decode_from_slice(&input)
        .map_err(|e| format!("failed to decode CodeGeneratorRequest: {}", e))?;

    // Parse plugin parameters (e.g., "views=true,unknown_fields=false").
    let config = parse_config(request.parameter.as_deref().unwrap_or(""))?;

    // Run code generation.
    let generated = buffa_codegen::generate(
        &request.proto_file,
        &request.file_to_generate,
        &config.codegen,
    )?;

    // Build the response. `generated` is consumed here so the names and
    // contents move directly into the response rather than being cloned.
    let files: Vec<CodeGeneratorResponseFile> = generated
        .into_iter()
        .map(|g| CodeGeneratorResponseFile {
            name: Some(g.name),
            content: Some(g.content),
            ..Default::default()
        })
        .collect();

    let response = CodeGeneratorResponse {
        supported_features: Some(feature_flags()),
        // Tell protoc which editions we support.
        minimum_edition: Some(Edition::EDITION_PROTO2 as i32),
        maximum_edition: Some(Edition::EDITION_2024 as i32),
        file: files,
        ..Default::default()
    };

    write_response(&response)?;
    Ok(())
}

/// Write the serialized CodeGeneratorResponse to stdout.
fn write_response(response: &CodeGeneratorResponse) -> io::Result<()> {
    let mut output = Vec::new();
    response.encode(&mut output);
    io::stdout().write_all(&output)?;
    io::stdout().flush()?;
    Ok(())
}

/// Feature flags we support (bitmask).
fn feature_flags() -> u64 {
    const FEATURE_PROTO3_OPTIONAL: u64 = 1;
    const FEATURE_SUPPORTS_EDITIONS: u64 = 2;
    FEATURE_PROTO3_OPTIONAL | FEATURE_SUPPORTS_EDITIONS
}

/// Plugin configuration parsed from the parameter string.
struct PluginConfig {
    /// Code generation options passed to buffa-codegen.
    codegen: CodeGenConfig,
}

/// Parse the plugin parameter string into a PluginConfig.
///
/// Parameters are comma-separated key=value pairs:
///   --buffa_opt=views=true,unknown_fields=false,json=true
///
/// Extern paths use the format `extern_path=<proto>=<rust>`, where `<proto>`
/// is either a package or a single type FQN:
///   --buffa_opt=extern_path=.my.common=::common_protos
///   --buffa_opt=extern_path=.my.common.Shared=::shared_types::Shared
fn parse_config(params: &str) -> Result<PluginConfig, String> {
    let mut codegen = CodeGenConfig::default();

    if params.is_empty() {
        return Ok(PluginConfig { codegen });
    }

    for param in params.split(',') {
        let param = param.trim();
        if let Some((key, value)) = param.split_once('=') {
            match key.trim() {
                "views" => codegen.generate_views = value.trim() == "true",
                "unknown_fields" => codegen.preserve_unknown_fields = value.trim() != "false",
                "json" => codegen.generate_json = value.trim() == "true",
                "text" => codegen.generate_text = value.trim() == "true",
                "arbitrary" => codegen.generate_arbitrary = value.trim() == "true",
                // `gate_impls=true` wraps generated impls in `#[cfg(feature = ...)]`
                // instead of emitting them unconditionally. For library crates whose
                // generated code is itself a public dependency surface; most plugin
                // invocations want the default (off).
                "gate_impls" => codegen.gate_impls_on_crate_features = value.trim() == "true",
                "allow_message_set" => codegen.allow_message_set = value.trim() == "true",
                "strict_utf8" | "strict_utf8_mapping" => {
                    codegen.strict_utf8_mapping = value.trim() == "true"
                }
                "register_types" => codegen.emit_register_fn = value.trim() != "false",
                // `with_setters=false` opts out of builder-style setter
                // methods. Like `register_types`, the default is on, so the
                // accepted spelling is the negation.
                "with_setters" => codegen.generate_with_setters = value.trim() != "false",
                // `reflection=true` selects the fast vtable mode (same as
                // `reflect_mode=vtable`); `reflect_mode=bridge` opts into the
                // smaller round-trip implementation.
                "reflection" => {
                    let mode = if value.trim() == "true" {
                        buffa_codegen::ReflectMode::VTable
                    } else {
                        buffa_codegen::ReflectMode::Off
                    };
                    mode.apply(&mut codegen);
                }
                // `reflect_mode=off|bridge|vtable` is the fuller form of
                // `reflection=`. `vtable` additionally emits `impl ReflectMessage`
                // on owned + view types and makes `reflect()` borrow `self`.
                "reflect_mode" => match value.trim() {
                    "off" => buffa_codegen::ReflectMode::Off.apply(&mut codegen),
                    "bridge" => buffa_codegen::ReflectMode::Bridge.apply(&mut codegen),
                    "vtable" => buffa_codegen::ReflectMode::VTable.apply(&mut codegen),
                    other => {
                        eprintln!(
                            "protoc-gen-buffa: invalid reflect_mode '{}', \
                             expected off, bridge, or vtable",
                            other
                        );
                    }
                },
                "file_per_package" => codegen.file_per_package = value.trim() == "true",
                "extern_path" => {
                    // value is "<proto_path>=<rust_path>"
                    if let Some((proto, rust)) = value.split_once('=') {
                        let mut proto = proto.trim().to_string();
                        // Normalize: accept both ".my.pkg" and "my.pkg".
                        if !proto.starts_with('.') {
                            proto.insert(0, '.');
                        }
                        codegen.extern_paths.push((proto, rust.trim().to_string()));
                    } else {
                        eprintln!(
                            "protoc-gen-buffa: invalid extern_path format '{}', \
                             expected 'extern_path=.proto.pkg=::rust::path' \
                             (or a type FQN, 'extern_path=.proto.pkg.Type=::rust::path::Type')",
                            value
                        );
                    }
                }
                "mod_file" => {
                    return Err("the mod_file option was removed in 0.2; use \
                         protoc-gen-buffa-packaging instead. See CHANGELOG \
                         for migration."
                        .to_string());
                }
                other => {
                    eprintln!("protoc-gen-buffa: unknown parameter '{}'", other);
                }
            }
        }
    }

    Ok(PluginConfig { codegen })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn empty_params_returns_defaults() {
        let config = parse_config("").unwrap();
        let defaults = CodeGenConfig::default();
        assert_eq!(config.codegen.generate_views, defaults.generate_views);
        assert_eq!(
            config.codegen.preserve_unknown_fields,
            defaults.preserve_unknown_fields
        );
        assert_eq!(config.codegen.generate_json, defaults.generate_json);
        assert!(config.codegen.extern_paths.is_empty());
    }

    #[test]
    fn views_true() {
        let config = parse_config("views=true").unwrap();
        assert!(config.codegen.generate_views);
    }

    #[test]
    fn views_false() {
        let config = parse_config("views=false").unwrap();
        assert!(!config.codegen.generate_views);
    }

    #[test]
    fn json_true() {
        let config = parse_config("json=true").unwrap();
        assert!(config.codegen.generate_json);
    }

    #[test]
    fn unknown_fields_false() {
        let config = parse_config("unknown_fields=false").unwrap();
        assert!(!config.codegen.preserve_unknown_fields);
    }

    #[test]
    fn unknown_fields_true() {
        let config = parse_config("unknown_fields=true").unwrap();
        assert!(config.codegen.preserve_unknown_fields);
    }

    #[test]
    fn file_per_package_true() {
        let config = parse_config("file_per_package=true").unwrap();
        assert!(config.codegen.file_per_package);
    }

    #[test]
    fn file_per_package_default_is_false() {
        let config = parse_config("").unwrap();
        assert!(!config.codegen.file_per_package);
    }

    #[test]
    fn extern_path_with_leading_dot() {
        let config = parse_config("extern_path=.my.common=::common_protos").unwrap();
        assert_eq!(config.codegen.extern_paths.len(), 1);
        assert_eq!(config.codegen.extern_paths[0].0, ".my.common");
        assert_eq!(config.codegen.extern_paths[0].1, "::common_protos");
    }

    #[test]
    fn extern_path_without_leading_dot_is_normalized() {
        let config = parse_config("extern_path=my.common=::common_protos").unwrap();
        assert_eq!(config.codegen.extern_paths[0].0, ".my.common");
    }

    #[test]
    fn multiple_params() {
        let config = parse_config("views=true,json=true").unwrap();
        assert!(config.codegen.generate_views);
        assert!(config.codegen.generate_json);
    }

    #[test]
    fn multiple_extern_paths() {
        let config =
            parse_config("extern_path=.my.a=::crate_a,extern_path=.my.b=::crate_b").unwrap();
        assert_eq!(config.codegen.extern_paths.len(), 2);
        assert_eq!(config.codegen.extern_paths[0].0, ".my.a");
        assert_eq!(config.codegen.extern_paths[1].0, ".my.b");
    }

    #[test]
    fn whitespace_is_trimmed() {
        let config = parse_config(" views = true , json = true ").unwrap();
        assert!(config.codegen.generate_views);
        assert!(config.codegen.generate_json);
    }

    #[test]
    fn unknown_param_is_ignored() {
        // Should not panic; unknown params produce an eprintln warning.
        let config = parse_config("unknown_key=value").unwrap();
        let defaults = CodeGenConfig::default();
        assert_eq!(config.codegen.generate_views, defaults.generate_views);
    }

    #[test]
    fn invalid_extern_path_is_ignored() {
        // Missing "=" in the value — should not panic.
        let config = parse_config("extern_path=no_equals_sign").unwrap();
        assert!(config.codegen.extern_paths.is_empty());
    }

    #[test]
    fn register_types_false() {
        let config = parse_config("register_types=false").unwrap();
        assert!(!config.codegen.emit_register_fn);
    }

    #[test]
    fn register_types_true() {
        let config = parse_config("register_types=true").unwrap();
        assert!(config.codegen.emit_register_fn);
    }

    #[test]
    fn register_types_default_is_true() {
        let config = parse_config("").unwrap();
        assert!(config.codegen.emit_register_fn);
    }

    #[test]
    fn gate_impls_true() {
        let config = parse_config("gate_impls=true").unwrap();
        assert!(config.codegen.gate_impls_on_crate_features);
    }

    #[test]
    fn gate_impls_default_is_false() {
        let config = parse_config("").unwrap();
        assert!(!config.codegen.gate_impls_on_crate_features);
    }

    #[test]
    fn with_setters_false() {
        let config = parse_config("with_setters=false").unwrap();
        assert!(!config.codegen.generate_with_setters);
    }

    #[test]
    fn with_setters_default_is_true() {
        let config = parse_config("").unwrap();
        assert!(config.codegen.generate_with_setters);
    }

    #[test]
    fn mod_file_errors_with_migration_hint() {
        let err = parse_config("mod_file=mod.rs").err().unwrap();
        assert!(err.contains("protoc-gen-buffa-packaging"));
    }

    #[test]
    fn text_true() {
        let config = parse_config("text=true").unwrap();
        assert!(config.codegen.generate_text);
    }

    #[test]
    fn text_default_is_false() {
        let config = parse_config("").unwrap();
        assert!(!config.codegen.generate_text);
    }

    #[test]
    fn allow_message_set_true() {
        let config = parse_config("allow_message_set=true").unwrap();
        assert!(config.codegen.allow_message_set);
    }

    #[test]
    fn allow_message_set_default_is_false() {
        let config = parse_config("").unwrap();
        assert!(!config.codegen.allow_message_set);
    }
}