rsconstruct 0.9.79

Rust based fast build system
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
#![allow(dead_code)]

use serde::Deserialize;
use std::fs;
use std::path::Path;
use std::process::Command;
use tempfile::TempDir;

/// Assert that an external tool is available on PATH.
/// Panics if the tool is missing — a missing tool must fail the test,
/// never silently skip it. Only presence is checked (some tools, like
/// pdfunite, have no --version flag); whether the tool actually works
/// is the test body's job.
pub fn require_tool(name: &str) {
    let available = Command::new(name)
        .arg("--version")
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .is_ok();
    assert!(
        available,
        "required tool '{name}' is not installed — install it; missing tools fail tests, they never skip"
    );
}

/// Helper to create a test project structure (tera processor only)
pub fn setup_test_project() -> TempDir {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");

    // Create directories
    fs::create_dir_all(temp_dir.path().join("tera.templates"))
        .expect("Failed to create tera.templates dir");
    fs::create_dir_all(temp_dir.path().join("config")).expect("Failed to create config dir");

    // Only enable the tera processor so config/*.py files aren't picked up by linters.
    // src_dirs is explicit because no processor defaults to scanning anywhere —
    // a bare [processor.tera] matches no files at all.
    fs::write(
        temp_dir.path().join("rsconstruct.toml"),
        "[processor.tera]\nsrc_dirs = [\"tera.templates\"]\n",
    )
    .expect("Failed to write rsconstruct.toml");

    temp_dir
}

/// Helper to run rsconstruct command in a directory
pub fn run_rsconstruct(dir: &Path, args: &[&str]) -> std::process::Output {
    let rsconstruct_path = env!("CARGO_BIN_EXE_rsconstruct");
    Command::new(rsconstruct_path)
        .current_dir(dir)
        .args(args)
        .output()
        .expect("Failed to execute rsconstruct")
}

/// Helper to run rsconstruct command with extra environment variables
pub fn run_rsconstruct_with_env(
    dir: &Path,
    args: &[&str],
    env_vars: &[(&str, &str)],
) -> std::process::Output {
    let rsconstruct_path = env!("CARGO_BIN_EXE_rsconstruct");
    let mut cmd = Command::new(rsconstruct_path);
    cmd.current_dir(dir).args(args);
    for (key, val) in env_vars {
        cmd.env(key, val);
    }
    cmd.output().expect("Failed to execute rsconstruct")
}

/// Create a temp dir with a rsconstruct.toml containing the given config string.
pub fn setup_project_with_config(config: &str) -> TempDir {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    fs::write(temp_dir.path().join("rsconstruct.toml"), config).unwrap();
    temp_dir
}

/// Mark a file executable, so a test can put a script on PATH and have the
/// build actually invoke it. Unconditionally unix (the project targets
/// Linux/macOS only — `#[cfg]` forks are forbidden as untestable dead code).
pub fn make_executable(path: &Path) {
    use std::os::unix::fs::PermissionsExt;
    let mut perms = fs::metadata(path).unwrap().permissions();
    perms.set_mode(0o755);
    fs::set_permissions(path, perms).unwrap();
}

/// Create a file at the given path, creating parent directories as needed.
pub fn write_file(base: &Path, relative: &str, content: &str) {
    let path = base.join(relative);
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).unwrap();
    }
    fs::write(path, content).unwrap();
}

/// Helper to set up a C project with the cc processor enabled
pub fn setup_cc_project(project_path: &Path) {
    fs::create_dir_all(project_path.join("src")).unwrap();
    fs::write(
        project_path.join("rsconstruct.toml"),
        "[processor.cc_single_file]\nsrc_dirs = [\"src\"]\n[analyzer.icpp]\n",
    )
    .unwrap();
}

// --- JSON output parsing for tests ---

/// Run rsconstruct with --json flag and return parsed build result
pub fn run_rsconstruct_json(dir: &Path, args: &[&str]) -> BuildResult {
    let mut full_args = vec!["--json"];
    full_args.extend(args);
    let output = run_rsconstruct(dir, &full_args);
    BuildResult::parse(&output)
}

/// Run rsconstruct with --json flag and extra environment variables
pub fn run_rsconstruct_json_with_env(
    dir: &Path,
    args: &[&str],
    env_vars: &[(&str, &str)],
) -> BuildResult {
    let mut full_args = vec!["--json"];
    full_args.extend(args);
    let output = run_rsconstruct_with_env(dir, &full_args, env_vars);
    BuildResult::parse(&output)
}

/// JSON event from rsconstruct --json output
#[derive(Debug, Deserialize)]
#[serde(tag = "event", rename_all = "snake_case")]
pub enum BuildEvent {
    BuildStart {
        total_products: usize,
    },
    ProductComplete {
        product: String,
        processor: String,
        status: String,
        #[serde(default)]
        duration_ms: Option<u64>,
        #[serde(default)]
        error: Option<String>,
    },
    BuildSummary {
        total: usize,
        success: usize,
        failed: usize,
        skipped: usize,
        restored: usize,
        duration_ms: u64,
        #[serde(default)]
        errors: Vec<String>,
    },
}

/// Parsed build result from rsconstruct --json output
#[derive(Debug, Default)]
pub struct BuildResult {
    pub exit_success: bool,
    pub total_products: usize,
    pub success: usize,
    pub failed: usize,
    pub skipped: usize,
    pub restored: usize,
    pub duration_ms: u64,
    pub errors: Vec<String>,
    pub products: Vec<ProductResult>,
}

/// Individual product result
#[derive(Debug, Clone)]
pub struct ProductResult {
    pub product: String,
    pub processor: String,
    pub status: String,
    pub duration_ms: Option<u64>,
    pub error: Option<String>,
}

impl BuildResult {
    /// Parse rsconstruct --json output into structured BuildResult
    pub fn parse(output: &std::process::Output) -> Self {
        let mut result = BuildResult {
            exit_success: output.status.success(),
            ..Default::default()
        };

        let stdout = String::from_utf8_lossy(&output.stdout);
        for line in stdout.lines() {
            if line.trim().is_empty() {
                continue;
            }
            if let Ok(event) = serde_json::from_str::<BuildEvent>(line) {
                match event {
                    BuildEvent::BuildStart { total_products } => {
                        result.total_products = total_products;
                    }
                    BuildEvent::ProductComplete {
                        product,
                        processor,
                        status,
                        duration_ms,
                        error,
                    } => {
                        result.products.push(ProductResult {
                            product,
                            processor,
                            status,
                            duration_ms,
                            error,
                        });
                    }
                    BuildEvent::BuildSummary {
                        total: _,
                        success,
                        failed,
                        skipped,
                        restored,
                        duration_ms,
                        errors,
                    } => {
                        result.success = success;
                        result.failed = failed;
                        result.skipped = skipped;
                        result.restored = restored;
                        result.duration_ms = duration_ms;
                        result.errors = errors;
                    }
                }
            }
        }
        result
    }

    /// Count products with a specific status
    pub fn count_status(&self, status: &str) -> usize {
        self.products.iter().filter(|p| p.status == status).count()
    }

    /// Check if a product with given name was processed with given status
    pub fn has_product(&self, name: &str, status: &str) -> bool {
        self.products
            .iter()
            .any(|p| p.product.contains(name) && p.status == status)
    }

    /// Get all products with a specific status
    pub fn products_with_status(&self, status: &str) -> Vec<&ProductResult> {
        self.products
            .iter()
            .filter(|p| p.status == status)
            .collect()
    }
}

/// Generate standard checker processor tests: valid file + incremental skip.
///
/// Usage:
/// ```ignore
/// test_checker!(eslint, tool: "eslint", processor: "eslint",
///     files: [(".eslintrc.json", "{}\n"), ("test.js", "var x = 1;\n")]);
/// ```
///
/// For build tools that don't have simple files to test, use `no_project`:
/// ```ignore
/// test_checker!(cmake, tool: "cmake", processor: "cmake", no_project);
/// ```
macro_rules! test_checker {
    // Full test: valid file + incremental skip
    ($mod_name:ident, tool: $tool:expr, processor: $proc:expr,
     files: [ $( ($fname:expr, $content:expr) ),+ $(,)? ]) => {
        paste::paste! {
            #[test]
            fn [<$mod_name _valid>]() {
                crate::common::require_tool($tool);

                let temp_dir = tempfile::TempDir::new().expect("Failed to create temp dir");
                let project_path = temp_dir.path();

                std::fs::write(
                    project_path.join("rsconstruct.toml"),
                    format!("[processor.{}]\nsrc_dirs = [\".\"]\n", $proc),
                ).unwrap();

                $( std::fs::write(project_path.join($fname), $content).unwrap(); )+

                let output = crate::common::run_rsconstruct_with_env(
                    project_path, &["build", "-v"], &[("NO_COLOR", "1")]);
                assert!(
                    output.status.success(),
                    "Build should succeed: stdout={}, stderr={}",
                    String::from_utf8_lossy(&output.stdout),
                    String::from_utf8_lossy(&output.stderr)
                );
            }

            #[test]
            fn [<$mod_name _incremental_skip>]() {
                crate::common::require_tool($tool);

                let temp_dir = tempfile::TempDir::new().expect("Failed to create temp dir");
                let project_path = temp_dir.path();

                std::fs::write(
                    project_path.join("rsconstruct.toml"),
                    format!("[processor.{}]\nsrc_dirs = [\".\"]\n", $proc),
                ).unwrap();

                $( std::fs::write(project_path.join($fname), $content).unwrap(); )+

                let output1 = crate::common::run_rsconstruct_with_env(
                    project_path, &["build"], &[("NO_COLOR", "1")]);
                assert!(output1.status.success());

                let output2 = crate::common::run_rsconstruct_with_env(
                    project_path, &["build", "--verbose"], &[("NO_COLOR", "1")]);
                assert!(output2.status.success());
                let stdout2 = String::from_utf8_lossy(&output2.stdout);
                assert!(
                    stdout2.contains(&format!("[{}] Skipping (unchanged):", $proc)),
                    "Second build should skip: {}", stdout2
                );
            }
        }
    };

    // No-project test: just verify the processor works with no matching files
    ($mod_name:ident, tool: $tool:expr, processor: $proc:expr, no_project) => {
        paste::paste! {
            #[test]
            fn [<$mod_name _no_project_discovered>]() {
                crate::common::require_tool($tool);

                let temp_dir = tempfile::TempDir::new().expect("Failed to create temp dir");
                let project_path = temp_dir.path();

                std::fs::write(
                    project_path.join("rsconstruct.toml"),
                    format!("[processor.{}]\nsrc_dirs = [\".\"]\n", $proc),
                ).unwrap();

                let output = crate::common::run_rsconstruct_with_env(
                    project_path, &["build", "-v"], &[("NO_COLOR", "1")]);
                assert!(
                    output.status.success(),
                    "Build should succeed with no files: stdout={}, stderr={}",
                    String::from_utf8_lossy(&output.stdout),
                    String::from_utf8_lossy(&output.stderr)
                );
            }
        }
    };

    // Custom config test: with extra TOML config
    ($mod_name:ident, tool: $tool:expr, processor: $proc:expr,
     config: $config:expr,
     files: [ $( ($fname:expr, $content:expr) ),+ $(,)? ]) => {
        paste::paste! {
            #[test]
            fn [<$mod_name _valid>]() {
                crate::common::require_tool($tool);

                let temp_dir = tempfile::TempDir::new().expect("Failed to create temp dir");
                let project_path = temp_dir.path();

                std::fs::write(project_path.join("rsconstruct.toml"), $config).unwrap();

                $( std::fs::write(project_path.join($fname), $content).unwrap(); )+

                let output = crate::common::run_rsconstruct_with_env(
                    project_path, &["build", "-v"], &[("NO_COLOR", "1")]);
                assert!(
                    output.status.success(),
                    "Build should succeed: stdout={}, stderr={}",
                    String::from_utf8_lossy(&output.stdout),
                    String::from_utf8_lossy(&output.stderr)
                );
            }

            #[test]
            fn [<$mod_name _incremental_skip>]() {
                crate::common::require_tool($tool);

                let temp_dir = tempfile::TempDir::new().expect("Failed to create temp dir");
                let project_path = temp_dir.path();

                std::fs::write(project_path.join("rsconstruct.toml"), $config).unwrap();

                $( std::fs::write(project_path.join($fname), $content).unwrap(); )+

                let output1 = crate::common::run_rsconstruct_with_env(
                    project_path, &["build"], &[("NO_COLOR", "1")]);
                assert!(output1.status.success());

                let output2 = crate::common::run_rsconstruct_with_env(
                    project_path, &["build", "--verbose"], &[("NO_COLOR", "1")]);
                assert!(output2.status.success());
                let stdout2 = String::from_utf8_lossy(&output2.stdout);
                assert!(
                    stdout2.contains(&format!("[{}] Skipping (unchanged):", $proc)),
                    "Second build should skip: {}", stdout2
                );
            }
        }
    };
}