checkleft 0.1.0-alpha.8

Experimental repository convention checker; API and behavior may change without notice
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
use std::collections::BTreeMap;
use std::fs;
use std::path::Path;
use std::sync::{Arc, Mutex};

use anyhow::Result;
use async_trait::async_trait;
use tempfile::tempdir;

use crate::check::{Check, CheckRegistry, ConfiguredCheck};
use crate::checks::register_builtin_checks;
use crate::config::ConfigResolver;
use crate::external::{
    ExternalCheckExecutor, ExternalCheckImplementationRef, ExternalCheckPackage,
    ExternalCheckPackageImplementation, ExternalCheckPackageProvider, ExternalCheckSourcePackage,
};
use crate::input::{ChangeKind, ChangeSet, ChangedFile, SourceTree};
use crate::output::{CheckResult, Finding, Location, Severity};
use crate::source_tree::LocalSourceTree;

use super::Runner;

struct StaticExternalProvider {
    package: Option<ExternalCheckPackage>,
}

impl ExternalCheckPackageProvider for StaticExternalProvider {
    fn resolve(
        &self,
        _implementation_ref: &ExternalCheckImplementationRef,
    ) -> Result<Option<ExternalCheckPackage>> {
        Ok(self.package.clone())
    }
}

struct StaticExternalExecutor {
    result: Option<CheckResult>,
    error_message: Option<String>,
    seen_packages: Arc<Mutex<Vec<String>>>,
}

impl ExternalCheckExecutor for StaticExternalExecutor {
    fn execute(
        &self,
        package: &ExternalCheckPackage,
        _changeset: &ChangeSet,
        _source_tree: &dyn SourceTree,
        _config: &toml::Value,
    ) -> Result<CheckResult> {
        self.seen_packages
            .lock()
            .expect("lock seen packages")
            .push(package.id.clone());

        if let Some(error_message) = self.error_message.as_ref() {
            anyhow::bail!("{error_message}");
        }

        Ok(self.result.clone().unwrap_or_else(|| CheckResult {
            check_id: package.id.clone(),
            findings: Vec::new(),
        }))
    }
}

#[derive(Clone)]
struct CapturingCheck {
    id: String,
    seen_files: Arc<Mutex<Vec<String>>>,
}

#[async_trait]
impl Check for CapturingCheck {
    fn id(&self) -> &str {
        &self.id
    }

    fn description(&self) -> &str {
        "captures the input files"
    }

    fn configure(&self, _config: &toml::Value) -> Result<Arc<dyn ConfiguredCheck>> {
        Ok(Arc::new(self.clone()))
    }
}

#[async_trait]
impl ConfiguredCheck for CapturingCheck {
    async fn run(&self, changeset: &ChangeSet, _tree: &dyn SourceTree) -> Result<CheckResult> {
        let files: Vec<_> = changeset
            .changed_files
            .iter()
            .map(|changed| changed.path.display().to_string())
            .collect();
        self.seen_files.lock().expect("lock files").extend(files);

        Ok(CheckResult {
            check_id: self.id().to_owned(),
            findings: Vec::new(),
        })
    }
}

#[derive(Clone)]
struct MetadataCapturingCheck {
    id: String,
    directive_name: String,
    seen_bypass_reason: Arc<Mutex<Option<String>>>,
    seen_change_id: Arc<Mutex<Option<String>>>,
    seen_repository: Arc<Mutex<Option<String>>>,
}

#[async_trait]
impl Check for MetadataCapturingCheck {
    fn id(&self) -> &str {
        &self.id
    }

    fn description(&self) -> &str {
        "captures description and change metadata"
    }

    fn configure(&self, _config: &toml::Value) -> Result<Arc<dyn ConfiguredCheck>> {
        Ok(Arc::new(self.clone()))
    }
}

#[async_trait]
impl ConfiguredCheck for MetadataCapturingCheck {
    async fn run(&self, changeset: &ChangeSet, _tree: &dyn SourceTree) -> Result<CheckResult> {
        *self.seen_bypass_reason.lock().expect("lock bypass reason") =
            changeset.bypass_reason(&self.directive_name);
        *self.seen_change_id.lock().expect("lock change id") = changeset.change_id.clone();
        *self.seen_repository.lock().expect("lock repository") = changeset.repository.clone();

        Ok(CheckResult {
            check_id: self.id().to_owned(),
            findings: Vec::new(),
        })
    }
}

#[tokio::test]
async fn runner_groups_files_by_check() {
    let temp = tempdir().expect("create temp dir");
    fs::create_dir_all(temp.path().join("backend/src")).expect("create dirs");
    fs::write(
        temp.path().join("CHECKS.toml"),
        r#"
[[checks]]
id = "capture"
"#,
    )
    .expect("write config");

    let seen_files = Arc::new(Mutex::new(Vec::new()));
    let mut registry = CheckRegistry::new();
    registry
        .register(CapturingCheck {
            id: "capture".to_owned(),
            seen_files: Arc::clone(&seen_files),
        })
        .expect("register check");

    let runner = Runner::new(
        Arc::new(registry),
        Arc::new(ConfigResolver::new(temp.path()).expect("resolver")),
        Arc::new(LocalSourceTree::new(temp.path()).expect("tree")),
    );

    let results = runner
        .run_changeset(&ChangeSet::new(vec![
            ChangedFile {
                path: Path::new("backend/src/a.rs").to_path_buf(),
                kind: ChangeKind::Modified,
                old_path: None,
            },
            ChangedFile {
                path: Path::new("backend/src/b.rs").to_path_buf(),
                kind: ChangeKind::Modified,
                old_path: None,
            },
        ]))
        .await
        .expect("run checks");

    assert_eq!(results.len(), 1);
    let files = seen_files.lock().expect("lock files").clone();
    assert_eq!(
        files,
        vec!["backend/src/a.rs".to_owned(), "backend/src/b.rs".to_owned()]
    );
}

#[tokio::test]
async fn runner_propagates_description_and_change_metadata_to_checks() {
    let temp = tempdir().expect("create temp dir");
    fs::create_dir_all(temp.path().join("backend/src")).expect("create dirs");
    fs::write(
        temp.path().join("CHECKS.toml"),
        r#"
[[checks]]
id = "capture-descriptions"
"#,
    )
    .expect("write config");

    let directive_name = "BYPASS_CAPTURE_DESCRIPTIONS".to_owned();
    let seen_bypass_reason = Arc::new(Mutex::new(None));
    let seen_change_id = Arc::new(Mutex::new(None));
    let seen_repository = Arc::new(Mutex::new(None));
    let mut registry = CheckRegistry::new();
    registry
        .register(MetadataCapturingCheck {
            id: "capture-descriptions".to_owned(),
            directive_name: directive_name.clone(),
            seen_bypass_reason: Arc::clone(&seen_bypass_reason),
            seen_change_id: Arc::clone(&seen_change_id),
            seen_repository: Arc::clone(&seen_repository),
        })
        .expect("register check");

    let runner = Runner::new(
        Arc::new(registry),
        Arc::new(ConfigResolver::new(temp.path()).expect("resolver")),
        Arc::new(LocalSourceTree::new(temp.path()).expect("tree")),
    );

    let results = runner
        .run_changeset(
            &ChangeSet::new(vec![ChangedFile {
                path: Path::new("backend/src/a.rs").to_path_buf(),
                kind: ChangeKind::Modified,
                old_path: None,
            }])
            .with_commit_description(Some(
                "BYPASS_CAPTURE_DESCRIPTIONS=Legitimate exception for validation.".to_owned(),
            ))
            .with_change_id(Some("235".to_owned()))
            .with_repository(Some("example/flunge".to_owned())),
        )
        .await
        .expect("run checks");

    assert_eq!(results.len(), 1);
    assert_eq!(
        *seen_bypass_reason.lock().expect("lock bypass reason"),
        Some("Legitimate exception for validation.".to_owned())
    );
    assert_eq!(
        *seen_change_id.lock().expect("lock change id"),
        Some("235".to_owned())
    );
    assert_eq!(
        *seen_repository.lock().expect("lock repository"),
        Some("example/flunge".to_owned())
    );
}

#[tokio::test]
async fn runner_ignores_checks_toml_by_default() {
    let temp = tempdir().expect("create temp dir");
    fs::write(
        temp.path().join("CHECKS.toml"),
        r#"
[[checks]]
id = "capture"
"#,
    )
    .expect("write config");

    let seen_files = Arc::new(Mutex::new(Vec::new()));
    let mut registry = CheckRegistry::new();
    registry
        .register(CapturingCheck {
            id: "capture".to_owned(),
            seen_files: Arc::clone(&seen_files),
        })
        .expect("register check");

    let runner = Runner::new(
        Arc::new(registry),
        Arc::new(ConfigResolver::new(temp.path()).expect("resolver")),
        Arc::new(LocalSourceTree::new(temp.path()).expect("tree")),
    );

    let results = runner
        .run_changeset(&ChangeSet::new(vec![ChangedFile {
            path: Path::new("CHECKS.toml").to_path_buf(),
            kind: ChangeKind::Modified,
            old_path: None,
        }]))
        .await
        .expect("run checks");

    assert!(results.is_empty());
    let files = seen_files.lock().expect("lock files").clone();
    assert!(files.is_empty());

    let configured = runner
        .list_configured_checks(&ChangeSet::new(vec![ChangedFile {
            path: Path::new("CHECKS.toml").to_path_buf(),
            kind: ChangeKind::Modified,
            old_path: None,
        }]))
        .expect("list checks");
    assert!(configured.is_empty());
}

#[tokio::test]
async fn runner_can_opt_in_to_check_checks_toml() {
    let temp = tempdir().expect("create temp dir");
    fs::write(
        temp.path().join("CHECKS.toml"),
        r#"
[settings]
include_config_files = true

[[checks]]
id = "capture"
"#,
    )
    .expect("write config");

    let seen_files = Arc::new(Mutex::new(Vec::new()));
    let mut registry = CheckRegistry::new();
    registry
        .register(CapturingCheck {
            id: "capture".to_owned(),
            seen_files: Arc::clone(&seen_files),
        })
        .expect("register check");

    let runner = Runner::new(
        Arc::new(registry),
        Arc::new(ConfigResolver::new(temp.path()).expect("resolver")),
        Arc::new(LocalSourceTree::new(temp.path()).expect("tree")),
    );

    let results = runner
        .run_changeset(&ChangeSet::new(vec![ChangedFile {
            path: Path::new("CHECKS.toml").to_path_buf(),
            kind: ChangeKind::Modified,
            old_path: None,
        }]))
        .await
        .expect("run checks");

    assert_eq!(results.len(), 1);
    let files = seen_files.lock().expect("lock files").clone();
    assert_eq!(files, vec!["CHECKS.toml".to_owned()]);

    let configured = runner
        .list_configured_checks(&ChangeSet::new(vec![ChangedFile {
            path: Path::new("CHECKS.toml").to_path_buf(),
            kind: ChangeKind::Modified,
            old_path: None,
        }]))
        .expect("list checks");
    assert_eq!(configured, vec!["capture".to_owned()]);
}

#[tokio::test]
async fn runner_reports_check_errors_in_output() {
    struct FailingCheck;

    #[async_trait]
    impl Check for FailingCheck {
        fn id(&self) -> &str {
            "fails"
        }

        fn description(&self) -> &str {
            "fails intentionally"
        }

        fn configure(&self, _config: &toml::Value) -> Result<Arc<dyn ConfiguredCheck>> {
            Ok(Arc::new(Self))
        }
    }

    #[async_trait]
    impl ConfiguredCheck for FailingCheck {
        async fn run(&self, _changeset: &ChangeSet, _tree: &dyn SourceTree) -> Result<CheckResult> {
            anyhow::bail!("boom");
        }
    }

    let temp = tempdir().expect("create temp dir");
    fs::create_dir_all(temp.path().join("backend/src")).expect("create dirs");
    fs::write(
        temp.path().join("CHECKS.toml"),
        r#"
[[checks]]
id = "fails"
"#,
    )
    .expect("write config");

    let mut registry = CheckRegistry::new();
    registry.register(FailingCheck).expect("register check");

    let runner = Runner::new(
        Arc::new(registry),
        Arc::new(ConfigResolver::new(temp.path()).expect("resolver")),
        Arc::new(LocalSourceTree::new(temp.path()).expect("tree")),
    );

    let results = runner
        .run_changeset(&ChangeSet::new(vec![ChangedFile {
            path: Path::new("backend/src/a.rs").to_path_buf(),
            kind: ChangeKind::Modified,
            old_path: None,
        }]))
        .await
        .expect("run checks");

    assert_eq!(results.len(), 1);
    assert_eq!(results[0].check_id, "fails");
    assert_eq!(results[0].findings[0].severity, Severity::Error);
    assert!(results[0].findings[0].message.contains("boom"));
}

#[tokio::test]
async fn runner_reports_malformed_checks_yaml_as_config_finding() {
    let temp = tempdir().expect("create temp dir");
    fs::create_dir_all(temp.path().join("backend/src")).expect("create dirs");
    fs::write(
        temp.path().join("CHECKS.yaml"),
        r#"
checks:
  - id: file-size
    config:
      max_lines: [1, 2
"#,
    )
    .expect("write config");

    let runner = Runner::new(
        Arc::new(CheckRegistry::new()),
        Arc::new(ConfigResolver::new(temp.path()).expect("resolver")),
        Arc::new(LocalSourceTree::new(temp.path()).expect("tree")),
    );

    let results = runner
        .run_changeset(&ChangeSet::new(vec![ChangedFile {
            path: Path::new("backend/src/a.rs").to_path_buf(),
            kind: ChangeKind::Modified,
            old_path: None,
        }]))
        .await
        .expect("run checks");

    assert_eq!(results.len(), 1);
    assert_eq!(results[0].check_id, "checks-config");
    assert_eq!(
        results[0].findings[0]
            .location
            .as_ref()
            .map(|location| &location.path),
        Some(&Path::new("CHECKS.yaml").to_path_buf())
    );
    assert!(
        results[0].findings[0]
            .message
            .contains("failed to parse checks config")
    );
}

#[tokio::test]
async fn runner_reports_invalid_builtin_config_on_checks_file() {
    let temp = tempdir().expect("create temp dir");
    fs::create_dir_all(temp.path().join("backend/src")).expect("create dirs");
    fs::write(
        temp.path().join("CHECKS.toml"),
        r#"
[[checks]]
id = "file-size"

[checks.config]
max_lines = "many"
"#,
    )
    .expect("write config");

    let mut registry = CheckRegistry::new();
    register_builtin_checks(&mut registry).expect("register built-ins");

    let runner = Runner::new(
        Arc::new(registry),
        Arc::new(ConfigResolver::new(temp.path()).expect("resolver")),
        Arc::new(LocalSourceTree::new(temp.path()).expect("tree")),
    );

    let results = runner
        .run_changeset(&ChangeSet::new(vec![ChangedFile {
            path: Path::new("backend/src/a.rs").to_path_buf(),
            kind: ChangeKind::Modified,
            old_path: None,
        }]))
        .await
        .expect("run checks");

    assert_eq!(results.len(), 1);
    assert_eq!(results[0].check_id, "file-size");
    assert_eq!(
        results[0].findings[0]
            .location
            .as_ref()
            .map(|location| &location.path),
        Some(&Path::new("CHECKS.toml").to_path_buf())
    );
    assert!(
        results[0].findings[0]
            .message
            .contains("invalid file-size check config")
    );
    assert!(
        !results[0].findings[0]
            .message
            .contains("check execution failed")
    );
}

#[tokio::test]
async fn runner_reports_unknown_configured_checks() {
    let temp = tempdir().expect("create temp dir");
    fs::create_dir_all(temp.path().join("backend/src")).expect("create dirs");
    fs::write(
        temp.path().join("CHECKS.toml"),
        r#"
[[checks]]
id = "spelling-typos"
check = "not-registered"
"#,
    )
    .expect("write config");

    let runner = Runner::new(
        Arc::new(CheckRegistry::new()),
        Arc::new(ConfigResolver::new(temp.path()).expect("resolver")),
        Arc::new(LocalSourceTree::new(temp.path()).expect("tree")),
    );

    let results = runner
        .run_changeset(&ChangeSet::new(vec![ChangedFile {
            path: Path::new("backend/src/a.rs").to_path_buf(),
            kind: ChangeKind::Modified,
            old_path: None,
        }]))
        .await
        .expect("run checks");

    assert_eq!(results.len(), 1);
    assert_eq!(results[0].check_id, "spelling-typos");
    assert_eq!(results[0].findings[0].severity, Severity::Error);
    assert!(
        results[0].findings[0]
            .message
            .contains("unknown implementation")
    );
}

#[tokio::test]
async fn runner_reports_instance_id_not_implementation_id() {
    let temp = tempdir().expect("create temp dir");
    fs::create_dir_all(temp.path().join("docs")).expect("create dirs");
    fs::write(temp.path().join("docs/file.md"), "teh value\n").expect("write file");
    fs::write(
        temp.path().join("CHECKS.toml"),
        r#"
[[checks]]
id = "spelling"
check = "capture"
"#,
    )
    .expect("write config");

    let seen_files = Arc::new(Mutex::new(Vec::new()));
    let mut registry = CheckRegistry::new();
    registry
        .register(CapturingCheck {
            id: "capture".to_owned(),
            seen_files,
        })
        .expect("register check");

    let runner = Runner::new(
        Arc::new(registry),
        Arc::new(ConfigResolver::new(temp.path()).expect("resolver")),
        Arc::new(LocalSourceTree::new(temp.path()).expect("tree")),
    );

    let results = runner
        .run_changeset(&ChangeSet::new(vec![ChangedFile {
            path: Path::new("docs/file.md").to_path_buf(),
            kind: ChangeKind::Modified,
            old_path: None,
        }]))
        .await
        .expect("run checks");

    assert_eq!(results.len(), 1);
    assert_eq!(results[0].check_id, "spelling");
}

include!("tests_policy.rs");
include!("tests_external.rs");