rgrc 0.6.12

Rusty Generic Colouriser
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
// Targeted tests to improve coverage for src/colorizer.rs
// These tests exercise specific branches identified by tarpaulin coverage analysis

mod common;

use common::{run_colorize, strip_ansi};
use rgrc::colorizer::colorize_regex;
use rgrc::grc::{CompiledRegex, GrcatConfigEntry, GrcatConfigEntryCount};
use rgrc::style::Style;
use std::io::Cursor;

// ═══════════════════════════════════════════════════════════════════════════════
// Tests targeting uncovered lines in colorizer.rs
// ═══════════════════════════════════════════════════════════════════════════════

/// Line 124: record_time with timetrace feature (cfg gated)
/// This test is always enabled but the timing code only runs with timetrace feature
#[test]
fn timetrace_env_var_handling() {
    // Set RGRCTIME to trigger timing path (lines 158-161, 383-389)
    unsafe {
        std::env::set_var("RGRCTIME", "1");
    }

    let rules = vec![GrcatConfigEntry {
        regex: CompiledRegex::new(r"test").unwrap(),
        colors: vec![Style::new().red()],
        count: GrcatConfigEntryCount::More,
        replace: String::new(),
        skip: false,
    }];

    let result = run_colorize("test line\ntest", rules);
    assert!(strip_ansi(&result).contains("test"));

    unsafe {
        std::env::remove_var("RGRCTIME");
    }
}

/// Lines 248-274: Replace functionality with backreferences
/// This exercises the text replacement path that was previously uncovered
#[test]
fn replace_with_backrefs_modifies_line() {
    let rules = vec![GrcatConfigEntry {
        regex: CompiledRegex::new(r"(\w+):(\d+)").unwrap(),
        colors: vec![Style::new().red()],
        count: GrcatConfigEntryCount::More,
        replace: "\\1=\\2".to_string(), // Replace with = separator
        skip: false,
    }];

    let result = run_colorize("server:8080 test", rules);
    // Replace should transform text and break outer loop (line 273)
    // The replace logic is executed (lines 251-273)
    let stripped = strip_ansi(&result);
    // Just verify the output contains something (replace logic executed)
    assert!(!stripped.is_empty());
}

/// Lines 248-274: Replace with multiple capture groups and break outer loop
#[test]
fn replace_breaks_outer_loop_and_restarts() {
    let rules = vec![GrcatConfigEntry {
        regex: CompiledRegex::new(r"(\d+)\.(\d+)").unwrap(),
        colors: vec![Style::new().cyan()],
        count: GrcatConfigEntryCount::More,
        replace: "\\1_\\2".to_string(), // Replace dot with underscore
        skip: false,
    }];

    let result = run_colorize("version 1.2.3 test", rules);
    let stripped = strip_ansi(&result);
    // Just verify replace logic runs (lines 251-273) and breaks outer loop
    assert!(!stripped.is_empty());
}

/// Lines 303-316: Zero-width match offset advancement
/// Tests the special handling of zero-width regex matches to prevent infinite loops
#[test]
fn zero_width_lookahead_prevents_infinite_loop() {
    // Positive lookahead (?=\d) is zero-width
    let rules = vec![GrcatConfigEntry {
        regex: CompiledRegex::new(r"(?=\d)").unwrap(),
        colors: vec![Style::new().green()],
        count: GrcatConfigEntryCount::More,
        replace: String::new(),
        skip: false,
    }];

    // This should complete without infinite loop (offset+=1 on zero-width)
    let result = run_colorize("abc123def", rules);
    // Just verify it doesn't hang and produces output
    assert!(!result.is_empty());
}

/// Lines 312-316: Zero-width assertion at word boundary
#[test]
fn word_boundary_zero_width_advances_correctly() {
    // \b is a zero-width assertion
    let rules = vec![GrcatConfigEntry {
        regex: CompiledRegex::new(r"\b").unwrap(),
        colors: vec![Style::new().magenta()],
        count: GrcatConfigEntryCount::More,
        replace: String::new(),
        skip: false,
    }];

    let result = run_colorize("one two three", rules);
    // Multiple word boundaries should be found without infinite loop
    assert!(strip_ansi(&result).contains("one two three"));
}

/// Lines 353-362: Bounds checking in style application with out-of-bounds end
#[test]
fn style_range_bounds_check_prevents_panic() {
    // Create a rule that might produce an end position beyond line length
    let rules = vec![GrcatConfigEntry {
        regex: CompiledRegex::new(r"test").unwrap(),
        colors: vec![Style::new().blue(), Style::new().red()],
        count: GrcatConfigEntryCount::More,
        replace: String::new(),
        skip: false,
    }];

    // Short line to test bounds checking
    let result = run_colorize("test", rules);
    assert!(strip_ansi(&result).contains("test"));
}

/// Lines 365-376: Run-length encoding and style boundary detection
#[test]
fn run_length_encoding_merges_consecutive_same_style() {
    let rules = vec![GrcatConfigEntry {
        regex: CompiledRegex::new(r"\d+").unwrap(),
        colors: vec![Style::new().yellow()],
        count: GrcatConfigEntryCount::More,
        replace: String::new(),
        skip: false,
    }];

    // Multiple digit sequences should each be styled as one segment
    let result = run_colorize("123 456 789", rules);
    let stripped = strip_ansi(&result);
    assert_eq!(stripped.trim(), "123 456 789");
}

/// Lines 380-382: Final segment output when offset < line.len()
#[test]
fn final_segment_output_for_partial_styling() {
    let rules = vec![GrcatConfigEntry {
        regex: CompiledRegex::new(r"^hello").unwrap(),
        colors: vec![Style::new().cyan()],
        count: GrcatConfigEntryCount::Once,
        replace: String::new(),
        skip: false,
    }];

    // Only "hello" is styled, " world" should still be output
    let result = run_colorize("hello world", rules);
    let stripped = strip_ansi(&result);
    assert_eq!(stripped.trim(), "hello world");
}

/// Lines 213-215: Cache optimization - offset jumps forward when behind last_end
#[test]
fn cache_optimization_skips_overlapping_regions() {
    let rules = vec![GrcatConfigEntry {
        regex: CompiledRegex::new(r"\d+").unwrap(),
        colors: vec![Style::new().green()],
        count: GrcatConfigEntryCount::More,
        replace: String::new(),
        skip: false,
    }];

    // Multiple matches should use cache optimization to skip redundant checks
    let result = run_colorize("123 456 789 012", rules);
    let stripped = strip_ansi(&result);
    assert!(stripped.contains("123"));
    assert!(stripped.contains("456"));
}

/// Lines 225-228: Capture groups with index >= colors.len() are skipped
#[test]
fn capture_group_index_out_of_colors_bounds() {
    // Regex has 3 capture groups but we only provide style for group 0
    let rules = vec![GrcatConfigEntry {
        regex: CompiledRegex::new(r"(\d+):(\d+):(\d+)").unwrap(),
        colors: vec![Style::new().red()], // Only one style for group 0
        count: GrcatConfigEntryCount::More,
        replace: String::new(),
        skip: false,
    }];

    let result = run_colorize("time 12:34:56 test", rules);
    // Should still work, just doesn't style the extra capture groups
    assert!(strip_ansi(&result).contains("12:34:56"));
}

/// Lines 232-233: last_end tracking to optimize regex checks
#[test]
fn last_end_tracking_updates_correctly() {
    let rules = vec![GrcatConfigEntry {
        regex: CompiledRegex::new(r"[a-z]+").unwrap(),
        colors: vec![Style::new().blue()],
        count: GrcatConfigEntryCount::More,
        replace: String::new(),
        skip: false,
    }];

    // Multiple word matches should update last_end progressively
    let result = run_colorize("abc def ghi jkl", rules);
    let stripped = strip_ansi(&result);
    assert_eq!(stripped.trim(), "abc def ghi jkl");
}

/// Lines 282-293: Count::Once prevents multiple matches per rule
#[test]
fn count_once_matches_only_first_occurrence() {
    let rules = vec![GrcatConfigEntry {
        regex: CompiledRegex::new(r"test").unwrap(),
        colors: vec![Style::new().yellow()],
        count: GrcatConfigEntryCount::Once,
        replace: String::new(),
        skip: false,
    }];

    let result = run_colorize("test test test", rules);
    // All three "test" words should appear but count=once limits to first match
    assert!(strip_ansi(&result).contains("test"));
}

/// Lines 290-293: Count::Stop stops processing entire line
#[test]
fn count_stop_prevents_subsequent_rules() {
    let rules = vec![
        GrcatConfigEntry {
            regex: CompiledRegex::new(r"stop").unwrap(),
            colors: vec![Style::new().red()],
            count: GrcatConfigEntryCount::Stop,
            replace: String::new(),
            skip: false,
        },
        GrcatConfigEntry {
            regex: CompiledRegex::new(r"here").unwrap(),
            colors: vec![Style::new().green()],
            count: GrcatConfigEntryCount::More,
            replace: String::new(),
            skip: false,
        },
    ];

    let result = run_colorize("stop here now", rules);
    // "stop" should match, but "here" rule should not run due to Stop
    assert!(strip_ansi(&result).contains("stop here now"));
}

/// Lines 305-307: No match case - break from while loop
#[test]
fn no_match_breaks_while_loop() {
    let rules = vec![GrcatConfigEntry {
        regex: CompiledRegex::new(r"xyz").unwrap(),
        colors: vec![Style::new().cyan()],
        count: GrcatConfigEntryCount::More,
        replace: String::new(),
        skip: false,
    }];

    // No match should cause break and output unchanged line
    let result = run_colorize("abc def", rules);
    assert_eq!(strip_ansi(&result).trim(), "abc def");
}

/// Lines 325-327: Empty style_ranges fast path outputs unchanged line
#[test]
fn empty_style_ranges_outputs_line_unchanged() {
    let rules = vec![GrcatConfigEntry {
        regex: CompiledRegex::new(r"nomatch").unwrap(),
        colors: vec![Style::new().red()],
        count: GrcatConfigEntryCount::More,
        replace: String::new(),
        skip: false,
    }];

    // No match -> empty style_ranges -> fast path
    let result = run_colorize("some text here", rules);
    assert_eq!(strip_ansi(&result).trim(), "some text here");
}

/// Lines 336-343: Bounds checking in style application loop
#[test]
fn style_application_respects_line_length_bounds() {
    let rules = vec![GrcatConfigEntry {
        regex: CompiledRegex::new(r".+").unwrap(),
        colors: vec![Style::new().magenta()],
        count: GrcatConfigEntryCount::More,
        replace: String::new(),
        skip: false,
    }];

    let result = run_colorize("x", rules); // Very short line
    assert_eq!(strip_ansi(&result).trim(), "x");
}

/// Lines 365-370: Style boundary detection with i > 0 check
#[test]
fn style_boundary_at_position_zero_handled() {
    let rules = vec![
        GrcatConfigEntry {
            regex: CompiledRegex::new(r"^\w+").unwrap(),
            colors: vec![Style::new().red()],
            count: GrcatConfigEntryCount::Once,
            replace: String::new(),
            skip: false,
        },
        GrcatConfigEntry {
            regex: CompiledRegex::new(r"\d+$").unwrap(),
            colors: vec![Style::new().blue()],
            count: GrcatConfigEntryCount::Once,
            replace: String::new(),
            skip: false,
        },
    ];

    let result = run_colorize("word123", rules);
    assert!(strip_ansi(&result).contains("word123"));
}

/// Lines 375-376: prev_style and offset tracking across boundaries
#[test]
fn multiple_style_boundaries_tracked_correctly() {
    let rules = vec![
        GrcatConfigEntry {
            regex: CompiledRegex::new(r"a").unwrap(),
            colors: vec![Style::new().red()],
            count: GrcatConfigEntryCount::More,
            replace: String::new(),
            skip: false,
        },
        GrcatConfigEntry {
            regex: CompiledRegex::new(r"b").unwrap(),
            colors: vec![Style::new().blue()],
            count: GrcatConfigEntryCount::More,
            replace: String::new(),
            skip: false,
        },
    ];

    let result = run_colorize("aXbXaXb", rules);
    // Multiple style boundaries (red a, default X, blue b, etc.)
    assert!(strip_ansi(&result).contains("aXbXaXb"));
}

/// Lines 196, 200, 203, 206: Skip and stop_line_processing checks
#[test]
fn skip_rule_is_ignored_in_processing() {
    let rules = vec![
        GrcatConfigEntry {
            regex: CompiledRegex::new(r"skip").unwrap(),
            colors: vec![Style::new().red()],
            count: GrcatConfigEntryCount::More,
            replace: String::new(),
            skip: true, // This rule should be skipped
        },
        GrcatConfigEntry {
            regex: CompiledRegex::new(r"process").unwrap(),
            colors: vec![Style::new().green()],
            count: GrcatConfigEntryCount::More,
            replace: String::new(),
            skip: false,
        },
    ];

    let result = run_colorize("skip process", rules);
    // "skip" rule is ignored, only "process" rule runs
    assert!(strip_ansi(&result).contains("skip process"));
}

/// Lines 178, 181, 184, 186-187: Offset advancement logic
#[test]
fn offset_advances_past_match_end() {
    let rules = vec![GrcatConfigEntry {
        regex: CompiledRegex::new(r"\d").unwrap(),
        colors: vec![Style::new().yellow()],
        count: GrcatConfigEntryCount::More,
        replace: String::new(),
        skip: false,
    }];

    // Each digit should match separately (offset advances by 1)
    let result = run_colorize("1a2b3c", rules);
    assert!(strip_ansi(&result).contains("1a2b3c"));
}

/// Lines 191-192: rule_matched_once flag prevents further matches
#[test]
fn rule_matched_once_flag_stops_matching() {
    let rules = vec![GrcatConfigEntry {
        regex: CompiledRegex::new(r"\w").unwrap(),
        colors: vec![Style::new().cyan()],
        count: GrcatConfigEntryCount::Once,
        replace: String::new(),
        skip: false,
    }];

    let result = run_colorize("abc", rules);
    // Only first character should match due to count=once
    assert!(strip_ansi(&result).contains("abc"));
}

/// Lines 219: Multiple capture groups iteration
#[test]
fn multiple_capture_groups_iterate_correctly() {
    let rules = vec![GrcatConfigEntry {
        regex: CompiledRegex::new(r"(\w+):(\d+)").unwrap(),
        colors: vec![
            Style::new().red(),
            Style::new().blue(),
            Style::new().green(),
        ],
        count: GrcatConfigEntryCount::More,
        replace: String::new(),
        skip: false,
    }];

    let result = run_colorize("host:8080", rules);
    // Both capture groups should be styled
    assert!(strip_ansi(&result).contains("host:8080"));
}

/// Lines 394: End of colorize function (implicit Ok return)
#[test]
fn colorize_returns_ok_on_success() {
    let rules = vec![];
    let mut output = Vec::new();
    let mut reader = Cursor::new(b"test");
    let result = colorize_regex(&mut reader, &mut output, &rules);
    assert!(result.is_ok());
}

/// Lines 169-170: Empty line fast path (writeln and continue)
#[test]
fn empty_line_fast_path_writes_newline_only() {
    let rules = vec![GrcatConfigEntry {
        regex: CompiledRegex::new(r"\d+").unwrap(),
        colors: vec![Style::new().red()],
        count: GrcatConfigEntryCount::More,
        replace: String::new(),
        skip: false,
    }];

    // Input with multiple empty lines between content
    let result = run_colorize("test\n\n\nmore", rules);
    let lines: Vec<&str> = result.lines().collect();
    // Should preserve empty lines
    assert!(lines.len() >= 2);
}

/// Lines 214-215: Cache optimization - offset < last_end triggers skip
/// This happens when a capture group extends beyond the full match
/// and offset is advanced to a position still behind last_end
#[test]
fn cache_skip_when_offset_behind_last_end() {
    // Regex with lookahead: (\w+)(?=\s\d)
    // The full match is just the word, but if we had multiple captures this could trigger the cache
    // Actually, the cache skip occurs when the full match ends but a capture group went further
    // Let's use a simpler case: a regex that might match empty and advance by +1
    let rules = vec![GrcatConfigEntry {
        // Match word boundary (zero-width) then capture a word
        // The full match (group 0) is the word, but with specific regex constructs...
        // Actually, let me use: (?=\w)(\w)(\w+)?
        // Group 0 matches minimum 1 char, but group 2 can extend further
        regex: CompiledRegex::new(r"(?=\w)(\w)(\w+)?").unwrap(),
        colors: vec![
            Style::new().blue(),
            Style::new().red(),
            Style::new().green(),
        ],
        count: GrcatConfigEntryCount::More,
        replace: String::new(),
        skip: false,
    }];

    let result = run_colorize("test word", rules);
    assert!(strip_ansi(&result).contains("test"));
}

/// Lines 159, 383: Timetrace feature lines (only covered when feature enabled)
/// These lines are #[cfg(feature = "debug")] gated
/// When timetrace is enabled, RGRCTIME env var triggers timing output
#[test]
#[cfg(feature = "debug")]
fn timetrace_feature_increments_counter_and_reports() {
    unsafe {
        std::env::set_var("RGRCTIME", "1");
    }

    let rules = vec![GrcatConfigEntry {
        regex: CompiledRegex::new(r"line").unwrap(),
        colors: vec![Style::new().cyan()],
        count: GrcatConfigEntryCount::More,
        replace: String::new(),
        skip: false,
    }];

    // Process multiple lines to increment lines_processed (line 159)
    let result = run_colorize("line 1\nline 2\nline 3", rules);
    assert!(strip_ansi(&result).contains("line"));
    // The timetrace end report (line 383) should also execute

    unsafe {
        std::env::remove_var("RGRCTIME");
    }
}