log-watcher 0.2.1

Real-time log file monitoring with pattern highlighting and desktop notifications
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
use crate::config::Config;
use crate::matcher::MatchResult;
use anyhow::Result;
use std::io::Write;
use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor};

#[derive(Debug)]
pub struct Highlighter {
    config: Config,
    stdout: StandardStream,
    stderr: StandardStream,
}

impl Highlighter {
    pub fn new(config: Config) -> Self {
        let color_choice = if config.no_color {
            ColorChoice::Never
        } else {
            ColorChoice::Auto
        };

        Self {
            config,
            stdout: StandardStream::stdout(color_choice),
            stderr: StandardStream::stderr(color_choice),
        }
    }

    pub fn print_line(
        &mut self,
        line: &str,
        filename: Option<&str>,
        match_result: &MatchResult,
        dry_run: bool,
    ) -> Result<()> {
        // Skip non-matching lines in quiet mode
        if self.config.quiet && !match_result.matched {
            return Ok(());
        }

        let mut output_line = String::new();

        // Add dry-run prefix if needed
        if dry_run && match_result.matched {
            output_line.push_str("[DRY-RUN] ");
        }

        // Add filename prefix if needed
        if self.config.prefix_files {
            if let Some(filename) = filename {
                output_line.push_str(&format!("[{}] ", filename));
            }
        }

        // Add the actual line content
        output_line.push_str(line);

        // Print with or without color
        if let Some(color) = match_result.color {
            self.print_colored(&output_line, color)?;
        } else {
            self.print_plain(&output_line)?;
        }

        Ok(())
    }

    fn print_colored(&mut self, text: &str, color: Color) -> Result<()> {
        self.stdout
            .set_color(ColorSpec::new().set_fg(Some(color)))?;
        writeln!(self.stdout, "{}", text)?;
        self.stdout.reset()?;
        self.stdout.flush()?;
        Ok(())
    }

    fn print_plain(&mut self, text: &str) -> Result<()> {
        writeln!(self.stdout, "{}", text)?;
        self.stdout.flush()?;
        Ok(())
    }

    pub fn print_error(&mut self, message: &str) -> Result<()> {
        self.stderr
            .set_color(ColorSpec::new().set_fg(Some(Color::Red)))?;
        writeln!(self.stderr, "Error: {}", message)?;
        self.stderr.reset()?;
        self.stderr.flush()?;
        Ok(())
    }

    pub fn print_warning(&mut self, message: &str) -> Result<()> {
        self.stderr
            .set_color(ColorSpec::new().set_fg(Some(Color::Yellow)))?;
        writeln!(self.stderr, "Warning: {}", message)?;
        self.stderr.reset()?;
        self.stderr.flush()?;
        Ok(())
    }

    pub fn print_info(&mut self, message: &str) -> Result<()> {
        self.stderr
            .set_color(ColorSpec::new().set_fg(Some(Color::Cyan)))?;
        writeln!(self.stderr, "Info: {}", message)?;
        self.stderr.reset()?;
        self.stderr.flush()?;
        Ok(())
    }

    pub fn print_dry_run_summary(&mut self, matches: &[(String, usize)]) -> Result<()> {
        if matches.is_empty() {
            self.print_info("No matching lines found")?;
            return Ok(());
        }

        self.print_info("Dry-run summary:")?;
        for (pattern, count) in matches {
            self.print_plain(&format!("  {}: {} matches", pattern, count))?;
        }
        self.print_info("Dry-run complete. No notifications sent.")?;
        Ok(())
    }

    pub fn print_startup_info(&mut self) -> Result<()> {
        self.print_info(&format!("Watching {} file(s)", self.config.files.len()))?;

        if !self.config.patterns.is_empty() {
            self.print_info(&format!("Patterns: {}", self.config.patterns.join(", ")))?;
        }

        if self.config.notify_enabled {
            self.print_info("Desktop notifications enabled")?;
        }

        if self.config.dry_run {
            self.print_info("Dry-run mode: reading existing content only")?;
        }

        Ok(())
    }

    pub fn print_file_rotation(&mut self, filename: &str) -> Result<()> {
        self.print_warning(&format!("File rotation detected for {}", filename))?;
        Ok(())
    }

    pub fn print_file_reopened(&mut self, filename: &str) -> Result<()> {
        self.print_info(&format!("Reopened file: {}", filename))?;
        Ok(())
    }

    pub fn print_file_error(&mut self, filename: &str, error: &str) -> Result<()> {
        self.print_error(&format!("Error watching {}: {}", filename, error))?;
        Ok(())
    }

    pub fn print_shutdown_summary(&mut self, stats: &WatcherStats) -> Result<()> {
        self.print_info("Shutdown summary:")?;
        self.print_plain(&format!("  Files watched: {}", stats.files_watched))?;
        self.print_plain(&format!("  Lines processed: {}", stats.lines_processed))?;
        if stats.lines_excluded > 0 {
            self.print_plain(&format!("  Lines excluded: {}", stats.lines_excluded))?;
        }
        self.print_plain(&format!("  Matches found: {}", stats.matches_found))?;
        self.print_plain(&format!(
            "  Notifications sent: {}",
            stats.notifications_sent
        ))?;
        Ok(())
    }
}

#[derive(Debug, Default)]
pub struct WatcherStats {
    pub files_watched: usize,
    pub lines_processed: usize,
    pub lines_excluded: usize,
    pub matches_found: usize,
    pub notifications_sent: usize,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::Args;
    use std::path::PathBuf;

    fn create_test_config() -> Config {
        let args = Args {
            files: vec![PathBuf::from("test.log")],
            completions: None,
            patterns: "ERROR".to_string(),
            regex: false,
            case_insensitive: false,
            color_map: None,
            notify: true,
            notify_patterns: None,
            notify_throttle: 5,
            dry_run: false,
            quiet: false,
            exclude: None,
            no_color: true, // Disable colors for testing
            prefix_file: None,
            poll_interval: 100,
            buffer_size: 8192,
        };
        Config::from_args(&args).unwrap()
    }

    #[test]
    fn test_print_line_without_match() {
        let config = create_test_config();
        let mut highlighter = Highlighter::new(config);

        let match_result = MatchResult {
            matched: false,
            pattern: None,
            color: None,
            should_notify: false,
        };

        // This should not panic
        highlighter
            .print_line("Normal line", None, &match_result, false)
            .unwrap();
    }

    #[test]
    fn test_print_line_with_match() {
        let config = create_test_config();
        let mut highlighter = Highlighter::new(config);

        let match_result = MatchResult {
            matched: true,
            pattern: Some("ERROR".to_string()),
            color: Some(Color::Red),
            should_notify: true,
        };

        // This should not panic
        highlighter
            .print_line("ERROR: Something went wrong", None, &match_result, false)
            .unwrap();
    }

    #[test]
    fn test_dry_run_prefix() {
        let config = create_test_config();
        let mut highlighter = Highlighter::new(config);

        let match_result = MatchResult {
            matched: true,
            pattern: Some("ERROR".to_string()),
            color: Some(Color::Red),
            should_notify: true,
        };

        // This should not panic
        highlighter
            .print_line("ERROR: Something went wrong", None, &match_result, true)
            .unwrap();
    }

    #[test]
    fn test_print_file_error() {
        let config = create_test_config();
        let mut highlighter = Highlighter::new(config);
        let result = highlighter.print_file_error("test.log", "Permission denied");
        assert!(result.is_ok());
    }

    #[test]
    fn test_print_shutdown_summary() {
        let config = create_test_config();
        let mut highlighter = Highlighter::new(config);
        let stats = WatcherStats {
            files_watched: 2,
            lines_processed: 100,
            lines_excluded: 10,
            matches_found: 5,
            notifications_sent: 3,
        };
        let result = highlighter.print_shutdown_summary(&stats);
        assert!(result.is_ok());
    }

    #[test]
    fn test_print_file_rotation() {
        let config = create_test_config();
        let mut highlighter = Highlighter::new(config);
        let result = highlighter.print_file_rotation("test.log");
        assert!(result.is_ok());
    }

    #[test]
    fn test_print_file_reopened() {
        let config = create_test_config();
        let mut highlighter = Highlighter::new(config);
        let result = highlighter.print_file_reopened("test.log");
        assert!(result.is_ok());
    }

    #[test]
    fn test_print_startup_info() {
        let config = create_test_config();
        let mut highlighter = Highlighter::new(config);
        let result = highlighter.print_startup_info();
        assert!(result.is_ok());
    }

    #[test]
    fn test_print_colored_with_custom_color() {
        let config = create_test_config();
        let mut highlighter = Highlighter::new(config);
        let result = highlighter.print_colored("Custom message", Color::Magenta);
        assert!(result.is_ok());
    }

    #[test]
    fn test_print_plain() {
        let config = create_test_config();
        let mut highlighter = Highlighter::new(config);
        let result = highlighter.print_plain("Plain message");
        assert!(result.is_ok());
    }

    #[test]
    fn test_color_choice_never() {
        let args = Args {
            files: vec![PathBuf::from("test.log")],
            completions: None,
            patterns: "ERROR".to_string(),
            regex: false,
            case_insensitive: false,
            color_map: None,
            notify: false,
            notify_patterns: None,
            quiet: false,
            dry_run: false,
            exclude: None,
            prefix_file: Some(false),
            poll_interval: 1000,
            buffer_size: 8192,
            no_color: true, // Force no color
            notify_throttle: 0,
        };

        let config = Config::from_args(&args).unwrap();
        let highlighter = Highlighter::new(config);

        // Test that highlighter is created successfully with no_color = true
        assert!(highlighter.config.no_color);
    }

    #[test]
    fn test_quiet_mode_skip_non_matching() {
        let args = Args {
            files: vec![PathBuf::from("test.log")],
            completions: None,
            patterns: "ERROR".to_string(),
            regex: false,
            case_insensitive: false,
            color_map: None,
            notify: false,
            notify_patterns: None,
            quiet: true, // Enable quiet mode
            dry_run: false,
            exclude: None,
            prefix_file: Some(false),
            poll_interval: 1000,
            buffer_size: 8192,
            no_color: false,
            notify_throttle: 0,
        };

        let config = Config::from_args(&args).unwrap();
        let mut highlighter = Highlighter::new(config);

        // Test that non-matching lines are skipped in quiet mode
        let match_result = MatchResult {
            matched: false,
            pattern: None,
            color: None,
            should_notify: false,
        };

        let result = highlighter.print_line("Normal line", None, &match_result, false);
        assert!(result.is_ok());
    }

    #[test]
    fn test_print_dry_run_summary_empty() {
        let config = create_test_config();
        let mut highlighter = Highlighter::new(config);

        // Test empty matches (covers line 112-113)
        let matches = vec![];
        let result = highlighter.print_dry_run_summary(&matches);
        assert!(result.is_ok());
    }

    #[test]
    fn test_print_dry_run_summary_with_matches() {
        let config = create_test_config();
        let mut highlighter = Highlighter::new(config);

        // Test with matches (covers line 116)
        let matches = vec![("ERROR".to_string(), 5), ("WARN".to_string(), 3)];
        let result = highlighter.print_dry_run_summary(&matches);
        assert!(result.is_ok());
    }

    #[test]
    fn test_print_dry_run_summary_coverage_line_116() {
        let config = create_test_config();
        let mut highlighter = Highlighter::new(config);

        // Test print_dry_run_summary to cover line 116 (self.print_info("Dry-run summary:"))
        let matches = vec![("ERROR".to_string(), 2)];
        let result = highlighter.print_dry_run_summary(&matches);
        assert!(result.is_ok());
    }
}