diffguard 0.2.0

CLI for diff-scoped governance linting in pull requests
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
//! Preset templates for diffguard init command.
//!
//! Each preset provides a starter configuration file tailored to a specific use case.

use clap::ValueEnum;

/// Available preset types for configuration generation.
#[derive(Clone, Copy, Debug, Default, ValueEnum, PartialEq, Eq)]
pub enum Preset {
    /// Minimal starter config with basic settings
    #[default]
    Minimal,
    /// Rust best practices (no_unwrap, no_dbg, no_todo, no_print)
    RustQuality,
    /// Credential and secret detection patterns
    Secrets,
    /// JavaScript console.log, debugger, etc.
    JsConsole,
    /// Python print, breakpoint, pdb
    PythonDebug,
}

impl Preset {
    /// Get the display name of the preset.
    pub fn name(&self) -> &'static str {
        match self {
            Preset::Minimal => "minimal",
            Preset::RustQuality => "rust-quality",
            Preset::Secrets => "secrets",
            Preset::JsConsole => "js-console",
            Preset::PythonDebug => "python-debug",
        }
    }

    /// Get the description of the preset.
    #[allow(dead_code)]
    pub fn description(&self) -> &'static str {
        match self {
            Preset::Minimal => "Minimal starter configuration with basic settings",
            Preset::RustQuality => "Rust best practices (no unwrap, no dbg, no todo, no print)",
            Preset::Secrets => "Credential and secret detection patterns",
            Preset::JsConsole => "JavaScript/TypeScript console and debugger detection",
            Preset::PythonDebug => "Python print, breakpoint, and pdb detection",
        }
    }

    /// Generate the TOML configuration content for this preset.
    pub fn generate(&self) -> String {
        match self {
            Preset::Minimal => generate_minimal(),
            Preset::RustQuality => generate_rust_quality(),
            Preset::Secrets => generate_secrets(),
            Preset::JsConsole => generate_js_console(),
            Preset::PythonDebug => generate_python_debug(),
        }
    }
}

fn generate_minimal() -> String {
    r#"# diffguard.toml - Minimal preset
# Generated by: diffguard init --preset minimal
#
# This is a starter configuration. Add rules below or use a different preset:
#   diffguard init --preset rust-quality   # Rust best practices
#   diffguard init --preset secrets        # Secret detection
#   diffguard init --preset js-console     # JavaScript/TypeScript
#   diffguard init --preset python-debug   # Python debugging

[defaults]
base = "origin/main"
scope = "added"         # added | changed | modified | deleted (changed kept for compatibility)
fail_on = "error"       # error | warn | never
max_findings = 200
diff_context = 0

# Example rule (uncomment and customize):
# [[rule]]
# id = "example.no_todo"
# severity = "warn"
# message = "TODO comments should be resolved before merging."
# patterns = ["\\bTODO\\b", "\\bFIXME\\b"]
# paths = ["**/*"]
# exclude_paths = []
# ignore_comments = false
# ignore_strings = true
"#
    .to_string()
}

fn generate_rust_quality() -> String {
    r#"# diffguard.toml - Rust Quality preset
# Generated by: diffguard init --preset rust-quality
#
# Enforces Rust best practices for production code.

[defaults]
base = "origin/main"
scope = "added"
fail_on = "error"
max_findings = 200
diff_context = 0

[[rule]]
id = "rust.no_unwrap"
severity = "error"
message = "Avoid unwrap() in production code - use proper error handling."
languages = ["rust"]
patterns = ["\\.unwrap\\("]
paths = ["**/*.rs"]
exclude_paths = ["**/tests/**", "**/benches/**", "**/examples/**"]
ignore_comments = true
ignore_strings = true

[[rule]]
id = "rust.no_expect"
severity = "warn"
message = "Consider replacing expect() with proper error handling."
languages = ["rust"]
patterns = ["\\.expect\\("]
paths = ["**/*.rs"]
exclude_paths = ["**/tests/**", "**/benches/**", "**/examples/**"]
ignore_comments = true
ignore_strings = true

[[rule]]
id = "rust.no_dbg"
severity = "error"
message = "Remove dbg!() macro before merging."
languages = ["rust"]
patterns = ["\\bdbg!\\("]
paths = ["**/*.rs"]
exclude_paths = ["**/tests/**", "**/benches/**", "**/examples/**"]
ignore_comments = true
ignore_strings = true

[[rule]]
id = "rust.no_println"
severity = "warn"
message = "Remove println!/eprintln! before merging - use proper logging."
languages = ["rust"]
patterns = ["\\bprintln!\\(", "\\beprintln!\\("]
paths = ["**/*.rs"]
exclude_paths = ["**/tests/**", "**/benches/**", "**/examples/**", "**/bin/**"]
ignore_comments = true
ignore_strings = true

[[rule]]
id = "rust.no_todo"
severity = "warn"
message = "Resolve TODO/FIXME comments before merging."
languages = ["rust"]
patterns = ["\\bTODO\\b", "\\bFIXME\\b", "\\bHACK\\b"]
paths = ["**/*.rs"]
exclude_paths = []
ignore_comments = false
ignore_strings = true

[[rule]]
id = "rust.no_unimplemented"
severity = "error"
message = "Replace unimplemented!()/todo!() with proper implementation."
languages = ["rust"]
patterns = ["\\bunimplemented!\\(", "\\btodo!\\("]
paths = ["**/*.rs"]
exclude_paths = ["**/tests/**", "**/benches/**", "**/examples/**"]
ignore_comments = true
ignore_strings = true
"#
    .to_string()
}

fn generate_secrets() -> String {
    r#"# diffguard.toml - Secrets Detection preset
# Generated by: diffguard init --preset secrets
#
# Detects potential secrets and credentials in code.
# Note: This uses pattern matching and may have false positives.
# Always review findings manually.

[defaults]
base = "origin/main"
scope = "added"
fail_on = "error"
max_findings = 200
diff_context = 0

[[rule]]
id = "secrets.api_key"
severity = "error"
message = "Potential API key detected - use environment variables instead."
patterns = [
    "(?i)(api[_-]?key|apikey)\\s*[=:]\\s*['\"][^'\"]{8,}['\"]",
    "(?i)(api[_-]?key|apikey)\\s*=\\s*['\"][^'\"]{8,}['\"]",
]
paths = ["**/*"]
exclude_paths = ["**/*.md", "**/docs/**", "**/*.example", "**/*.sample"]
ignore_comments = true
ignore_strings = false

[[rule]]
id = "secrets.secret_key"
severity = "error"
message = "Potential secret key detected - use environment variables instead."
patterns = [
    "(?i)(secret[_-]?key|secretkey)\\s*[=:]\\s*['\"][^'\"]{8,}['\"]",
    "(?i)(client[_-]?secret)\\s*[=:]\\s*['\"][^'\"]{8,}['\"]",
]
paths = ["**/*"]
exclude_paths = ["**/*.md", "**/docs/**", "**/*.example", "**/*.sample"]
ignore_comments = true
ignore_strings = false

[[rule]]
id = "secrets.password"
severity = "error"
message = "Potential hardcoded password detected - use environment variables instead."
patterns = [
    "(?i)(password|passwd|pwd)\\s*[=:]\\s*['\"][^'\"]{4,}['\"]",
]
paths = ["**/*"]
exclude_paths = ["**/*.md", "**/docs/**", "**/*.example", "**/*.sample", "**/*.test.*", "**/tests/**"]
ignore_comments = true
ignore_strings = false

[[rule]]
id = "secrets.private_key"
severity = "error"
message = "Potential private key detected - never commit private keys."
patterns = [
    "-----BEGIN (RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----",
    "-----BEGIN PGP PRIVATE KEY BLOCK-----",
]
paths = ["**/*"]
exclude_paths = ["**/*.md", "**/docs/**"]
ignore_comments = false
ignore_strings = false

[[rule]]
id = "secrets.aws_credentials"
severity = "error"
message = "Potential AWS credentials detected - use IAM roles or environment variables."
patterns = [
    "(?i)aws[_-]?(access[_-]?key[_-]?id|secret[_-]?access[_-]?key)\\s*[=:]\\s*['\"][A-Za-z0-9/+=]{16,}['\"]",
    "AKIA[0-9A-Z]{16}",
]
paths = ["**/*"]
exclude_paths = ["**/*.md", "**/docs/**", "**/*.example", "**/*.sample"]
ignore_comments = true
ignore_strings = false

[[rule]]
id = "secrets.jwt_token"
severity = "error"
message = "Potential JWT token detected - tokens should not be committed."
patterns = [
    "eyJ[A-Za-z0-9_-]{10,}\\.eyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}",
]
paths = ["**/*"]
exclude_paths = ["**/*.md", "**/docs/**", "**/tests/**"]
ignore_comments = true
ignore_strings = false

[[rule]]
id = "secrets.generic_token"
severity = "warn"
message = "Potential token or secret detected - review if this should be committed."
patterns = [
    "(?i)(token|auth[_-]?token|bearer)\\s*[=:]\\s*['\"][^'\"]{20,}['\"]",
]
paths = ["**/*"]
exclude_paths = ["**/*.md", "**/docs/**", "**/*.example", "**/*.sample", "**/tests/**"]
ignore_comments = true
ignore_strings = false
"#
    .to_string()
}

fn generate_js_console() -> String {
    r#"# diffguard.toml - JavaScript/TypeScript Console preset
# Generated by: diffguard init --preset js-console
#
# Detects debugging statements in JavaScript and TypeScript code.

[defaults]
base = "origin/main"
scope = "added"
fail_on = "error"
max_findings = 200
diff_context = 0

[[rule]]
id = "js.no_console_log"
severity = "warn"
message = "Remove console.log() before merging - use a proper logger."
languages = ["javascript", "typescript"]
patterns = ["\\bconsole\\.log\\s*\\("]
paths = ["**/*.js", "**/*.ts", "**/*.jsx", "**/*.tsx", "**/*.mjs", "**/*.cjs"]
exclude_paths = ["**/tests/**", "**/*.test.*", "**/*.spec.*", "**/node_modules/**"]
ignore_comments = true
ignore_strings = true

[[rule]]
id = "js.no_console_debug"
severity = "warn"
message = "Remove console.debug() before merging."
languages = ["javascript", "typescript"]
patterns = ["\\bconsole\\.(debug|info|trace)\\s*\\("]
paths = ["**/*.js", "**/*.ts", "**/*.jsx", "**/*.tsx", "**/*.mjs", "**/*.cjs"]
exclude_paths = ["**/tests/**", "**/*.test.*", "**/*.spec.*", "**/node_modules/**"]
ignore_comments = true
ignore_strings = true

[[rule]]
id = "js.no_console_error"
severity = "info"
message = "Consider using a proper error logging service instead of console.error()."
languages = ["javascript", "typescript"]
patterns = ["\\bconsole\\.(error|warn)\\s*\\("]
paths = ["**/*.js", "**/*.ts", "**/*.jsx", "**/*.tsx", "**/*.mjs", "**/*.cjs"]
exclude_paths = ["**/tests/**", "**/*.test.*", "**/*.spec.*", "**/node_modules/**"]
ignore_comments = true
ignore_strings = true

[[rule]]
id = "js.no_debugger"
severity = "error"
message = "Remove debugger statement before merging."
languages = ["javascript", "typescript"]
patterns = ["\\bdebugger\\s*;?"]
paths = ["**/*.js", "**/*.ts", "**/*.jsx", "**/*.tsx", "**/*.mjs", "**/*.cjs"]
exclude_paths = ["**/node_modules/**"]
ignore_comments = true
ignore_strings = true

[[rule]]
id = "js.no_alert"
severity = "error"
message = "Remove alert()/confirm()/prompt() before merging."
languages = ["javascript", "typescript"]
patterns = ["\\b(alert|confirm|prompt)\\s*\\("]
paths = ["**/*.js", "**/*.ts", "**/*.jsx", "**/*.tsx", "**/*.mjs", "**/*.cjs"]
exclude_paths = ["**/tests/**", "**/*.test.*", "**/*.spec.*", "**/node_modules/**"]
ignore_comments = true
ignore_strings = true

[[rule]]
id = "js.no_todo"
severity = "warn"
message = "Resolve TODO/FIXME comments before merging."
languages = ["javascript", "typescript"]
patterns = ["\\bTODO\\b", "\\bFIXME\\b", "\\bHACK\\b"]
paths = ["**/*.js", "**/*.ts", "**/*.jsx", "**/*.tsx", "**/*.mjs", "**/*.cjs"]
exclude_paths = ["**/node_modules/**"]
ignore_comments = false
ignore_strings = true
"#
    .to_string()
}

fn generate_python_debug() -> String {
    r#"# diffguard.toml - Python Debug preset
# Generated by: diffguard init --preset python-debug
#
# Detects debugging statements in Python code.

[defaults]
base = "origin/main"
scope = "added"
fail_on = "error"
max_findings = 200
diff_context = 0

[[rule]]
id = "python.no_print"
severity = "warn"
message = "Remove print() before merging - use proper logging."
languages = ["python"]
patterns = ["\\bprint\\s*\\("]
paths = ["**/*.py"]
exclude_paths = ["**/tests/**", "**/test_*.py", "**/*_test.py", "**/conftest.py"]
ignore_comments = true
ignore_strings = true

[[rule]]
id = "python.no_pdb"
severity = "error"
message = "Remove pdb import/usage before merging."
languages = ["python"]
patterns = ["\\bimport\\s+pdb\\b", "\\bfrom\\s+pdb\\s+import\\b", "\\bpdb\\.set_trace\\s*\\("]
paths = ["**/*.py"]
exclude_paths = []
ignore_comments = true
ignore_strings = true

[[rule]]
id = "python.no_breakpoint"
severity = "error"
message = "Remove breakpoint() before merging."
languages = ["python"]
patterns = ["\\bbreakpoint\\s*\\("]
paths = ["**/*.py"]
exclude_paths = []
ignore_comments = true
ignore_strings = true

[[rule]]
id = "python.no_ipdb"
severity = "error"
message = "Remove ipdb import/usage before merging."
languages = ["python"]
patterns = ["\\bimport\\s+ipdb\\b", "\\bfrom\\s+ipdb\\s+import\\b", "\\bipdb\\.set_trace\\s*\\("]
paths = ["**/*.py"]
exclude_paths = []
ignore_comments = true
ignore_strings = true

[[rule]]
id = "python.no_pudb"
severity = "error"
message = "Remove pudb import/usage before merging."
languages = ["python"]
patterns = ["\\bimport\\s+pudb\\b", "\\bfrom\\s+pudb\\s+import\\b"]
paths = ["**/*.py"]
exclude_paths = []
ignore_comments = true
ignore_strings = true

[[rule]]
id = "python.no_ic"
severity = "warn"
message = "Remove icecream (ic) debugging before merging."
languages = ["python"]
patterns = ["\\bfrom\\s+icecream\\s+import\\b", "\\bic\\s*\\("]
paths = ["**/*.py"]
exclude_paths = ["**/tests/**", "**/test_*.py", "**/*_test.py"]
ignore_comments = true
ignore_strings = true

[[rule]]
id = "python.no_todo"
severity = "warn"
message = "Resolve TODO/FIXME comments before merging."
languages = ["python"]
patterns = ["\\bTODO\\b", "\\bFIXME\\b", "\\bHACK\\b"]
paths = ["**/*.py"]
exclude_paths = []
ignore_comments = false
ignore_strings = true
"#
    .to_string()
}

#[cfg(test)]
mod tests {
    use super::*;
    use diffguard_types::ConfigFile;

    #[test]
    fn test_minimal_preset_generates_valid_toml() {
        let content = Preset::Minimal.generate();
        // Should parse without error (comments are valid TOML)
        let result: Result<ConfigFile, _> = toml::from_str(&content);
        let err = result.as_ref().err();
        assert!(result.is_ok(), "Failed to parse minimal preset: {:?}", err);
    }

    #[test]
    fn test_rust_quality_preset_generates_valid_toml() {
        let content = Preset::RustQuality.generate();
        let result: Result<ConfigFile, _> = toml::from_str(&content);
        let err = result.as_ref().err();
        assert!(
            result.is_ok(),
            "Failed to parse rust-quality preset: {:?}",
            err
        );

        let config = result.unwrap();
        assert!(
            !config.rule.is_empty(),
            "rust-quality preset should have rules"
        );
        assert!(config.rule.iter().any(|r| r.id == "rust.no_unwrap"));
        assert!(config.rule.iter().any(|r| r.id == "rust.no_dbg"));
    }

    #[test]
    fn test_secrets_preset_generates_valid_toml() {
        let content = Preset::Secrets.generate();
        let result: Result<ConfigFile, _> = toml::from_str(&content);
        let err = result.as_ref().err();
        assert!(result.is_ok(), "Failed to parse secrets preset: {:?}", err);

        let config = result.unwrap();
        assert!(!config.rule.is_empty(), "secrets preset should have rules");
        assert!(config.rule.iter().any(|r| r.id == "secrets.api_key"));
    }

    #[test]
    fn test_js_console_preset_generates_valid_toml() {
        let content = Preset::JsConsole.generate();
        let result: Result<ConfigFile, _> = toml::from_str(&content);
        let err = result.as_ref().err();
        assert!(
            result.is_ok(),
            "Failed to parse js-console preset: {:?}",
            err
        );

        let config = result.unwrap();
        assert!(
            !config.rule.is_empty(),
            "js-console preset should have rules"
        );
        assert!(config.rule.iter().any(|r| r.id == "js.no_console_log"));
        assert!(config.rule.iter().any(|r| r.id == "js.no_debugger"));
    }

    #[test]
    fn test_python_debug_preset_generates_valid_toml() {
        let content = Preset::PythonDebug.generate();
        let result: Result<ConfigFile, _> = toml::from_str(&content);
        let err = result.as_ref().err();
        assert!(
            result.is_ok(),
            "Failed to parse python-debug preset: {:?}",
            err
        );

        let config = result.unwrap();
        assert!(
            !config.rule.is_empty(),
            "python-debug preset should have rules"
        );
        assert!(config.rule.iter().any(|r| r.id == "python.no_print"));
        assert!(config.rule.iter().any(|r| r.id == "python.no_pdb"));
    }

    #[test]
    fn test_all_presets_have_defaults() {
        for preset in [
            Preset::Minimal,
            Preset::RustQuality,
            Preset::Secrets,
            Preset::JsConsole,
            Preset::PythonDebug,
        ] {
            let content = preset.generate();
            let config: ConfigFile =
                toml::from_str(&content).expect("Preset should parse as valid TOML");

            // All presets should have reasonable defaults
            let msg = format!("{:?} preset should have some defaults configured", preset);
            assert!(
                config.defaults.base.is_some() || config.defaults.scope.is_some(),
                "{msg}"
            );
        }
    }

    #[test]
    fn test_preset_names() {
        assert_eq!(Preset::Minimal.name(), "minimal");
        assert_eq!(Preset::RustQuality.name(), "rust-quality");
        assert_eq!(Preset::Secrets.name(), "secrets");
        assert_eq!(Preset::JsConsole.name(), "js-console");
        assert_eq!(Preset::PythonDebug.name(), "python-debug");
    }

    #[test]
    fn test_preset_descriptions() {
        // Just verify descriptions are not empty
        for preset in [
            Preset::Minimal,
            Preset::RustQuality,
            Preset::Secrets,
            Preset::JsConsole,
            Preset::PythonDebug,
        ] {
            assert!(
                !preset.description().is_empty(),
                "{:?} should have a description",
                preset
            );
        }
    }
}