rsconstruct 0.9.183

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
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
#![allow(dead_code)]

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

/// A directory that holds no user config, so tests see built-in defaults.
fn no_user_config_dir() -> std::path::PathBuf {
    std::env::temp_dir().join("rsconstruct-tests-no-user-config")
}

/// Set to run the whole suite with `execution_model = "native"`: every
/// test's rsconstruct then reads a user config that turns the sandbox off,
/// instead of none (the default, `sandbox`). A fixture's own
/// `execution_model` still wins. See docs/src/internal/sandbox.md,
/// "Running the tests natively".
const NATIVE_SUITE_ENV: &str = "RSCONSTRUCT_TEST_NATIVE";

/// The user config directory every test's rsconstruct reads: none, or with
/// [`NATIVE_SUITE_ENV`] set, one whose config turns the sandbox off.
fn test_user_config_dir() -> std::path::PathBuf {
    if std::env::var_os(NATIVE_SUITE_ENV).is_none() {
        return no_user_config_dir();
    }
    let dir = std::env::temp_dir().join("rsconstruct-tests-native-user-config");
    let config = dir.join("rsconstruct/config.toml");
    fs::create_dir_all(config.parent().unwrap()).expect("Failed to create native user config dir");
    // Tests run in parallel: write a private file and rename it into place,
    // so a reader never sees a half-written config.
    let tmp = config.with_extension(format!(
        "{}-{:?}.tmp",
        std::process::id(),
        std::thread::current().id()
    ));
    fs::write(&tmp, "[build]\nexecution_model = \"native\"\n")
        .expect("Failed to write native user config");
    fs::rename(&tmp, &config).expect("Failed to move native user config into place");
    dir
}

/// The tool store tests install into, never the developer's own.
fn test_tool_store() -> std::path::PathBuf {
    std::env::temp_dir().join("rsconstruct-tests-tool-store")
}

/// 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.generator.tera] matches no files at all.
    fs::write(
        temp_dir.path().join("rsconstruct.toml"),
        "[processor.generator.tera]\nsrc_dirs = [\"tera.templates\"]\n",
    )
    .expect("Failed to write rsconstruct.toml");

    temp_dir
}

/// The one place a test builds a command for the rsconstruct binary. Every
/// spawn goes through here so every test is hermetic: it never reads the
/// developer's ~/.config/rsconstruct/config.toml, whose `[build]` keys
/// (`reject_dot_src_dirs = true`, say) would otherwise change what the
/// binary under test accepts. A test that wants a user config sets
/// XDG_CONFIG_HOME itself, which overrides this because later env() calls win.
///
/// `CI` is removed for the same reason: in CI the binary enforces
/// rsconstruct.lock, which no fixture project carries, so a suite running on
/// a runner would otherwise test different behavior than the same suite run
/// locally. A test about CI behavior sets `CI` itself.
///
/// The tool store is redirected too, so no test installs into (or links
/// from) the developer's own; a test that needs a store sets its own.
pub fn rsconstruct_command(dir: &Path) -> Command {
    let rsconstruct_path = env!("CARGO_BIN_EXE_rsconstruct");
    let mut cmd = Command::new(rsconstruct_path);
    cmd.env("XDG_CONFIG_HOME", test_user_config_dir());
    cmd.env("RSCONSTRUCT_TOOL_STORE", test_tool_store());
    cmd.env_remove("CI");
    cmd.current_dir(dir);
    cmd
}

/// Helper to run rsconstruct command in a directory
pub fn run_rsconstruct(dir: &Path, args: &[&str]) -> std::process::Output {
    run_rsconstruct_with_env(dir, args, &[])
}

/// 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 mut cmd = rsconstruct_command(dir);
    cmd.args(args);
    for (key, val) in env_vars {
        cmd.env(key, val);
    }
    cmd.output().expect("Failed to execute rsconstruct")
}

/// `rsconstruct --json processor defconfig <pname>`: the processor's default
/// configuration as JSON. Asserts a plugin's defaults (`dep_auto`,
/// `output_depends_on_input_name`, ...) without the tool installed and
/// without a project.
pub fn processor_defconfig(pname: &str) -> serde_json::Value {
    processor_json(&["--json", "processor", "defconfig", pname])
}

/// `rsconstruct --json processor info <pname>`: the plugin's capabilities
/// (`supports_batch`, ...) — the single entry of the list it prints.
pub fn processor_info(pname: &str) -> serde_json::Value {
    let mut entries = processor_json(&["--json", "processor", "info", pname]);
    let entries = entries
        .as_array_mut()
        .expect("processor info prints a list of entries");
    assert_eq!(entries.len(), 1, "one info entry for {pname}");
    entries.remove(0)
}

fn processor_json(args: &[&str]) -> serde_json::Value {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let output = run_rsconstruct_with_env(temp_dir.path(), args, &[("NO_COLOR", "1")]);
    assert!(
        output.status.success(),
        "rsconstruct {} failed: {}",
        args.join(" "),
        String::from_utf8_lossy(&output.stderr)
    );
    serde_json::from_slice(&output.stdout).unwrap_or_else(|e| {
        panic!(
            "rsconstruct {} printed invalid JSON: {e}\n{}",
            args.join(" "),
            String::from_utf8_lossy(&output.stdout)
        )
    })
}

/// 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();
}

/// Write the Cargo.lock for the crate at `crate_dir` with `cargo
/// generate-lockfile`, the way a committed lockfile exists in a real
/// project. The cargo and clippy processors track Cargo.lock as an input,
/// so a fixture without one sees cargo create it on the first build and
/// legitimately rebuilds on the second; tests that assert a skip need the
/// lockfile in place before the first build.
pub fn generate_lockfile(crate_dir: &Path) {
    let status = Command::new("cargo")
        .arg("generate-lockfile")
        .arg("--offline")
        .current_dir(crate_dir)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::inherit())
        .status()
        .unwrap_or_else(|e| {
            panic!(
                "running cargo generate-lockfile in {}: {e}",
                crate_dir.display()
            )
        });
    assert!(
        status.success(),
        "cargo generate-lockfile failed in {}",
        crate_dir.display()
    );
}

/// 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.generator.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) ),+ $(,)? ]) => {
        pastey::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!("[{}]\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!("[{}]\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) => {
        pastey::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!("[{}]\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) ),+ $(,)? ]) => {
        pastey::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
                );
            }
        }
    };
}