python-proto-importer 0.1.4

Rust-based CLI to streamline Python gRPC/Protobuf workflows: generate code, stabilize imports, and run type checks.
Documentation
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
use crate::config::AppConfig;
use anyhow::{Context, Result};
use glob::glob;
use std::fs;
use std::process::Command;
use tempfile::NamedTempFile;

pub struct ProtocRunner<'a> {
    cfg: &'a AppConfig,
}

impl<'a> ProtocRunner<'a> {
    pub fn new(cfg: &'a AppConfig) -> Self {
        Self { cfg }
    }

    pub fn generate(&self) -> Result<Vec<u8>> {
        // 1) Create descriptor set
        let fds = NamedTempFile::new().context("create temp file for descriptor set")?;
        let fds_path = fds.path().to_path_buf();

        // ensure output directory exists
        if let Err(e) = std::fs::create_dir_all(&self.cfg.out) {
            return Err(e).context(format!(
                "failed to create output directory: {}",
                self.cfg.out.display()
            ));
        }

        // Include paths
        let mut args: Vec<String> = Vec::new();
        for inc in &self.cfg.include {
            args.push(format!("--proto_path={}", inc.display()));
        }
        // Inputs (designed to delegate glob to Python, but v0.1 passes strings directly)
        let inputs = &self.cfg.inputs;

        // python -m grpc_tools.protoc ...
        // Use specified python_exe (uv/python3)
        let py = &self.cfg.python_exe;
        let mut cmd = Command::new(py);

        // Handle uv-specific command structure
        if py == "uv" {
            cmd.arg("run").arg("-m").arg("grpc_tools.protoc");
        } else {
            cmd.arg("-m").arg("grpc_tools.protoc");
        }
        // Ensure protoc plugins installed in the same env are discoverable
        if let Some(parent_str) = std::path::Path::new(py)
            .parent()
            .and_then(|p| p.to_str())
            .filter(|s| !s.is_empty())
            .filter(|s| std::path::Path::new(s).exists())
        {
            use std::env;
            let mut buf = std::ffi::OsString::new();
            buf.push(parent_str);
            buf.push(if cfg!(windows) { ";" } else { ":" });
            if let Some(existing) = env::var_os("PATH") {
                buf.push(existing);
            }
            cmd.env("PATH", buf);
        }

        // Output directories
        cmd.arg(format!("--python_out={}", self.cfg.out.display()));
        cmd.arg(format!("--grpc_python_out={}", self.cfg.out.display()));

        // Optional mypy/mypy_grpc output
        if self.cfg.generate_mypy {
            cmd.arg(format!("--mypy_out={}", self.cfg.out.display()));
        }
        if self.cfg.generate_mypy_grpc {
            cmd.arg(format!("--mypy_grpc_out={}", self.cfg.out.display()));
        }

        // Descriptor set output
        cmd.arg("--include_imports");
        cmd.arg(format!("--descriptor_set_out={}", fds_path.display()));

        // Add include paths and process inputs
        for a in &args {
            cmd.arg(a);
        }
        // Expand globs in inputs (v0.1: perform expansion here)
        // Filter files to only include those under specified include paths
        for pattern in inputs {
            let mut matched_any = false;
            if let Ok(paths) = glob(pattern) {
                for entry in paths.flatten() {
                    // Check if the file is under any of the include paths
                    let should_include = self.cfg.include.iter().any(|inc_path| {
                        // Try canonical path comparison first (most accurate)
                        match (entry.canonicalize(), inc_path.canonicalize()) {
                            (Ok(entry_canonical), Ok(inc_canonical)) => {
                                entry_canonical.starts_with(&inc_canonical)
                            },
                            _ => {
                                // Fallback to string-based comparison if canonicalization fails
                                // This handles cases where files/directories don't exist yet
                                entry.starts_with(inc_path) ||
                                // Also try relative path normalization
                                entry.strip_prefix("./").unwrap_or(&entry).starts_with(inc_path.strip_prefix("./").unwrap_or(inc_path))
                            }
                        }
                    });

                    if should_include {
                        cmd.arg(entry);
                        matched_any = true;
                    }
                }
            }
            if !matched_any {
                // If no files matched after filtering, don't pass anything
                // This prevents protoc errors for files outside include paths
                tracing::debug!("Pattern {} matched no files within include paths", pattern);
            }
        }

        tracing::info!("running grpc_tools.protoc");
        let output = cmd.output().context("failed to run grpc_tools.protoc")?;
        if !output.status.success() {
            let stdout = String::from_utf8_lossy(&output.stdout);
            let stderr = String::from_utf8_lossy(&output.stderr);
            anyhow::bail!(
                "grpc_tools.protoc failed: status {:?}\nstdout:\n{}\nstderr:\n{}",
                output.status.code(),
                stdout,
                stderr
            );
        }

        // Read and return FDS
        let bytes = fs::read(&fds_path).context("failed to read descriptor_set_out")?;
        Ok(bytes)
    }

    // Helper method for testing - allows inspection of command without execution
    #[cfg(test)]
    pub fn build_command(&self) -> Result<(Command, tempfile::NamedTempFile)> {
        let fds = NamedTempFile::new().context("create temp file for descriptor set")?;
        let fds_path = fds.path().to_path_buf();

        let mut args: Vec<String> = Vec::new();
        for inc in &self.cfg.include {
            args.push(format!("--proto_path={}", inc.display()));
        }

        let py = &self.cfg.python_exe;
        let mut cmd = Command::new(py);

        // Handle uv-specific command structure
        if py == "uv" {
            cmd.arg("run").arg("-m").arg("grpc_tools.protoc");
        } else {
            cmd.arg("-m").arg("grpc_tools.protoc");
        }

        // PATH handling
        if let Some(parent_str) = std::path::Path::new(py)
            .parent()
            .and_then(|p| p.to_str())
            .filter(|s| !s.is_empty())
            .filter(|s| std::path::Path::new(s).exists())
        {
            use std::env;
            let mut buf = std::ffi::OsString::new();
            buf.push(parent_str);
            buf.push(if cfg!(windows) { ";" } else { ":" });
            if let Some(existing) = env::var_os("PATH") {
                buf.push(existing);
            }
            cmd.env("PATH", buf);
        }

        // Output arguments
        cmd.arg(format!("--python_out={}", self.cfg.out.display()));
        cmd.arg(format!("--grpc_python_out={}", self.cfg.out.display()));

        if self.cfg.generate_mypy {
            cmd.arg(format!("--mypy_out={}", self.cfg.out.display()));
        }
        if self.cfg.generate_mypy_grpc {
            cmd.arg(format!("--mypy_grpc_out={}", self.cfg.out.display()));
        }

        cmd.arg("--include_imports");
        cmd.arg(format!("--descriptor_set_out={}", fds_path.display()));

        for a in &args {
            cmd.arg(a);
        }

        // Process inputs with glob expansion and filtering
        for pattern in &self.cfg.inputs {
            if let Ok(paths) = glob(pattern) {
                for entry in paths.flatten() {
                    let should_include = self.cfg.include.iter().any(|inc_path| {
                        match (entry.canonicalize(), inc_path.canonicalize()) {
                            (Ok(entry_canonical), Ok(inc_canonical)) => {
                                entry_canonical.starts_with(&inc_canonical)
                            }
                            _ => {
                                entry.starts_with(inc_path)
                                    || entry.strip_prefix("./").unwrap_or(&entry).starts_with(
                                        inc_path.strip_prefix("./").unwrap_or(inc_path),
                                    )
                            }
                        }
                    });

                    if should_include {
                        cmd.arg(&entry);
                    }
                }
            }
        }

        Ok((cmd, fds))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{AppConfig, Backend, PostProcess};
    use std::fs;
    use tempfile::tempdir;

    fn create_test_config() -> AppConfig {
        AppConfig {
            backend: Backend::Protoc,
            python_exe: "python3".to_string(),
            include: vec![std::path::PathBuf::from(".")],
            inputs: vec!["**/*.proto".to_string()],
            out: std::path::PathBuf::from("generated"),
            generate_mypy: false,
            generate_mypy_grpc: false,
            postprocess: PostProcess {
                relative_imports: true,
                fix_pyi: true,
                create_package: true,
                exclude_google: true,
                pyright_header: false,
                module_suffixes: vec!["_pb2.py".into()],
            },
            verify: None,
        }
    }

    #[test]
    fn new_runner() {
        let config = create_test_config();
        let runner = ProtocRunner::new(&config);
        assert_eq!(runner.cfg.backend as u8, Backend::Protoc as u8);
    }

    #[test]
    fn build_command_basic_args() {
        let config = create_test_config();
        let runner = ProtocRunner::new(&config);
        let (cmd, _temp) = runner.build_command().unwrap();

        let cmd_str = format!("{:?}", cmd);
        assert!(cmd_str.contains("python3"));
        assert!(cmd_str.contains("-m"));
        assert!(cmd_str.contains("grpc_tools.protoc"));
        assert!(cmd_str.contains("--python_out=generated"));
        assert!(cmd_str.contains("--grpc_python_out=generated"));
        assert!(cmd_str.contains("--proto_path=."));
        assert!(cmd_str.contains("--include_imports"));
        assert!(cmd_str.contains("--descriptor_set_out="));
    }

    #[test]
    fn build_command_with_mypy() {
        let mut config = create_test_config();
        config.generate_mypy = true;
        config.generate_mypy_grpc = true;

        let runner = ProtocRunner::new(&config);
        let (cmd, _temp) = runner.build_command().unwrap();

        let cmd_str = format!("{:?}", cmd);
        assert!(cmd_str.contains("--mypy_out=generated"));
        assert!(cmd_str.contains("--mypy_grpc_out=generated"));
    }

    #[test]
    fn build_command_multiple_include_paths() {
        let mut config = create_test_config();
        config.include = vec![
            std::path::PathBuf::from("proto"),
            std::path::PathBuf::from("common"),
        ];

        let runner = ProtocRunner::new(&config);
        let (cmd, _temp) = runner.build_command().unwrap();

        let cmd_str = format!("{:?}", cmd);
        assert!(cmd_str.contains("--proto_path=proto"));
        assert!(cmd_str.contains("--proto_path=common"));
    }

    #[test]
    fn build_command_custom_python_exe() {
        let mut config = create_test_config();
        config.python_exe = "uv".to_string();

        let runner = ProtocRunner::new(&config);
        let (cmd, _temp) = runner.build_command().unwrap();

        let cmd_str = format!("{:?}", cmd);
        assert!(cmd_str.contains("uv"));
    }

    #[test]
    fn include_path_filtering() {
        let dir = tempdir().unwrap();
        let proto_dir = dir.path().join("proto");
        let other_dir = dir.path().join("other");
        fs::create_dir_all(&proto_dir).unwrap();
        fs::create_dir_all(&other_dir).unwrap();

        // Create test files
        fs::write(proto_dir.join("service.proto"), "syntax = \"proto3\";").unwrap();
        fs::write(other_dir.join("external.proto"), "syntax = \"proto3\";").unwrap();

        let mut config = create_test_config();
        config.include = vec![proto_dir.clone()];
        config.inputs = vec![format!("{}/**/*.proto", dir.path().display())];

        let runner = ProtocRunner::new(&config);
        let (cmd, _temp) = runner.build_command().unwrap();

        let cmd_str = format!("{:?}", cmd);
        // Should include service.proto but not external.proto
        assert!(cmd_str.contains("service.proto"));
        assert!(!cmd_str.contains("external.proto"));
    }

    #[test]
    fn relative_path_normalization() {
        let dir = tempdir().unwrap();
        let proto_dir = dir.path().join("proto");
        fs::create_dir_all(&proto_dir).unwrap();
        fs::write(proto_dir.join("service.proto"), "syntax = \"proto3\";").unwrap();

        let mut config = create_test_config();
        config.include = vec![std::path::PathBuf::from("./proto")];
        config.inputs = vec!["proto/**/*.proto".to_string()];

        // Change to test directory
        let original_dir = std::env::current_dir().unwrap();
        std::env::set_current_dir(&dir).unwrap();

        let runner = ProtocRunner::new(&config);
        let (cmd, _temp) = runner.build_command().unwrap();

        let cmd_str = format!("{:?}", cmd);
        assert!(cmd_str.contains("--proto_path=./proto"));

        std::env::set_current_dir(&original_dir).unwrap();
    }

    #[test]
    fn empty_glob_pattern() {
        let mut config = create_test_config();
        config.inputs = vec!["nonexistent/**/*.proto".to_string()];

        let runner = ProtocRunner::new(&config);
        let (cmd, _temp) = runner.build_command().unwrap();

        // Check command arguments - should not contain paths ending with .proto
        // except for the descriptor_set_out parameter
        let args: Vec<&std::ffi::OsStr> = cmd.get_args().collect();
        let proto_file_args = args.iter().filter(|arg| {
            if let Some(s) = arg.to_str() {
                s.ends_with(".proto") && !s.contains("descriptor_set_out")
            } else {
                false
            }
        });
        assert_eq!(proto_file_args.count(), 0);
    }

    #[test]
    fn invalid_python_path_handling() {
        let mut config = create_test_config();
        config.python_exe = "/nonexistent/python".to_string();

        let runner = ProtocRunner::new(&config);
        // Should not panic, should handle gracefully
        let result = runner.build_command();
        assert!(result.is_ok());

        let (cmd, _temp) = result.unwrap();
        let cmd_str = format!("{:?}", cmd);
        assert!(cmd_str.contains("/nonexistent/python"));
    }
}