granc 0.7.5

A dynamic gRPC CLI tool written in Rust (gRPC + Cranc, Crab in Catalan)
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
//! # CLI
//!
//! This module defines the command-line interface of `granc` using `clap`.
//! It enforces strict invariants for arguments using subcommands and argument groups.
use std::path::PathBuf;

use clap::{Args, Parser, Subcommand};

#[derive(Parser, Debug)]
#[command(name = "granc", version, about = "Dynamic gRPC CLI")]
pub struct Cli {
    #[command(subcommand)]
    pub command: Commands,
}

#[derive(Subcommand, Debug)]
pub enum Commands {
    /// Perform a gRPC call to a server.
    ///
    /// Requires a server URI. Can optionally use a local file descriptor set.
    Call {
        /// Endpoint (package.Service/Method)
        #[arg(value_parser = parse_endpoint)]
        endpoint: (String, String),

        /// The server URI to connect to (e.g. http://localhost:50051)
        #[arg(long, short = 'u')]
        uri: String,

        /// "JSON body (Object for Unary, Array for Streaming)"
        #[arg(long, short = 'b', value_parser = parse_body)]
        body: serde_json::Value,

        #[arg(short = 'H', long = "header", value_parser = parse_header)]
        headers: Vec<(String, String)>,

        /// Optional path to a file descriptor set (.bin) to use instead of reflection
        #[arg(long, short = 'f')]
        file_descriptor_set: Option<PathBuf>,
    },

    /// List available services.
    ///
    /// Requires EITHER a server URI (Reflection) OR a file descriptor set (Offline).
    List {
        #[command(flatten)]
        source: SourceSelection,
    },

    /// Describe a service, message or enum.
    ///
    /// Requires EITHER a server URI (Reflection) OR a file descriptor set (Offline).
    Describe {
        #[command(flatten)]
        source: SourceSelection,

        /// Fully qualified name (e.g. my.package.Service)
        symbol: String,
    },

    /// Generate Markdown documentation for a service.
    Doc {
        #[command(flatten)]
        source: SourceSelection,

        /// Fully qualified service name (e.g. my.package.MyService)
        symbol: String,

        /// Output directory for the generated markdown files
        #[arg(long, short = 'o')]
        output: PathBuf,
    },
}

#[derive(Args, Debug)]
#[group(required = true, multiple = false)] // Enforces: Either URI OR FileDescriptorSet, never both.
pub struct SourceSelection {
    /// The server URI to use for reflection-based introspection
    #[arg(long, short = 'u')]
    uri: Option<String>,

    /// Path to the descriptor set (.bin) to use for offline introspection
    #[arg(long, short = 'f')]
    file_descriptor_set: Option<PathBuf>,
}

// The source where to resolve the proto schemas from.
//
// It can either be a URI (If the server supports server streaming)
// or a file (a `.bin` or `.pb` file generated with protoc)
pub enum Source {
    Uri(String),
    File(PathBuf),
}

impl SourceSelection {
    pub fn value(self) -> Source {
        if let Some(uri) = self.uri {
            Source::Uri(uri)
        } else if let Some(path) = self.file_descriptor_set {
            Source::File(path)
        } else {
            // This is unreachable because `clap` verifies the group requirements before we ever get here.
            unreachable!(
                "Clap ensures exactly one argument (uri or file) is present via #[group(required = true)]"
            )
        }
    }
}

fn parse_endpoint(value: &str) -> Result<(String, String), String> {
    let (service, method) = value.split_once('/').ok_or_else(|| {
        format!("Invalid endpoint format: '{value}'. Expected 'package.Service/Method'",)
    })?;

    if service.trim().is_empty() || method.trim().is_empty() {
        return Err("Service and Method names cannot be empty".to_string());
    }

    Ok((service.to_string(), method.to_string()))
}

fn parse_header(s: &str) -> Result<(String, String), String> {
    s.split_once(':')
        .map(|(k, v)| (k.trim().to_string(), v.trim().to_string()))
        .ok_or_else(|| "Format must be 'key:value'".to_string())
}

fn parse_body(value: &str) -> Result<serde_json::Value, String> {
    serde_json::from_str(value).map_err(|e| format!("Invalid JSON: {e}"))
}

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

    #[test]
    fn test_call_command_reflection() {
        let args = vec![
            "granc",
            "call",
            "helloworld.Greeter/SayHello",
            "--uri",
            "http://localhost:50051",
            "--body",
            r#"{"name": "Ferris"}"#,
        ];

        let cli = Cli::try_parse_from(&args).expect("Parsing failed");

        match cli.command {
            Commands::Call {
                endpoint,
                uri,
                body,
                file_descriptor_set,
                ..
            } => {
                assert_eq!(
                    endpoint,
                    ("helloworld.Greeter".to_string(), "SayHello".to_string())
                );
                assert_eq!(uri, "http://localhost:50051");
                assert_eq!(body, serde_json::json!({"name": "Ferris"}));
                assert!(file_descriptor_set.is_none());
            }
            _ => panic!("Expected Call command"),
        }
    }

    #[test]
    fn test_call_command_with_file_descriptor() {
        let args = vec![
            "granc",
            "call",
            "helloworld.Greeter/SayHello",
            "--uri",
            "http://localhost:50051",
            "--body",
            r#"{"name": "Ferris"}"#,
            "--file-descriptor-set",
            "./descriptors.bin",
        ];

        let cli = Cli::try_parse_from(&args).expect("Parsing failed");

        match cli.command {
            Commands::Call {
                file_descriptor_set,
                ..
            } => {
                assert_eq!(
                    file_descriptor_set.unwrap().to_str().unwrap(),
                    "./descriptors.bin"
                );
            }
            _ => panic!("Expected Call command"),
        }
    }

    #[test]
    fn test_call_command_short_flags() {
        let args = vec![
            "granc",
            "call",
            "svc/mthd",
            "-u",
            "http://localhost:50051",
            "-b",
            "{}",
            "-f",
            "desc.bin",
            "-H",
            "auth:bearer",
        ];

        let cli = Cli::try_parse_from(&args).expect("Parsing failed");

        match cli.command {
            Commands::Call {
                uri,
                file_descriptor_set,
                headers,
                body,
                ..
            } => {
                assert_eq!(uri, "http://localhost:50051");
                assert_eq!(file_descriptor_set.unwrap().to_str().unwrap(), "desc.bin");
                assert_eq!(body, serde_json::json!({}));
                assert_eq!(headers[0], ("auth".to_string(), "bearer".to_string()));
            }
            _ => panic!("Expected Call command"),
        }
    }

    #[test]
    fn test_list_command_reflection() {
        let args = vec!["granc", "list", "--uri", "http://localhost:50051"];
        let cli = Cli::try_parse_from(&args).expect("Parsing failed");

        match cli.command {
            Commands::List { source } => {
                assert_eq!(source.uri.unwrap(), "http://localhost:50051");
                assert!(source.file_descriptor_set.is_none());
            }
            _ => panic!("Expected List command"),
        }
    }

    #[test]
    fn test_list_command_offline() {
        let args = vec!["granc", "list", "--file-descriptor-set", "desc.bin"];
        let cli = Cli::try_parse_from(&args).expect("Parsing failed");

        match cli.command {
            Commands::List { source } => {
                assert_eq!(
                    source.file_descriptor_set.unwrap().to_str().unwrap(),
                    "desc.bin"
                );
                assert!(source.uri.is_none());
            }
            _ => panic!("Expected List command"),
        }
    }

    #[test]
    fn test_describe_command() {
        let args = vec![
            "granc",
            "describe",
            "helloworld.Greeter",
            "--uri",
            "http://localhost:50051",
        ];
        let cli = Cli::try_parse_from(&args).expect("Parsing failed");

        match cli.command {
            Commands::Describe { symbol, source } => {
                assert_eq!(symbol, "helloworld.Greeter");
                assert!(source.uri.is_some());
            }
            _ => panic!("Expected Describe command"),
        }
    }

    #[test]
    fn test_doc_command_reflection() {
        let args = vec![
            "granc",
            "doc",
            "my.package.Service",
            "--uri",
            "http://localhost:50051",
            "--output",
            "./docs",
        ];
        let cli = Cli::try_parse_from(&args).expect("Parsing failed");

        match cli.command {
            Commands::Doc {
                symbol,
                source,
                output,
            } => {
                assert_eq!(symbol, "my.package.Service");
                assert_eq!(source.uri.unwrap(), "http://localhost:50051");
                assert_eq!(output.to_str().unwrap(), "./docs");
            }
            _ => panic!("Expected Doc command"),
        }
    }

    #[test]
    fn test_doc_command_offline() {
        let args = vec![
            "granc",
            "doc",
            "my.package.Service",
            "--file-descriptor-set",
            "descriptors.bin",
            "-o",
            "./docs",
        ];
        let cli = Cli::try_parse_from(&args).expect("Parsing failed");

        match cli.command {
            Commands::Doc {
                symbol,
                source,
                output,
            } => {
                assert_eq!(symbol, "my.package.Service");
                assert_eq!(
                    source.file_descriptor_set.unwrap().to_str().unwrap(),
                    "descriptors.bin"
                );
                assert_eq!(output.to_str().unwrap(), "./docs");
            }
            _ => panic!("Expected Doc command"),
        }
    }

    // --- Failure Cases ---

    #[test]
    fn test_fail_invalid_json_body() {
        let args = vec!["granc", "call", "s/m", "-u", "x", "--body", "{invalid_json"];
        let err = Cli::try_parse_from(&args).unwrap_err();
        // Should verify that the error comes from the body parser
        assert!(err.to_string().contains("Invalid JSON"));
    }

    #[test]
    fn test_fail_invalid_endpoint_format() {
        let args = vec![
            "granc",
            "call",
            "OnlyServiceNoMethod", // Missing '/'
            "-u",
            "x",
            "-b",
            "{}",
        ];
        let err = Cli::try_parse_from(&args).unwrap_err();
        assert!(err.to_string().contains("Invalid endpoint format"));
    }

    #[test]
    fn test_fail_list_requires_source() {
        let args = vec!["granc", "list"];
        let err = Cli::try_parse_from(&args).unwrap_err();
        // Clap error for missing required arguments in group
        assert!(err.kind() == clap::error::ErrorKind::MissingRequiredArgument);
    }

    #[test]
    fn test_fail_list_mutual_exclusion() {
        let args = vec![
            "granc",
            "list",
            "--uri",
            "http://host",
            "--file-descriptor-set",
            "file.bin",
        ];
        let err = Cli::try_parse_from(&args).unwrap_err();
        // Clap error for argument conflict
        assert!(err.kind() == clap::error::ErrorKind::ArgumentConflict);
    }

    #[test]
    fn test_fail_describe_mutual_exclusion() {
        let args = vec![
            "granc",
            "describe",
            "Symbol",
            "-u",
            "http://host",
            "-f",
            "file.bin",
        ];
        let err = Cli::try_parse_from(&args).unwrap_err();
        assert!(err.kind() == clap::error::ErrorKind::ArgumentConflict);
    }
}