destructive_command_guard 0.4.3

A Claude Code hook that blocks destructive commands before they execute
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
//! E2E Test Logging Utilities
//!
//! Provides structured logging for E2E tests with detailed output for debugging
//! test failures and generating test reports.

#![allow(dead_code, clippy::format_push_string)]

use std::collections::HashMap;
use std::fs::OpenOptions;
use std::io::Write;
use std::path::PathBuf;
use std::sync::Once;
use std::time::{Duration, Instant};

use tracing_subscriber::{EnvFilter, layer::SubscriberExt, util::SubscriberInitExt};

/// Global initialization guard for logging.
static INIT: Once = Once::new();

/// Initialize E2E test logging.
///
/// This should be called once per test session. Multiple calls are safe
/// (subsequent calls are no-ops).
///
/// # Environment
///
/// Set `RUST_LOG=dcg=debug` to see detailed DCG logs in test output.
pub fn init_e2e_logging() {
    INIT.call_once(|| {
        let filter = EnvFilter::try_from_default_env()
            .unwrap_or_else(|_| EnvFilter::new("dcg=info,e2e=debug"));

        tracing_subscriber::registry()
            .with(
                tracing_subscriber::fmt::layer()
                    .with_test_writer()
                    .with_ansi(true)
                    .with_level(true)
                    .with_target(true)
                    .with_file(false)
                    .with_line_number(false)
                    .compact(),
            )
            .with(filter)
            .init();
    });
}

/// A step in a test execution.
#[derive(Debug, Clone)]
pub struct TestStep {
    /// Step name.
    pub name: String,
    /// Step details/description.
    pub details: String,
    /// Time taken for this step.
    pub duration: Duration,
    /// Whether the step passed.
    pub passed: bool,
    /// Optional error message if step failed.
    pub error: Option<String>,
}

/// A complete test report.
#[derive(Debug, Clone)]
pub struct TestReport {
    /// Name of the test.
    pub test_name: String,
    /// Overall result.
    pub passed: bool,
    /// Total duration.
    pub duration: Duration,
    /// Individual steps.
    pub steps: Vec<TestStep>,
    /// Metadata (key-value pairs).
    pub metadata: HashMap<String, String>,
    /// Error message if test failed.
    pub error: Option<String>,
}

impl TestReport {
    /// Generate a markdown report.
    #[must_use]
    pub fn to_markdown(&self) -> String {
        let mut md = String::new();

        // Header
        let status = if self.passed { "PASS" } else { "FAIL" };
        md.push_str(&format!(
            "# Test Report: {} [{}]\n\n",
            self.test_name, status
        ));

        // Summary
        md.push_str("## Summary\n\n");
        md.push_str(&format!("- **Duration**: {:?}\n", self.duration));
        md.push_str(&format!("- **Steps**: {}\n", self.steps.len()));
        md.push_str(&format!(
            "- **Passed Steps**: {}\n",
            self.steps.iter().filter(|s| s.passed).count()
        ));

        // Error if present
        if let Some(error) = &self.error {
            md.push_str(&format!("\n**Error**: {}\n", error));
        }

        // Metadata
        if !self.metadata.is_empty() {
            md.push_str("\n## Metadata\n\n");
            for (key, value) in &self.metadata {
                md.push_str(&format!("- **{}**: {}\n", key, value));
            }
        }

        // Steps
        md.push_str("\n## Steps\n\n");
        for (i, step) in self.steps.iter().enumerate() {
            let step_status = if step.passed { "[PASS]" } else { "[FAIL]" };
            md.push_str(&format!(
                "{}. **{}** {} ({:?})\n",
                i + 1,
                step.name,
                step_status,
                step.duration
            ));
            if !step.details.is_empty() {
                md.push_str(&format!("   - {}\n", step.details));
            }
            if let Some(error) = &step.error {
                md.push_str(&format!("   - **Error**: {}\n", error));
            }
        }

        md
    }

    /// Generate a JSON report.
    #[must_use]
    pub fn to_json(&self) -> String {
        let steps: Vec<serde_json::Value> = self
            .steps
            .iter()
            .map(|s| {
                serde_json::json!({
                    "name": s.name,
                    "details": s.details,
                    "duration_ms": s.duration.as_millis(),
                    "passed": s.passed,
                    "error": s.error,
                })
            })
            .collect();

        let report = serde_json::json!({
            "test_name": self.test_name,
            "passed": self.passed,
            "duration_ms": self.duration.as_millis(),
            "steps": steps,
            "metadata": self.metadata,
            "error": self.error,
        });

        serde_json::to_string_pretty(&report).unwrap_or_default()
    }
}

/// Logger for E2E tests with detailed output.
pub struct TestLogger {
    test_name: String,
    log_path: Option<PathBuf>,
    start_time: Instant,
    steps: Vec<TestStep>,
    metadata: HashMap<String, String>,
    verbose: bool,
    current_step_start: Option<Instant>,
    current_step_name: Option<String>,
}

impl TestLogger {
    /// Create a new test logger.
    #[must_use]
    pub fn new(test_name: &str) -> Self {
        Self {
            test_name: test_name.to_string(),
            log_path: None,
            start_time: Instant::now(),
            steps: Vec::new(),
            metadata: HashMap::new(),
            verbose: std::env::var("E2E_VERBOSE").is_ok(),
            current_step_start: None,
            current_step_name: None,
        }
    }

    /// Create a logger that writes to a file.
    #[must_use]
    pub fn with_log_file(mut self, path: PathBuf) -> Self {
        self.log_path = Some(path);
        self
    }

    /// Enable verbose output.
    #[must_use]
    pub fn verbose(mut self) -> Self {
        self.verbose = true;
        self
    }

    /// Add metadata to the test.
    pub fn add_metadata(&mut self, key: &str, value: &str) {
        self.metadata.insert(key.to_string(), value.to_string());
    }

    /// Log the start of a test.
    pub fn log_test_start(&self, description: &str) {
        if self.verbose {
            tracing::info!(target: "e2e", test = %self.test_name, "Starting test: {}", description);
        }

        self.write_to_file(&format!(
            "[{}] TEST START: {}\n  Description: {}\n",
            chrono::Utc::now().format("%Y-%m-%d %H:%M:%S"),
            self.test_name,
            description
        ));
    }

    /// Log a test step.
    pub fn log_step(&self, step: &str, details: &str) {
        if self.verbose {
            tracing::debug!(target: "e2e", test = %self.test_name, step = %step, "Step: {}", details);
        }

        self.write_to_file(&format!("  [STEP] {}: {}\n", step, details));
    }

    /// Start timing a step.
    pub fn start_step(&mut self, name: &str) {
        self.current_step_start = Some(Instant::now());
        self.current_step_name = Some(name.to_string());

        if self.verbose {
            tracing::debug!(target: "e2e", test = %self.test_name, "Starting step: {}", name);
        }
    }

    /// End the current step with success.
    pub fn end_step_pass(&mut self, details: &str) {
        if let (Some(start), Some(name)) = (
            self.current_step_start.take(),
            self.current_step_name.take(),
        ) {
            let duration = start.elapsed();
            self.steps.push(TestStep {
                name: name.clone(),
                details: details.to_string(),
                duration,
                passed: true,
                error: None,
            });

            if self.verbose {
                tracing::debug!(target: "e2e", test = %self.test_name, step = %name, "Step passed: {} ({:?})", details, duration);
            }

            self.write_to_file(&format!(
                "  [PASS] {} ({:?}): {}\n",
                name, duration, details
            ));
        }
    }

    /// End the current step with failure.
    pub fn end_step_fail(&mut self, details: &str, error: &str) {
        if let (Some(start), Some(name)) = (
            self.current_step_start.take(),
            self.current_step_name.take(),
        ) {
            let duration = start.elapsed();
            self.steps.push(TestStep {
                name: name.clone(),
                details: details.to_string(),
                duration,
                passed: false,
                error: Some(error.to_string()),
            });

            if self.verbose {
                tracing::warn!(target: "e2e", test = %self.test_name, step = %name, "Step failed: {} - {}", details, error);
            }

            self.write_to_file(&format!(
                "  [FAIL] {} ({:?}): {} - Error: {}\n",
                name, duration, details, error
            ));
        }
    }

    /// Log a command being executed.
    pub fn log_command(&self, cmd: &str, args: &[&str]) {
        let full_cmd = if args.is_empty() {
            cmd.to_string()
        } else {
            format!("{} {}", cmd, args.join(" "))
        };

        if self.verbose {
            tracing::debug!(target: "e2e", test = %self.test_name, "Command: {}", full_cmd);
        }

        self.write_to_file(&format!("  [CMD] {}\n", full_cmd));
    }

    /// Log command output.
    pub fn log_output(&self, stdout: &str, stderr: &str, exit_code: i32) {
        if self.verbose {
            tracing::debug!(target: "e2e", test = %self.test_name, exit_code = exit_code, "Output received");
        }

        let mut output = format!("  [OUTPUT] exit_code={}\n", exit_code);
        if !stdout.is_empty() {
            output.push_str(&format!("    stdout: {}\n", truncate_output(stdout, 500)));
        }
        if !stderr.is_empty() {
            output.push_str(&format!("    stderr: {}\n", truncate_output(stderr, 500)));
        }

        self.write_to_file(&output);
    }

    /// Log an assertion.
    pub fn log_assertion(&self, assertion: &str, passed: bool) {
        let status = if passed { "PASS" } else { "FAIL" };

        if self.verbose {
            if passed {
                tracing::debug!(target: "e2e", test = %self.test_name, "Assertion passed: {}", assertion);
            } else {
                tracing::warn!(target: "e2e", test = %self.test_name, "Assertion failed: {}", assertion);
            }
        }

        self.write_to_file(&format!("  [ASSERT:{}] {}\n", status, assertion));
    }

    /// Log the end of a test.
    pub fn log_test_end(&self, passed: bool, error: Option<&str>) {
        let status = if passed { "PASS" } else { "FAIL" };
        let duration = self.start_time.elapsed();

        if self.verbose {
            if passed {
                tracing::info!(target: "e2e", test = %self.test_name, "Test passed ({:?})", duration);
            } else {
                tracing::error!(target: "e2e", test = %self.test_name, "Test failed ({:?}): {:?}", duration, error);
            }
        }

        let mut output = format!(
            "[{}] TEST END: {} [{}] ({:?})\n",
            chrono::Utc::now().format("%Y-%m-%d %H:%M:%S"),
            self.test_name,
            status,
            duration
        );

        if let Some(err) = error {
            output.push_str(&format!("  Error: {}\n", err));
        }

        self.write_to_file(&output);
    }

    /// Generate a test report.
    #[must_use]
    pub fn generate_report(&self, passed: bool, error: Option<String>) -> TestReport {
        TestReport {
            test_name: self.test_name.clone(),
            passed,
            duration: self.start_time.elapsed(),
            steps: self.steps.clone(),
            metadata: self.metadata.clone(),
            error,
        }
    }

    /// Write to the log file if configured.
    fn write_to_file(&self, content: &str) {
        if let Some(path) = &self.log_path {
            if let Ok(mut file) = OpenOptions::new().create(true).append(true).open(path) {
                let _ = file.write_all(content.as_bytes());
            }
        }
    }
}

/// Truncate output for display.
fn truncate_output(s: &str, max_len: usize) -> String {
    if s.len() <= max_len {
        s.to_string()
    } else {
        format!("{}...[truncated]", &s[..max_len])
    }
}

/// Macro for logging test progress.
#[macro_export]
macro_rules! e2e_log {
    ($($arg:tt)*) => {
        tracing::info!(target: "e2e", $($arg)*)
    };
}

/// Macro for logging test debug info.
#[macro_export]
macro_rules! e2e_debug {
    ($($arg:tt)*) => {
        tracing::debug!(target: "e2e", $($arg)*)
    };
}

/// Macro for logging test warnings.
#[macro_export]
macro_rules! e2e_warn {
    ($($arg:tt)*) => {
        tracing::warn!(target: "e2e", $($arg)*)
    };
}

/// Macro for logging test errors.
#[macro_export]
macro_rules! e2e_error {
    ($($arg:tt)*) => {
        tracing::error!(target: "e2e", $($arg)*)
    };
}

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

    #[test]
    fn test_logger_creation() {
        let logger = TestLogger::new("test_logger");
        assert_eq!(logger.test_name, "test_logger");
    }

    #[test]
    fn test_logger_step_tracking() {
        let mut logger = TestLogger::new("step_tracking");
        logger.start_step("step1");
        std::thread::sleep(Duration::from_millis(10));
        logger.end_step_pass("Step 1 completed");

        logger.start_step("step2");
        logger.end_step_fail("Step 2 failed", "Some error");

        assert_eq!(logger.steps.len(), 2);
        assert!(logger.steps[0].passed);
        assert!(!logger.steps[1].passed);
    }

    #[test]
    fn test_report_generation() {
        let mut logger = TestLogger::new("report_test");
        logger.add_metadata("config", "minimal");
        logger.start_step("setup");
        logger.end_step_pass("Setup complete");

        let report = logger.generate_report(true, None);

        assert_eq!(report.test_name, "report_test");
        assert!(report.passed);
        assert_eq!(report.steps.len(), 1);
        assert_eq!(report.metadata.get("config"), Some(&"minimal".to_string()));
    }

    #[test]
    fn test_report_markdown() {
        let report = TestReport {
            test_name: "markdown_test".to_string(),
            passed: true,
            duration: Duration::from_millis(100),
            steps: vec![TestStep {
                name: "step1".to_string(),
                details: "Test step".to_string(),
                duration: Duration::from_millis(50),
                passed: true,
                error: None,
            }],
            metadata: HashMap::new(),
            error: None,
        };

        let md = report.to_markdown();
        assert!(md.contains("# Test Report: markdown_test"));
        assert!(md.contains("[PASS]"));
    }

    #[test]
    fn test_report_json() {
        let report = TestReport {
            test_name: "json_test".to_string(),
            passed: false,
            duration: Duration::from_millis(100),
            steps: vec![],
            metadata: HashMap::new(),
            error: Some("Test error".to_string()),
        };

        let json = report.to_json();
        assert!(json.contains("\"test_name\": \"json_test\""));
        assert!(json.contains("\"passed\": false"));
        assert!(json.contains("\"error\": \"Test error\""));
    }

    #[test]
    fn test_truncate_output() {
        let short = "short";
        let long = "a".repeat(1000);

        assert_eq!(truncate_output(short, 100), "short");
        let truncated = truncate_output(&long, 100);
        assert!(truncated.ends_with("...[truncated]"));
        assert!(truncated.len() < long.len());
    }
}