rsconstruct 0.9.133

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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
use crate::common::{
    run_rsconstruct_json_with_env, run_rsconstruct_with_env, setup_project_with_config,
    setup_test_project,
};
use std::fs;
use tempfile::TempDir;

#[test]
fn processors_list_shows_declared() {
    let temp_dir = setup_test_project();
    let project_path = temp_dir.path();

    let output =
        run_rsconstruct_with_env(project_path, &["processor", "list"], &[("NO_COLOR", "1")]);
    assert!(
        output.status.success(),
        "processor list failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("tera"), "Expected tera processor in list");
}

#[test]
fn processors_files_shows_products() {
    let temp_dir = setup_test_project();
    let project_path = temp_dir.path();

    // Write a template so there's at least one product
    fs::write(project_path.join("config/test.py"), "value = 42").expect("Failed to write config");
    fs::write(
        project_path.join("tera.templates/output.txt.tera"),
        "{% set c = load_python(path='config/test.py') %}{{ c.value }}",
    )
    .expect("Failed to write template");

    let output = run_rsconstruct_with_env(
        project_path,
        &["processor", "files", "--headers"],
        &[("NO_COLOR", "1")],
    );
    assert!(
        output.status.success(),
        "processor files failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("[processor.generator.tera]"),
        "Expected [tera] header in output"
    );
    assert!(
        stdout.contains("output.txt"),
        "Expected output file in listing"
    );
}

#[test]
fn processors_files_no_files_message() {
    let temp_dir = setup_test_project();
    let project_path = temp_dir.path();

    // No template files written, so no products
    let output =
        run_rsconstruct_with_env(project_path, &["processor", "files"], &[("NO_COLOR", "1")]);
    assert!(output.status.success());

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("No files discovered") || stdout.contains("(no files)"),
        "Expected empty message, got: {}",
        stdout
    );
}

#[test]
fn processors_files_unknown_processor_fails() {
    let temp_dir = setup_test_project();
    let project_path = temp_dir.path();

    let output = run_rsconstruct_with_env(
        project_path,
        &["processor", "files", "nonexistent"],
        &[("NO_COLOR", "1")],
    );
    assert!(
        !output.status.success(),
        "Expected failure for unknown processor"
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("Unknown processor"),
        "Expected 'Unknown processor' error, got: {}",
        stderr
    );
}

#[test]
fn processors_list_shows_descriptions() {
    let temp_dir = setup_test_project();
    let project_path = temp_dir.path();

    let output =
        run_rsconstruct_with_env(project_path, &["processor", "list"], &[("NO_COLOR", "1")]);
    assert!(
        output.status.success(),
        "processor list failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    // processor list shows processors in a table
    assert!(stdout.contains("tera"), "Expected tera processor");
}

/// `processor config` of an instance ends with the processor's own field
/// table. It used to split the name by hand and look up a processor called
/// "processor", which printed only the shared fields with type `?`.
#[test]
fn processor_config_of_an_instance_lists_its_own_fields() {
    let temp_dir =
        setup_project_with_config("[processor.generator.marp.slides]\nsrc_dirs = [\"slides\"]\n");
    let output = run_rsconstruct_with_env(
        temp_dir.path(),
        &["processor", "config", "processor.generator.marp.slides"],
        &[("NO_COLOR", "1")],
    );
    assert!(
        output.status.success(),
        "processor config failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    let parameters = stdout
        .split_once("Parameters:")
        .map(|(_, rest)| rest)
        .expect("a Parameters table follows the config");
    assert!(
        parameters.contains("timeout_secs"),
        "marp's own field must be in the Parameters table:\n{stdout}"
    );
    assert!(
        !parameters.contains("| ?"),
        "every field must show its type, not `?`:\n{stdout}"
    );
}

#[test]
fn processors_files_json_output() {
    let temp_dir = setup_test_project();
    let project_path = temp_dir.path();

    // Write a template so there's at least one product
    fs::write(project_path.join("config/test.py"), "value = 42").expect("Failed to write config");
    fs::write(
        project_path.join("tera.templates/output.txt.tera"),
        "{% set c = load_python(path='config/test.py') %}{{ c.value }}",
    )
    .expect("Failed to write template");

    let output = run_rsconstruct_with_env(
        project_path,
        &["--json", "processor", "files"],
        &[("NO_COLOR", "1")],
    );
    assert!(
        output.status.success(),
        "processor files --json failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    let entries: Vec<serde_json::Value> =
        serde_json::from_str(&stdout).expect("Expected valid JSON array");
    assert!(!entries.is_empty(), "Expected at least one entry");

    let entry = &entries[0];
    assert!(
        entry.get("processor").is_some(),
        "Entry should have 'processor' field"
    );
    assert!(
        entry.get("processor_type").is_some(),
        "Entry should have 'processor_type' field"
    );
    assert!(
        entry.get("inputs").is_some(),
        "Entry should have 'inputs' field"
    );
    assert!(
        entry.get("outputs").is_some(),
        "Entry should have 'outputs' field"
    );
    assert_eq!(entry["processor"], "processor.generator.tera");
    assert_eq!(entry["processor_type"], "generator");
}

/// `processor files <name>` lists the products the build would run for that
/// processor, including those whose inputs another processor generates.
#[test]
fn processors_files_named_includes_generated_inputs() {
    let temp_dir = TempDir::new().unwrap();
    let project = temp_dir.path();
    fs::write(
        project.join("rsconstruct.toml"),
        r#"[build]
hash_tool_versions = false

[processor.generator.generic.make]
command = "cp"
output_dir = "gen"
output_extension = "mid"
batch = false
src_extensions = [".raw"]
src_dirs = ["raw"]

[processor.generator.generic.use]
command = "cp"
output_dir = "out/use"
output_extension = "txt"
batch = false
src_extensions = [".mid"]
src_dirs = ["gen"]
"#,
    )
    .unwrap();
    fs::create_dir_all(project.join("raw")).unwrap();
    fs::write(project.join("raw/a.raw"), "a\n").unwrap();

    let output = run_rsconstruct_with_env(
        project,
        &[
            "--json",
            "processor",
            "files",
            "processor.generator.generic.use",
        ],
        &[("NO_COLOR", "1")],
    );
    assert!(
        output.status.success(),
        "processor files failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let entries: Vec<serde_json::Value> =
        serde_json::from_slice(&output.stdout).expect("Expected valid JSON array");
    assert_eq!(entries.len(), 1, "only the named processor: {entries:?}");
    assert_eq!(entries[0]["processor"], "processor.generator.generic.use");
    assert_eq!(entries[0]["inputs"][0], "gen/a.mid");
}

/// `processor info <pname>` shows the processor's description and its
/// fields, with each field's description; no config is needed.
#[test]
fn processor_info_shows_description_and_fields() {
    let temp_dir = TempDir::new().unwrap();
    let output = run_rsconstruct_with_env(
        temp_dir.path(),
        &["processor", "info", "processor.checker.ruff"],
        &[("NO_COLOR", "1")],
    );
    assert!(
        output.status.success(),
        "processor info failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("processor.checker.ruff (checker)"),
        "{stdout}"
    );
    assert!(stdout.contains("Lint and format Python files"), "{stdout}");
    assert!(stdout.contains("src_extensions"), "{stdout}");
    assert!(
        stdout.contains("File extensions to match during scanning"),
        "field descriptions are shown: {stdout}"
    );
}

/// Without a name, `processor info` covers every processor, each with a
/// description and its fields.
#[test]
fn processor_info_without_name_covers_every_processor() {
    let temp_dir = TempDir::new().unwrap();
    let listed = run_rsconstruct_with_env(
        temp_dir.path(),
        &["--json", "processor", "list"],
        &[("NO_COLOR", "1")],
    );
    assert!(listed.status.success());
    let listed: Vec<serde_json::Value> = serde_json::from_slice(&listed.stdout).unwrap();

    let output = run_rsconstruct_with_env(
        temp_dir.path(),
        &["--json", "processor", "info"],
        &[("NO_COLOR", "1")],
    );
    assert!(
        output.status.success(),
        "processor info failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let entries: Vec<serde_json::Value> =
        serde_json::from_slice(&output.stdout).expect("Expected valid JSON array");
    assert_eq!(entries.len(), listed.len(), "one entry per processor");
    for entry in &entries {
        assert_ne!(entry["description"], "", "{entry}");
        let fields = entry["fields"].as_array().expect("fields array");
        assert!(
            fields.iter().any(|f| f["name"] == "enabled"),
            "every processor has the standard fields: {entry}"
        );
    }
}

#[test]
fn processors_files_json_empty() {
    let temp_dir = setup_test_project();
    let project_path = temp_dir.path();

    // No template files written, so no products
    let output = run_rsconstruct_with_env(
        project_path,
        &["--json", "processor", "files"],
        &[("NO_COLOR", "1")],
    );
    assert!(output.status.success());

    let stdout = String::from_utf8_lossy(&output.stdout);
    let entries: Vec<serde_json::Value> =
        serde_json::from_str(&stdout).expect("Expected valid JSON array");
    assert!(
        entries.is_empty(),
        "Expected empty JSON array, got: {}",
        stdout
    );
}

#[test]
fn processors_list_works_without_config() {
    // Run from a temp dir with no rsconstruct.toml
    let temp_dir = TempDir::new().expect("Failed to create temp dir");

    let output = run_rsconstruct_with_env(
        temp_dir.path(),
        &["processor", "list"],
        &[("NO_COLOR", "1")],
    );
    assert!(
        output.status.success(),
        "processor list should work without rsconstruct.toml: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("tera"), "Expected tera processor in output");
    assert!(stdout.contains("ruff"), "Expected ruff processor in output");
    assert!(
        stdout.contains("shellcheck"),
        "Expected shellcheck processor in output"
    );
}

/// `processor list` reports whether each processor can take several input
/// files in one tool invocation: the plugin's `supports_batch` flag, the
/// same value `processor info` prints. A linter that accepts a file list
/// (ruff) can; a converter that writes one output per input (pandoc, marp)
/// cannot. Checked through the JSON form, which is what scripts read, and
/// the table header, which is what people read.
#[test]
fn processors_list_reports_batch() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");

    let output = run_rsconstruct_with_env(
        temp_dir.path(),
        &["--json", "processor", "list"],
        &[("NO_COLOR", "1")],
    );
    assert!(
        output.status.success(),
        "processor list --json failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    let entries: Vec<serde_json::Value> =
        serde_json::from_str(&stdout).expect("Expected valid JSON array");

    let by_name = |name: &str| -> &serde_json::Value {
        entries
            .iter()
            .find(|e| e["name"] == name)
            .unwrap_or_else(|| panic!("no '{name}' entry in processor list --json"))
    };
    assert_eq!(by_name("processor.checker.ruff")["supports_batch"], true);
    assert_eq!(
        by_name("processor.checker.shellcheck")["supports_batch"],
        true
    );
    assert_eq!(
        by_name("processor.generator.pandoc")["supports_batch"],
        false
    );
    assert_eq!(by_name("processor.generator.marp")["supports_batch"], false);

    for entry in &entries {
        assert!(
            entry["supports_batch"].is_boolean(),
            "'supports_batch' must be a boolean on every entry, got {entry}"
        );
    }

    let table = run_rsconstruct_with_env(
        temp_dir.path(),
        &["processor", "list"],
        &[("NO_COLOR", "1")],
    );
    assert!(table.status.success());
    let table_out = String::from_utf8_lossy(&table.stdout);
    assert!(
        table_out.contains("Batch"),
        "processor list table should have a Batch column:\n{table_out}"
    );
}

/// `processor list` reports whether each processor's implementation is
/// written in Rust: every native one is, and an external one is only when
/// its tool is (ruff yes, pylint no). Checked through the JSON form, which
/// is what scripts read, and the table header, which is what people read.
#[test]
fn processors_list_reports_rust() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");

    let output = run_rsconstruct_with_env(
        temp_dir.path(),
        &["--json", "processor", "list"],
        &[("NO_COLOR", "1")],
    );
    assert!(
        output.status.success(),
        "processor list --json failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    let entries: Vec<serde_json::Value> =
        serde_json::from_str(&stdout).expect("Expected valid JSON array");

    let by_name = |name: &str| -> &serde_json::Value {
        entries
            .iter()
            .find(|e| e["name"] == name)
            .unwrap_or_else(|| panic!("no '{name}' entry in processor list --json"))
    };
    assert_eq!(by_name("processor.generator.tera")["native"], true);
    assert_eq!(by_name("processor.generator.tera")["rust"], true);
    assert_eq!(by_name("processor.checker.ruff")["native"], false);
    assert_eq!(by_name("processor.checker.ruff")["rust"], true);
    assert_eq!(by_name("processor.checker.pylint")["native"], false);
    assert_eq!(by_name("processor.checker.pylint")["rust"], false);

    for entry in &entries {
        assert!(
            entry["rust"].is_boolean(),
            "'rust' must be a boolean on every entry, got {entry}"
        );
        if entry["native"] == true {
            assert_eq!(
                entry["rust"], true,
                "native processor '{}' must report rust: true",
                entry["name"]
            );
        }
    }

    let table = run_rsconstruct_with_env(
        temp_dir.path(),
        &["processor", "list"],
        &[("NO_COLOR", "1")],
    );
    let table_out = String::from_utf8_lossy(&table.stdout);
    assert!(
        table_out.contains("Rust"),
        "processor list table should have a Rust column: {table_out}"
    );
}

#[test]
fn no_processor_section_means_no_products() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let project_path = temp_dir.path();

    // Create tera template directory and file
    fs::create_dir_all(project_path.join("tera.templates")).unwrap();
    fs::write(project_path.join("tera.templates/quick.txt.tera"), "hello").unwrap();

    // No processor sections declared
    fs::write(project_path.join("rsconstruct.toml"), "\n").unwrap();

    // Build should produce zero products (no processors declared)
    let result = run_rsconstruct_json_with_env(project_path, &["build"], &[("NO_COLOR", "1")]);
    assert!(result.exit_success, "Build should succeed");
    assert_eq!(
        result.total_products, 0,
        "Expected 0 products when no processor is declared"
    );
}

#[test]
fn per_processor_enabled_true_is_default() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let project_path = temp_dir.path();

    // Create tera template directory and file
    fs::create_dir_all(project_path.join("tera.templates")).unwrap();
    fs::write(project_path.join("tera.templates/quick.txt.tera"), "hello").unwrap();

    // Enable tera in the enabled list without setting per-processor enabled
    fs::write(
        project_path.join("rsconstruct.toml"),
        "[processor.generator.tera]\nsrc_dirs = [\"tera.templates\"]\n",
    )
    .unwrap();

    // Build should produce one product (tera defaults to enabled = true)
    let result = run_rsconstruct_json_with_env(project_path, &["build"], &[("NO_COLOR", "1")]);
    assert!(result.exit_success, "Build should succeed");
    assert_eq!(
        result.total_products, 1,
        "Expected 1 product when processor defaults to enabled"
    );
}

/// `enabled = false` exists to keep a stanza while its tool is not installed:
/// the tool pre-flight must not fail the build for disabled instances.
#[test]
fn disabled_processor_skips_tool_preflight() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let project_path = temp_dir.path();
    fs::create_dir_all(project_path.join("src")).unwrap();
    fs::write(project_path.join("src/a.txt"), "hello\n").unwrap();

    // src_extensions must match src/a.txt: the tool check runs against
    // processors that actually produced products, so a processor matching
    // nothing would never reach it.
    let config = |enabled: &str| {
        format!(
            "[processor.checker.script]\ncommand = \"definitely-not-a-real-tool-xyz\"\nsrc_dirs = [\"src\"]\nsrc_extensions = [\".txt\"]\nenabled = {enabled}\n"
        )
    };

    // Control: enabled instance with a missing tool must fail pre-flight
    fs::write(project_path.join("rsconstruct.toml"), config("true")).unwrap();
    let result = run_rsconstruct_json_with_env(project_path, &["build"], &[("NO_COLOR", "1")]);
    assert!(
        !result.exit_success,
        "enabled instance with missing tool must fail"
    );

    // Disabled instance must not trip the pre-flight
    fs::write(project_path.join("rsconstruct.toml"), config("false")).unwrap();
    let result = run_rsconstruct_json_with_env(project_path, &["build"], &[("NO_COLOR", "1")]);
    assert!(
        result.exit_success,
        "disabled instance must not fail the tool pre-flight"
    );
    assert_eq!(
        result.total_products, 0,
        "disabled instance must produce no products"
    );
}

#[test]
fn processors_list_json() {
    let temp_dir = setup_test_project();
    let project_path = temp_dir.path();

    let output = run_rsconstruct_with_env(
        project_path,
        &["--json", "processor", "list"],
        &[("NO_COLOR", "1")],
    );
    assert!(
        output.status.success(),
        "processor list --json failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    let entries: Vec<serde_json::Value> =
        serde_json::from_str(&stdout).expect("Expected valid JSON array");
    assert!(!entries.is_empty(), "Expected at least one entry");

    // Check that every entry has the expected fields
    for entry in &entries {
        assert!(
            entry.get("name").is_some(),
            "Entry should have 'name' field"
        );
        assert!(
            entry.get("processor_type").is_some(),
            "Entry should have 'processor_type' field"
        );
        assert!(
            entry.get("enabled").is_some(),
            "Entry should have 'enabled' field"
        );
        assert!(
            entry.get("detected").is_some(),
            "Entry should have 'detected' field"
        );
        assert!(
            entry.get("supports_batch").is_some(),
            "Entry should have 'supports_batch' field"
        );
        assert!(
            entry.get("description").is_some(),
            "Entry should have 'description' field"
        );
    }

    // list always shows all processors regardless of config
    let tera = entries
        .iter()
        .find(|e| e["name"] == "processor.generator.tera")
        .expect("Expected tera in list");
    assert!(tera.get("name").is_some());
}

#[test]
fn processors_list_all_json_without_config() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");

    let output = run_rsconstruct_with_env(
        temp_dir.path(),
        &["--json", "processor", "list"],
        &[("NO_COLOR", "1")],
    );
    assert!(
        output.status.success(),
        "processor list --json failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    let entries: Vec<serde_json::Value> =
        serde_json::from_str(&stdout).expect("Expected valid JSON array");
    assert!(!entries.is_empty(), "Expected at least one entry");

    // Check that every entry has the expected fields
    for entry in &entries {
        assert!(
            entry.get("name").is_some(),
            "Entry should have 'name' field"
        );
        assert!(
            entry.get("processor_type").is_some(),
            "Entry should have 'processor_type' field"
        );
        assert!(
            entry.get("supports_batch").is_some(),
            "Entry should have 'supports_batch' field"
        );
        assert!(
            entry.get("description").is_some(),
            "Entry should have 'description' field"
        );
    }

    let tera = entries
        .iter()
        .find(|e| e["name"] == "processor.generator.tera")
        .expect("Expected tera in list");
    assert!(tera.get("name").is_some());
}

#[test]
fn removing_processor_section_disables_it() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let project_path = temp_dir.path();

    // Create tera template directory and file
    fs::create_dir_all(project_path.join("tera.templates")).unwrap();
    fs::write(project_path.join("tera.templates/output.txt.tera"), "hello").unwrap();

    // First build with tera declared — should produce 1 product
    fs::write(
        project_path.join("rsconstruct.toml"),
        "[processor.generator.tera]\nsrc_dirs = [\"tera.templates\"]\n",
    )
    .unwrap();

    let result = run_rsconstruct_json_with_env(project_path, &["build"], &[("NO_COLOR", "1")]);
    assert!(result.exit_success, "Build should succeed");
    assert_eq!(
        result.total_products, 1,
        "Expected 1 product with tera declared"
    );

    // Remove tera section — should produce 0 products
    fs::write(project_path.join("rsconstruct.toml"), "\n").unwrap();

    let result = run_rsconstruct_json_with_env(project_path, &["build"], &[("NO_COLOR", "1")]);
    assert!(result.exit_success, "Build should succeed");
    assert_eq!(
        result.total_products, 0,
        "Expected 0 products with no processor declared"
    );
}

#[test]
fn remove_no_file_processors_keeps_disabled_stanza() {
    // A processor with `enabled = false` produces 0 products because discovery
    // skips it — that is the documented purpose of the flag, not dead config.
    // It must survive `smart remove-no-file-processors`.
    let temp_dir = setup_project_with_config(
        "[processor.generator.tera]\nsrc_dirs = [\"tera.templates\"]\n\n[processor.checker.shellcheck]\nsrc_dirs = [\"src\"]\nenabled = false\n",
    );
    let project_path = temp_dir.path();
    fs::create_dir_all(project_path.join("tera.templates")).unwrap();
    fs::write(project_path.join("tera.templates/output.txt.tera"), "hello").unwrap();

    let output = run_rsconstruct_with_env(
        project_path,
        &["smart", "remove-no-file-processors"],
        &[("NO_COLOR", "1")],
    );
    assert!(
        output.status.success(),
        "command failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        !stdout.contains("shellcheck"),
        "Disabled processor must not be reported as having no files, got: {stdout}"
    );

    let toml = fs::read_to_string(project_path.join("rsconstruct.toml")).unwrap();
    assert!(
        toml.contains("[processor.checker.shellcheck]"),
        "Disabled stanza must be preserved, got: {toml}"
    );
    assert!(
        toml.contains("enabled = false"),
        "enabled = false must be preserved, got: {toml}"
    );
}

#[test]
fn remove_no_file_processors_removes_enabled_stanza_with_no_files() {
    // An *enabled* processor matching nothing is still dead config and must go.
    let temp_dir = setup_project_with_config(
        "[processor.generator.tera]\nsrc_dirs = [\"tera.templates\"]\n\n[processor.checker.shellcheck]\nsrc_dirs = [\"src\"]\n",
    );
    let project_path = temp_dir.path();
    fs::create_dir_all(project_path.join("tera.templates")).unwrap();
    fs::write(project_path.join("tera.templates/output.txt.tera"), "hello").unwrap();

    let output = run_rsconstruct_with_env(
        project_path,
        &["smart", "remove-no-file-processors"],
        &[("NO_COLOR", "1")],
    );
    assert!(
        output.status.success(),
        "command failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let toml = fs::read_to_string(project_path.join("rsconstruct.toml")).unwrap();
    assert!(
        !toml.contains("[processor.checker.shellcheck]"),
        "Enabled stanza with no files must be removed, got: {toml}"
    );
    assert!(
        toml.contains("[processor.generator.tera]"),
        "Processor with files must be kept, got: {toml}"
    );
}

#[test]
fn processor_types_shows_descriptions() {
    let temp_dir = TempDir::new().unwrap();
    let output = run_rsconstruct_with_env(
        temp_dir.path(),
        &["processor", "types"],
        &[("NO_COLOR", "1")],
    );
    assert!(
        output.status.success(),
        "processor types failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("Type"), "Expected Type header:\n{stdout}");
    assert!(
        stdout.contains("Description"),
        "Expected Description header:\n{stdout}"
    );
    for (name, desc_snippet) in [
        ("generator", "Generates output files from input files"),
        ("checker", "Validates input files without producing outputs"),
        ("explicit", "Many inputs aggregated into"),
        ("mass_generator", "Runs a tool that enumerates its outputs"),
    ] {
        assert!(
            stdout.contains(name) && stdout.contains(desc_snippet),
            "Expected type '{name}' and description '{desc_snippet}' in:\n{stdout}"
        );
    }
}

/// `processor types` states each type's batching contract: whether one tool
/// invocation may take more than one input. Checkers and generators leave
/// it to the processor (`optional`); explicit processors and mass
/// generators take every input in one invocation by construction
/// (`always`). The JSON carries the same as `batch`, with the one-line
/// contract as `batching`.
#[test]
fn processor_types_shows_batching_contract() {
    let temp_dir = TempDir::new().unwrap();
    let output = run_rsconstruct_with_env(
        temp_dir.path(),
        &["--json", "processor", "types"],
        &[("NO_COLOR", "1")],
    );
    assert!(output.status.success());
    let entries: Vec<serde_json::Value> =
        serde_json::from_str(&String::from_utf8_lossy(&output.stdout)).unwrap();
    let batch_of = |name: &str| -> String {
        entries
            .iter()
            .find(|e| e["name"] == name)
            .unwrap_or_else(|| panic!("no type {name}"))["batch"]
            .as_str()
            .unwrap()
            .to_string()
    };
    assert_eq!(batch_of("checker"), "optional");
    assert_eq!(batch_of("generator"), "optional");
    assert_eq!(batch_of("explicit"), "always");
    assert_eq!(batch_of("mass_generator"), "always");
    for entry in &entries {
        assert!(
            entry["batching"].as_str().is_some_and(|s| !s.is_empty()),
            "every type explains its contract: {entry}"
        );
    }

    let table = run_rsconstruct_with_env(
        temp_dir.path(),
        &["processor", "types"],
        &[("NO_COLOR", "1")],
    );
    let stdout = String::from_utf8_lossy(&table.stdout);
    assert!(stdout.contains("Batch"), "Batch column:\n{stdout}");
    let explicit_row = stdout
        .lines()
        .find(|l| l.contains("explicit"))
        .unwrap_or_else(|| panic!("no explicit row:\n{stdout}"));
    assert!(explicit_row.contains("always"), "{explicit_row}");
    let checker_row = stdout.lines().find(|l| l.contains("checker")).unwrap();
    assert!(checker_row.contains("optional"), "{checker_row}");
    assert!(
        !stdout.contains("Batching"),
        "the contract text needs --verbose:\n{stdout}"
    );
    let verbose = run_rsconstruct_with_env(
        temp_dir.path(),
        &["--verbose", "processor", "types"],
        &[("NO_COLOR", "1")],
    );
    let stdout = String::from_utf8_lossy(&verbose.stdout);
    assert!(
        stdout.contains("Batching") && stdout.contains("runs once per manifest"),
        "{stdout}"
    );
}