perfgate 0.17.0

Core library for perfgate performance budgets and baseline diffs
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
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
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
//! Benchmark discovery and config generation for `perfgate init`.
//!
//! Scans a repository to detect benchmark targets and generates
//! a `perfgate.toml` configuration file.

use perfgate_types::{BenchConfigFile, ConfigFile, DefaultsConfig, NoisePolicy};
use std::fmt;
use std::path::{Path, PathBuf};

// ---------------------------------------------------------------------------
// Public types
// ---------------------------------------------------------------------------

/// How a benchmark was discovered.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BenchSource {
    /// A `[[bench]]` target in `Cargo.toml`.
    CargoTarget,
    /// Detected via `criterion_group!` / `criterion_main!` macros.
    Criterion,
    /// Go `func Benchmark*` in `*_test.go`.
    GoBench,
    /// Python pytest-benchmark detected.
    PytestBenchmark,
    /// Fallback / user-supplied.
    Custom,
}

impl fmt::Display for BenchSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            BenchSource::CargoTarget => write!(f, "cargo bench target"),
            BenchSource::Criterion => write!(f, "criterion benchmark"),
            BenchSource::GoBench => write!(f, "go benchmark"),
            BenchSource::PytestBenchmark => write!(f, "pytest-benchmark"),
            BenchSource::Custom => write!(f, "custom"),
        }
    }
}

/// A benchmark discovered by scanning the repository.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiscoveredBench {
    pub name: String,
    pub command: Vec<String>,
    pub source: BenchSource,
}

/// Budget preset for config generation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Preset {
    Standard,
    Release,
    Tier1Fast,
}

impl Preset {
    pub fn defaults(self) -> DefaultsConfig {
        match self {
            Preset::Standard => DefaultsConfig {
                repeat: Some(7),
                warmup: Some(1),
                threshold: Some(0.20),
                warn_factor: Some(0.50),
                noise_threshold: Some(0.10),
                noise_policy: Some(NoisePolicy::Warn),
                out_dir: Some("artifacts/perfgate".into()),
                baseline_dir: Some("baselines".into()),
                ..DefaultsConfig::default()
            },
            Preset::Release => DefaultsConfig {
                repeat: Some(10),
                warmup: Some(2),
                threshold: Some(0.10),
                warn_factor: Some(0.50),
                noise_threshold: Some(0.08),
                noise_policy: Some(NoisePolicy::Warn),
                out_dir: Some("artifacts/perfgate".into()),
                baseline_dir: Some("baselines".into()),
                ..DefaultsConfig::default()
            },
            Preset::Tier1Fast => DefaultsConfig {
                repeat: Some(3),
                warmup: Some(1),
                threshold: Some(0.30),
                warn_factor: Some(0.50),
                noise_threshold: Some(0.15),
                noise_policy: Some(NoisePolicy::Warn),
                out_dir: Some("artifacts/perfgate".into()),
                baseline_dir: Some("baselines".into()),
                ..DefaultsConfig::default()
            },
        }
    }
}

/// CI platform for workflow scaffolding.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CiPlatform {
    GitHub,
    GitLab,
    Bitbucket,
    CircleCi,
}

// ---------------------------------------------------------------------------
// Benchmark discovery
// ---------------------------------------------------------------------------

/// Scan `root` for benchmarks.  Does not recurse into hidden or `target` dirs.
pub fn discover_benchmarks(root: &Path) -> Vec<DiscoveredBench> {
    let mut found: Vec<DiscoveredBench> = Vec::new();

    discover_rust_benches(root, &mut found);
    discover_go_benches(root, &mut found);
    discover_python_benches(root, &mut found);

    // De-duplicate by name (first wins).
    let mut seen = std::collections::HashSet::new();
    found.retain(|b| seen.insert(b.name.clone()));

    found
}

// -- Rust / Cargo ----------------------------------------------------------

fn discover_rust_benches(root: &Path, out: &mut Vec<DiscoveredBench>) {
    let cargo_toml = root.join("Cargo.toml");
    if !cargo_toml.is_file() {
        return;
    }

    let content = match std::fs::read_to_string(&cargo_toml) {
        Ok(c) => c,
        Err(_) => return,
    };

    // Parse [[bench]] targets.
    if let Ok(parsed) = content.parse::<toml::Table>()
        && let Some(toml::Value::Array(benches)) = parsed.get("bench")
    {
        for bench in benches {
            if let Some(name) = bench.get("name").and_then(|v| v.as_str()) {
                let harness = bench
                    .get("harness")
                    .and_then(|v| v.as_bool())
                    .unwrap_or(true);

                let source = if harness {
                    BenchSource::CargoTarget
                } else {
                    // harness = false usually means Criterion or custom runner
                    BenchSource::Criterion
                };

                out.push(DiscoveredBench {
                    name: name.to_string(),
                    command: vec![
                        "cargo".into(),
                        "bench".into(),
                        "--bench".into(),
                        name.to_string(),
                    ],
                    source,
                });
            }
        }
    }

    // Scan benches/ directory for criterion macros.
    let benches_dir = root.join("benches");
    if benches_dir.is_dir() {
        scan_dir_for_criterion(&benches_dir, out);
    }
}

fn scan_dir_for_criterion(dir: &Path, out: &mut Vec<DiscoveredBench>) {
    let entries = match std::fs::read_dir(dir) {
        Ok(e) => e,
        Err(_) => return,
    };

    for entry in entries.flatten() {
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("rs") {
            continue;
        }

        let content = match std::fs::read_to_string(&path) {
            Ok(c) => c,
            Err(_) => continue,
        };

        if content.contains("criterion_group!") || content.contains("criterion_main!") {
            let stem = path
                .file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or("benchmark");

            // Only add if not already discovered via [[bench]].
            if !out.iter().any(|b| b.name == stem) {
                out.push(DiscoveredBench {
                    name: stem.to_string(),
                    command: vec![
                        "cargo".into(),
                        "bench".into(),
                        "--bench".into(),
                        stem.to_string(),
                    ],
                    source: BenchSource::Criterion,
                });
            }
        }
    }
}

// -- Go --------------------------------------------------------------------

fn discover_go_benches(root: &Path, out: &mut Vec<DiscoveredBench>) {
    // Look for go.mod first.
    if !root.join("go.mod").is_file() {
        return;
    }

    walk_for_go_bench_files(root, root, out);
}

fn walk_for_go_bench_files(root: &Path, dir: &Path, out: &mut Vec<DiscoveredBench>) {
    let entries = match std::fs::read_dir(dir) {
        Ok(e) => e,
        Err(_) => return,
    };

    for entry in entries.flatten() {
        let path = entry.path();

        if path.is_dir() {
            let name = path
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or_default();
            if name.starts_with('.') || name == "vendor" || name == "node_modules" {
                continue;
            }
            walk_for_go_bench_files(root, &path, out);
            continue;
        }

        let file_name = path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or_default();
        if !file_name.ends_with("_test.go") {
            continue;
        }

        let content = match std::fs::read_to_string(&path) {
            Ok(c) => c,
            Err(_) => continue,
        };

        if content.contains("func Benchmark") {
            let pkg_dir = path.parent().unwrap_or(root);
            let rel = pkg_dir
                .strip_prefix(root)
                .unwrap_or(pkg_dir)
                .to_string_lossy()
                .replace('\\', "/");

            let pkg = if rel.is_empty() {
                ".".to_string()
            } else {
                format!("./{rel}")
            };

            let bench_name = format!("go-bench-{}", rel.replace('/', "-")).replace("..", "root");
            let bench_name = if bench_name == "go-bench-" {
                "go-bench".to_string()
            } else {
                bench_name
            };

            if !out.iter().any(|b| b.name == bench_name) {
                out.push(DiscoveredBench {
                    name: bench_name,
                    command: vec![
                        "go".into(),
                        "test".into(),
                        "-bench=.".into(),
                        "-benchmem".into(),
                        pkg,
                    ],
                    source: BenchSource::GoBench,
                });
            }
        }
    }
}

// -- Python ----------------------------------------------------------------

fn discover_python_benches(root: &Path, out: &mut Vec<DiscoveredBench>) {
    let markers = [
        "requirements.txt",
        "requirements-dev.txt",
        "requirements-test.txt",
        "setup.py",
        "setup.cfg",
        "pyproject.toml",
    ];

    let mut has_pytest_benchmark = false;
    for marker in &markers {
        let path = root.join(marker);
        if let Ok(content) = std::fs::read_to_string(&path)
            && (content.contains("pytest-benchmark") || content.contains("pytest_benchmark"))
        {
            has_pytest_benchmark = true;
            break;
        }
    }

    // Also check for conftest.py with benchmark fixture usage.
    if !has_pytest_benchmark {
        let conftest = root.join("conftest.py");
        if let Ok(content) = std::fs::read_to_string(&conftest)
            && content.contains("benchmark")
        {
            has_pytest_benchmark = true;
        }
    }

    if has_pytest_benchmark {
        out.push(DiscoveredBench {
            name: "pytest-bench".to_string(),
            command: vec![
                "pytest".into(),
                "--benchmark-only".into(),
                "--benchmark-json=benchmark.json".into(),
            ],
            source: BenchSource::PytestBenchmark,
        });
    }
}

// ---------------------------------------------------------------------------
// Config generation
// ---------------------------------------------------------------------------

/// Build a `ConfigFile` from discovered benchmarks and a preset.
pub fn generate_config(benchmarks: &[DiscoveredBench], preset: Preset) -> ConfigFile {
    let defaults = preset.defaults();

    let benches: Vec<BenchConfigFile> = benchmarks
        .iter()
        .map(|b| BenchConfigFile {
            name: b.name.clone(),
            command: b.command.clone(),
            cwd: None,
            work: None,
            timeout: None,
            repeat: None,
            warmup: None,
            metrics: None,
            budgets: None,
            scaling: None,
        })
        .collect();

    ConfigFile {
        defaults,
        benches,
        ..ConfigFile::default()
    }
}

/// Render a `ConfigFile` to a well-commented TOML string.
pub fn render_config_toml(config: &ConfigFile) -> String {
    let mut out = String::new();

    out.push_str("# perfgate.toml — generated by `perfgate init`\n");
    out.push_str("#\n");
    out.push_str("# Documentation: https://github.com/EffortlessMetrics/perfgate\n\n");

    // [defaults]
    out.push_str("# Default settings applied to all benchmarks unless overridden.\n");
    out.push_str("[defaults]\n");
    if let Some(repeat) = config.defaults.repeat {
        out.push_str(&format!(
            "# Number of measured samples per benchmark run.\n\
             repeat = {repeat}\n"
        ));
    }
    if let Some(warmup) = config.defaults.warmup {
        out.push_str(&format!(
            "# Warmup iterations excluded from statistics.\n\
             warmup = {warmup}\n"
        ));
    }
    if let Some(threshold) = config.defaults.threshold {
        out.push_str(&format!(
            "# Maximum allowed regression fraction (0.20 = 20%).\n\
             threshold = {threshold:.2}\n"
        ));
    }
    if let Some(warn_factor) = config.defaults.warn_factor {
        out.push_str(&format!(
            "# Warn when regression reaches threshold * warn_factor.\n\
             warn_factor = {warn_factor:.2}\n"
        ));
    }
    if let Some(noise_threshold) = config.defaults.noise_threshold {
        out.push_str(&format!(
            "# Coefficient of variation that marks a benchmark as noisy.\n\
             noise_threshold = {noise_threshold:.2}\n"
        ));
    }
    if let Some(noise_policy) = config.defaults.noise_policy {
        out.push_str(&format!(
            "# What to do when measured noise exceeds noise_threshold.\n\
             noise_policy = \"{}\"\n",
            noise_policy.as_str()
        ));
    }
    if let Some(ref out_dir) = config.defaults.out_dir {
        out.push_str(&format!("out_dir = \"{out_dir}\"\n"));
    }
    if let Some(ref baseline_dir) = config.defaults.baseline_dir {
        out.push_str(&format!("baseline_dir = \"{baseline_dir}\"\n"));
    }

    // [[bench]] entries
    for bench in &config.benches {
        out.push_str(&format!("\n[[bench]]\nname = \"{}\"\n", bench.name));

        // Format command as TOML array.
        let parts: Vec<String> = bench.command.iter().map(|c| format!("\"{c}\"")).collect();
        out.push_str(&format!("command = [{}]\n", parts.join(", ")));

        if let Some(ref cwd) = bench.cwd {
            out.push_str(&format!("cwd = \"{cwd}\"\n"));
        }
        if let Some(repeat) = bench.repeat {
            out.push_str(&format!("repeat = {repeat}\n"));
        }
        if let Some(warmup) = bench.warmup {
            out.push_str(&format!("warmup = {warmup}\n"));
        }
        if let Some(ref timeout) = bench.timeout {
            out.push_str(&format!("timeout = \"{timeout}\"\n"));
        }
    }

    out
}

// ---------------------------------------------------------------------------
// CI scaffold
// ---------------------------------------------------------------------------

/// Generate CI workflow content for the given platform.
pub fn scaffold_ci(platform: CiPlatform, config_path: &Path) -> String {
    let config_str = config_path.to_string_lossy().replace('\\', "/");
    match platform {
        CiPlatform::GitHub => scaffold_github(&config_str),
        CiPlatform::GitLab => scaffold_gitlab(&config_str),
        CiPlatform::Bitbucket => scaffold_bitbucket(&config_str),
        CiPlatform::CircleCi => scaffold_circleci(&config_str),
    }
}

fn scaffold_github(config_path: &str) -> String {
    format!(
        r#"# .github/workflows/perfgate.yml — generated by `perfgate init`
name: Performance Gate

on:
  pull_request:
    branches: [main]
  push:
    branches: [main]

permissions:
  contents: read
  pull-requests: write

jobs:
  perfgate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: EffortlessMetrics/perfgate@v0
        with:
          config: {config_path}
          all: "true"
          require_baseline: "true"
          upload_artifact: "true"
"#
    )
}

/// Render the onboarding note written by the CLI next to generated artifacts.
pub fn render_onboarding_readme(config_path: &Path, ci_path: Option<&Path>) -> String {
    let config = config_path.to_string_lossy().replace('\\', "/");
    let ci_file = ci_path
        .map(|path| format!("- `{}`: CI performance gate workflow.\n", path.display()))
        .unwrap_or_default();
    let ci_commit = ci_path
        .map(|path| format!("{}, ", path.display()))
        .unwrap_or_default();
    format!(
        r#"# perfgate setup

Generated by `perfgate init`.

## Files

- `{config}`: benchmark commands, budgets, baseline location, and artifact path.
{ci_file}
- `baselines/`: checked-in local baselines. Keep `.gitkeep` until the first baseline is promoted.
- `artifacts/perfgate/`: local and CI output receipts, reports, and PR comment markdown.

## Next

1. Run `perfgate check --config {config} --all`.
2. Promote trusted first runs with `perfgate baseline promote --config {config} --all`.
3. Commit `{config}`, {ci_commit}`baselines/.gitkeep`, and this directory.
"#
    )
}

fn scaffold_gitlab(config_path: &str) -> String {
    format!(
        r#"# .gitlab-ci.yml snippet — generated by `perfgate init`
perfgate:
  stage: test
  script:
    - cargo install perfgate-cli
    - perfgate check --config {config_path} --all --mode cockpit --out-dir artifacts/perfgate
  artifacts:
    paths:
      - artifacts/perfgate/
    when: always
"#
    )
}

fn scaffold_bitbucket(config_path: &str) -> String {
    format!(
        r#"# bitbucket-pipelines.yml snippet — generated by `perfgate init`
pipelines:
  pull-requests:
    '**':
      - step:
          name: Performance Gate
          script:
            - cargo install perfgate-cli
            - perfgate check --config {config_path} --all --mode cockpit --out-dir artifacts/perfgate
          artifacts:
            - artifacts/perfgate/**
"#
    )
}

fn scaffold_circleci(config_path: &str) -> String {
    format!(
        r#"# .circleci/config.yml snippet — generated by `perfgate init`
version: 2.1
jobs:
  perfgate:
    docker:
      - image: cimg/rust:1.80
    steps:
      - checkout
      - run:
          name: Install perfgate
          command: cargo install perfgate-cli
      - run:
          name: Run benchmarks
          command: perfgate check --config {config_path} --all --mode cockpit --out-dir artifacts/perfgate
      - store_artifacts:
          path: artifacts/perfgate
"#
    )
}

/// Return the default CI workflow file path for a platform.
pub fn ci_workflow_path(platform: CiPlatform) -> PathBuf {
    match platform {
        CiPlatform::GitHub => PathBuf::from(".github/workflows/perfgate.yml"),
        CiPlatform::GitLab => PathBuf::from(".gitlab-ci.perfgate.yml"),
        CiPlatform::Bitbucket => PathBuf::from("bitbucket-pipelines.perfgate.yml"),
        CiPlatform::CircleCi => PathBuf::from(".circleci/perfgate.yml"),
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;

    // -- Preset defaults ---------------------------------------------------

    #[test]
    fn preset_standard_defaults() {
        let d = Preset::Standard.defaults();
        assert_eq!(d.repeat, Some(7));
        assert_eq!(d.warmup, Some(1));
        assert_eq!(d.threshold, Some(0.20));
        assert_eq!(d.warn_factor, Some(0.50));
        assert_eq!(d.noise_threshold, Some(0.10));
        assert_eq!(d.noise_policy, Some(NoisePolicy::Warn));
        assert_eq!(d.out_dir.as_deref(), Some("artifacts/perfgate"));
        assert_eq!(d.baseline_dir.as_deref(), Some("baselines"));
    }

    #[test]
    fn preset_release_defaults() {
        let d = Preset::Release.defaults();
        assert_eq!(d.repeat, Some(10));
        assert_eq!(d.warmup, Some(2));
        assert_eq!(d.threshold, Some(0.10));
        assert_eq!(d.warn_factor, Some(0.50));
        assert_eq!(d.noise_threshold, Some(0.08));
        assert_eq!(d.noise_policy, Some(NoisePolicy::Warn));
    }

    #[test]
    fn preset_tier1fast_defaults() {
        let d = Preset::Tier1Fast.defaults();
        assert_eq!(d.repeat, Some(3));
        assert_eq!(d.warmup, Some(1));
        assert_eq!(d.threshold, Some(0.30));
        assert_eq!(d.warn_factor, Some(0.50));
        assert_eq!(d.noise_threshold, Some(0.15));
        assert_eq!(d.noise_policy, Some(NoisePolicy::Warn));
    }

    // -- Rust / Cargo discovery -------------------------------------------

    #[test]
    fn discover_cargo_bench_targets() {
        let dir = tempfile::tempdir().unwrap();
        let cargo = dir.path().join("Cargo.toml");
        fs::write(
            &cargo,
            r#"
[package]
name = "example"
version = "0.1.0"
edition = "2021"

[[bench]]
name = "my-bench"
harness = false
"#,
        )
        .unwrap();

        let found = discover_benchmarks(dir.path());
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].name, "my-bench");
        assert_eq!(found[0].source, BenchSource::Criterion); // harness=false
        assert_eq!(
            found[0].command,
            vec!["cargo", "bench", "--bench", "my-bench"]
        );
    }

    #[test]
    fn discover_cargo_bench_harness_true() {
        let dir = tempfile::tempdir().unwrap();
        let cargo = dir.path().join("Cargo.toml");
        fs::write(
            &cargo,
            r#"
[package]
name = "example"
version = "0.1.0"
edition = "2021"

[[bench]]
name = "basic"
"#,
        )
        .unwrap();

        let found = discover_benchmarks(dir.path());
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].source, BenchSource::CargoTarget);
    }

    #[test]
    fn discover_criterion_from_benches_dir() {
        let dir = tempfile::tempdir().unwrap();
        // Need a Cargo.toml so the Rust scanner fires.
        fs::write(
            dir.path().join("Cargo.toml"),
            "[package]\nname = \"x\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
        )
        .unwrap();

        let benches_dir = dir.path().join("benches");
        fs::create_dir(&benches_dir).unwrap();
        fs::write(
            benches_dir.join("perf.rs"),
            "criterion_group!(benches, bench_fn);\ncriterion_main!(benches);\n",
        )
        .unwrap();

        let found = discover_benchmarks(dir.path());
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].name, "perf");
        assert_eq!(found[0].source, BenchSource::Criterion);
    }

    #[test]
    fn criterion_dedup_with_cargo_target() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(
            dir.path().join("Cargo.toml"),
            r#"
[package]
name = "x"
version = "0.1.0"
edition = "2021"

[[bench]]
name = "perf"
harness = false
"#,
        )
        .unwrap();

        let benches_dir = dir.path().join("benches");
        fs::create_dir(&benches_dir).unwrap();
        fs::write(
            benches_dir.join("perf.rs"),
            "criterion_group!(benches, bench_fn);\ncriterion_main!(benches);\n",
        )
        .unwrap();

        let found = discover_benchmarks(dir.path());
        // Should only appear once.
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].name, "perf");
    }

    // -- Go discovery ------------------------------------------------------

    #[test]
    fn discover_go_benches() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("go.mod"), "module example\n").unwrap();
        fs::write(
            dir.path().join("bench_test.go"),
            "package main\n\nfunc BenchmarkFoo(b *testing.B) {\n}\n",
        )
        .unwrap();

        let found = discover_benchmarks(dir.path());
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].name, "go-bench");
        assert_eq!(found[0].source, BenchSource::GoBench);
        assert!(found[0].command.contains(&"-bench=.".to_string()));
    }

    #[test]
    fn discover_go_benches_in_subpackage() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("go.mod"), "module example\n").unwrap();
        let sub = dir.path().join("pkg").join("fast");
        fs::create_dir_all(&sub).unwrap();
        fs::write(
            sub.join("bench_test.go"),
            "package fast\nfunc BenchmarkBar(b *testing.B) {}\n",
        )
        .unwrap();

        let found = discover_benchmarks(dir.path());
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].name, "go-bench-pkg-fast");
    }

    // -- Python discovery --------------------------------------------------

    #[test]
    fn discover_pytest_benchmark_from_requirements() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(
            dir.path().join("requirements.txt"),
            "pytest\npytest-benchmark\n",
        )
        .unwrap();

        let found = discover_benchmarks(dir.path());
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].name, "pytest-bench");
        assert_eq!(found[0].source, BenchSource::PytestBenchmark);
    }

    #[test]
    fn discover_pytest_benchmark_from_pyproject() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(
            dir.path().join("pyproject.toml"),
            "[project.optional-dependencies]\ntest = [\"pytest-benchmark\"]\n",
        )
        .unwrap();

        let found = discover_benchmarks(dir.path());
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].source, BenchSource::PytestBenchmark);
    }

    #[test]
    fn discover_pytest_benchmark_from_conftest() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(
            dir.path().join("conftest.py"),
            "def test_speed(benchmark):\n    benchmark(lambda: None)\n",
        )
        .unwrap();

        let found = discover_benchmarks(dir.path());
        assert_eq!(found.len(), 1);
    }

    // -- Empty repo --------------------------------------------------------

    #[test]
    fn empty_repo_discovers_nothing() {
        let dir = tempfile::tempdir().unwrap();
        let found = discover_benchmarks(dir.path());
        assert!(found.is_empty());
    }

    // -- Config generation -------------------------------------------------

    #[test]
    fn generate_config_produces_valid_toml() {
        let benches = vec![
            DiscoveredBench {
                name: "my-bench".into(),
                command: vec!["cargo".into(), "bench".into()],
                source: BenchSource::CargoTarget,
            },
            DiscoveredBench {
                name: "go-bench".into(),
                command: vec!["go".into(), "test".into(), "-bench=.".into(), ".".into()],
                source: BenchSource::GoBench,
            },
        ];

        let config = generate_config(&benches, Preset::Standard);
        assert_eq!(config.benches.len(), 2);
        assert_eq!(config.defaults.repeat, Some(7));
        assert_eq!(config.defaults.threshold, Some(0.20));
        assert_eq!(
            config.defaults.out_dir.as_deref(),
            Some("artifacts/perfgate")
        );
        assert_eq!(config.defaults.baseline_dir.as_deref(), Some("baselines"));
    }

    #[test]
    fn render_config_toml_roundtrip() {
        let benches = vec![DiscoveredBench {
            name: "my-bench".into(),
            command: vec![
                "cargo".into(),
                "bench".into(),
                "--bench".into(),
                "my-bench".into(),
            ],
            source: BenchSource::CargoTarget,
        }];

        let config = generate_config(&benches, Preset::Release);
        let toml_str = render_config_toml(&config);

        // The rendered TOML must parse back without error.
        let parsed: ConfigFile = toml::from_str(&toml_str).expect("rendered TOML should parse");
        assert_eq!(parsed.benches.len(), 1);
        assert_eq!(parsed.benches[0].name, "my-bench");
        assert_eq!(parsed.defaults.repeat, Some(10));
        assert_eq!(parsed.defaults.threshold, Some(0.10));
        assert_eq!(parsed.defaults.warn_factor, Some(0.50));
        assert_eq!(parsed.defaults.noise_policy, Some(NoisePolicy::Warn));
        assert_eq!(
            parsed.defaults.out_dir.as_deref(),
            Some("artifacts/perfgate")
        );
        assert_eq!(parsed.defaults.baseline_dir.as_deref(), Some("baselines"));
    }

    // -- CI scaffold -------------------------------------------------------

    #[test]
    fn scaffold_github_ci() {
        let content = scaffold_ci(CiPlatform::GitHub, Path::new("perfgate.toml"));
        assert!(content.contains("EffortlessMetrics/perfgate@v0"));
        assert!(content.contains("perfgate.toml"));
        assert!(content.contains("require_baseline: \"true\""));
        assert!(content.contains("ubuntu-latest"));
    }

    #[test]
    fn onboarding_readme_mentions_artifacts_and_next_steps() {
        let content = render_onboarding_readme(
            Path::new("perfgate.toml"),
            Some(Path::new(".github/workflows/perfgate.yml")),
        );

        assert!(content.contains("artifacts/perfgate/"));
        assert!(content.contains("baselines/"));
        assert!(content.contains(".github/workflows/perfgate.yml"));
        assert!(content.contains("perfgate check --config perfgate.toml --all"));
        assert!(content.contains("perfgate baseline promote --config perfgate.toml --all"));
    }

    #[test]
    fn scaffold_gitlab_ci() {
        let content = scaffold_ci(CiPlatform::GitLab, Path::new("perfgate.toml"));
        assert!(content.contains("perfgate check"));
        assert!(content.contains("stage: test"));
    }

    #[test]
    fn scaffold_bitbucket_ci() {
        let content = scaffold_ci(CiPlatform::Bitbucket, Path::new("perfgate.toml"));
        assert!(content.contains("perfgate check"));
        assert!(content.contains("pipelines"));
    }

    #[test]
    fn scaffold_circleci_ci() {
        let content = scaffold_ci(CiPlatform::CircleCi, Path::new("perfgate.toml"));
        assert!(content.contains("perfgate check"));
        assert!(content.contains("version: 2.1"));
    }

    #[test]
    fn ci_workflow_paths() {
        assert_eq!(
            ci_workflow_path(CiPlatform::GitHub),
            PathBuf::from(".github/workflows/perfgate.yml")
        );
        assert_eq!(
            ci_workflow_path(CiPlatform::GitLab),
            PathBuf::from(".gitlab-ci.perfgate.yml")
        );
    }

    // -- BenchSource display -----------------------------------------------

    #[test]
    fn bench_source_display() {
        assert_eq!(
            format!("{}", BenchSource::CargoTarget),
            "cargo bench target"
        );
        assert_eq!(format!("{}", BenchSource::Criterion), "criterion benchmark");
        assert_eq!(format!("{}", BenchSource::GoBench), "go benchmark");
        assert_eq!(
            format!("{}", BenchSource::PytestBenchmark),
            "pytest-benchmark"
        );
        assert_eq!(format!("{}", BenchSource::Custom), "custom");
    }

    // -- Mixed repo discovery ----------------------------------------------

    #[test]
    fn discover_mixed_repo() {
        let dir = tempfile::tempdir().unwrap();

        // Rust
        fs::write(
            dir.path().join("Cargo.toml"),
            r#"
[package]
name = "mixed"
version = "0.1.0"
edition = "2021"

[[bench]]
name = "rust-bench"
harness = false
"#,
        )
        .unwrap();

        // Go
        fs::write(dir.path().join("go.mod"), "module mixed\n").unwrap();
        fs::write(
            dir.path().join("bench_test.go"),
            "package main\nfunc BenchmarkX(b *testing.B) {}\n",
        )
        .unwrap();

        // Python
        fs::write(dir.path().join("requirements.txt"), "pytest-benchmark\n").unwrap();

        let found = discover_benchmarks(dir.path());
        assert_eq!(found.len(), 3);

        let names: Vec<&str> = found.iter().map(|b| b.name.as_str()).collect();
        assert!(names.contains(&"rust-bench"));
        assert!(names.contains(&"go-bench"));
        assert!(names.contains(&"pytest-bench"));
    }
}