gitstack 5.3.0

Git history viewer with insights - Author stats, file heatmap, code ownership
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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
//! Smart filter module
//!
//! Provides advanced commit filtering via structured queries

use chrono::{DateTime, Duration, Local, NaiveDate};

use crate::event::{GitEvent, GitEventKind};

/// Smart filter query
///
/// Parses query strings starting with `/` and holds structured filter conditions
#[derive(Debug, Clone, Default)]
pub struct FilterQuery {
    /// Author filter
    pub author: Option<String>,
    /// Start date/time filter
    pub since: Option<DateTime<Local>>,
    /// End date/time filter
    pub until: Option<DateTime<Local>>,
    /// File pattern filter
    pub file_pattern: Option<String>,
    /// Message pattern filter
    pub message_pattern: Option<String>,
    /// Commit type filter
    pub commit_type: Option<GitEventKind>,
    /// Plain text filter (for backward compatibility)
    pub plain_text: Option<String>,
    /// Hash range filter (start hash, end hash)
    pub hash_range: Option<(String, String)>,
    /// AI session filter
    pub session: Option<u32>,
}

impl FilterQuery {
    /// Create an empty query
    pub fn new() -> Self {
        Self::default()
    }

    /// Parse a query string
    ///
    /// If the string starts with `/`, parse as a smart filter.
    /// Otherwise, treat as a legacy plain text search.
    pub fn parse(input: &str) -> Self {
        let input = input.trim();

        if input.is_empty() {
            return Self::default();
        }

        // If not starting with `/`, use backward-compatible plain text search
        if !input.starts_with('/') {
            return Self {
                plain_text: Some(input.to_lowercase()),
                ..Default::default()
            };
        }

        let mut query = Self::default();

        // Remove the leading `/` and split into tokens
        let content = &input[1..];
        let tokens: Vec<&str> = content.split_whitespace().collect();

        for token in tokens {
            if let Some(value) = token.strip_prefix("author:") {
                query.author = Some(value.to_lowercase());
            } else if let Some(value) = token.strip_prefix("since:") {
                query.since = parse_date(value);
            } else if let Some(value) = token.strip_prefix("until:") {
                query.until = parse_date(value);
            } else if let Some(value) = token.strip_prefix("file:") {
                query.file_pattern = Some(value.to_string());
            } else if let Some(value) = token.strip_prefix("message:") {
                query.message_pattern = Some(value.to_lowercase());
            } else if let Some(value) = token.strip_prefix("type:") {
                query.commit_type = parse_commit_type(value);
            } else if let Some(value) = token.strip_prefix("hash:") {
                // Parse hash:A..B format
                if let Some((start, end)) = value.split_once("..") {
                    if !start.is_empty() && !end.is_empty() {
                        query.hash_range = Some((start.to_string(), end.to_string()));
                    }
                }
            } else if let Some(value) = token.strip_prefix("session:") {
                query.session = value.parse().ok();
            } else {
                // Tokens without a keyword are treated as message patterns
                if let Some(existing) = query.message_pattern.take() {
                    query.message_pattern = Some(format!("{} {}", existing, token.to_lowercase()));
                } else {
                    query.message_pattern = Some(token.to_lowercase());
                }
            }
        }

        query
    }

    /// Determine whether an event matches this filter
    ///
    /// `files` is only needed when the file filter is active
    ///
    /// Conditions are evaluated in order of increasing computational cost (short-circuit optimization):
    /// 1. commit_type: enum comparison (lightest)
    /// 2. since/until: date/time comparison
    /// 3. author: substring match
    /// 4. message: substring match
    /// 5. plain_text: substring match across multiple fields
    /// 6. file: array traversal (heaviest)
    pub fn matches(&self, event: &GitEvent, files: Option<&[String]>) -> bool {
        // Plain text filter (backward compatible) - mutually exclusive with other filters
        if let Some(ref text) = self.plain_text {
            return event.message.to_lowercase().contains(text)
                || event.author.to_lowercase().contains(text)
                || event.short_hash.to_lowercase().contains(text);
        }

        // Session filter (simple Option comparison - lightest)
        if let Some(session_id) = self.session {
            if event.session_id != Some(session_id) {
                return false;
            }
        }

        // Commit type filter (enum comparison - lightest)
        if let Some(ref kind) = self.commit_type {
            if event.kind != *kind {
                return false;
            }
        }

        // Date filter (since) - date/time comparison
        if let Some(since) = self.since {
            if event.timestamp < since {
                return false;
            }
        }

        // Date filter (until) - date/time comparison
        if let Some(until) = self.until {
            if event.timestamp > until {
                return false;
            }
        }

        // Author filter - substring match
        if let Some(ref author) = self.author {
            if !event.author.to_lowercase().contains(author) {
                return false;
            }
        }

        // Message pattern filter - substring match
        if let Some(ref pattern) = self.message_pattern {
            if !event.message.to_lowercase().contains(pattern) {
                return false;
            }
        }

        // File pattern filter (array traversal - heaviest)
        // Note: File info is only available for preloaded commits
        // To prevent UI blocking, older commits will not match the file filter
        if let Some(ref pattern) = self.file_pattern {
            if let Some(file_list) = files {
                let pattern_lower = pattern.to_lowercase();
                if !file_list
                    .iter()
                    .any(|f| f.to_lowercase().contains(&pattern_lower))
                {
                    return false;
                }
            } else {
                // No file info available (outside preload range) - no match
                return false;
            }
        }

        true
    }

    /// Whether the file filter is active
    pub fn has_file_filter(&self) -> bool {
        self.file_pattern.is_some()
    }

    /// Whether any filter is set
    pub fn is_empty(&self) -> bool {
        self.author.is_none()
            && self.since.is_none()
            && self.until.is_none()
            && self.file_pattern.is_none()
            && self.message_pattern.is_none()
            && self.commit_type.is_none()
            && self.plain_text.is_none()
            && self.hash_range.is_none()
            && self.session.is_none()
    }

    /// Whether the hash range filter is active
    pub fn has_hash_range(&self) -> bool {
        self.hash_range.is_some()
    }

    /// Generate a description of the filter
    pub fn description(&self) -> String {
        if self.is_empty() {
            return String::new();
        }

        if let Some(ref text) = self.plain_text {
            return format!("\"{}\"", text);
        }

        let mut parts = Vec::new();

        if let Some(ref author) = self.author {
            parts.push(format!("author:{}", author));
        }
        if self.since.is_some() {
            parts.push("since:...".to_string());
        }
        if self.until.is_some() {
            parts.push("until:...".to_string());
        }
        if let Some(ref pattern) = self.message_pattern {
            parts.push(format!("message:{}", pattern));
        }
        if let Some(ref kind) = self.commit_type {
            let kind_str = match kind {
                GitEventKind::Commit => "commit",
                GitEventKind::Merge => "merge",
                GitEventKind::BranchSwitch => "switch",
            };
            parts.push(format!("type:{}", kind_str));
        }
        if let Some(ref pattern) = self.file_pattern {
            parts.push(format!("file:{}", pattern));
        }
        if let Some((ref start, ref end)) = self.hash_range {
            parts.push(format!("hash:{}..{}", start, end));
        }

        parts.join(" ")
    }
}

/// Parse a date string
///
/// Supported formats:
/// - Relative dates: `1day`, `2days`, `1week`, `2weeks`, `1month`, `2months`
/// - Absolute dates: `YYYY-MM-DD`
fn parse_date(input: &str) -> Option<DateTime<Local>> {
    let input = input.trim().to_lowercase();

    // Parse relative dates
    if let Some(num_str) = input.strip_suffix("day") {
        if let Ok(days) = num_str.parse::<i64>() {
            return Some(Local::now() - Duration::days(days));
        }
    }
    if let Some(num_str) = input.strip_suffix("days") {
        if let Ok(days) = num_str.parse::<i64>() {
            return Some(Local::now() - Duration::days(days));
        }
    }
    if let Some(num_str) = input.strip_suffix("week") {
        if let Ok(weeks) = num_str.parse::<i64>() {
            return Some(Local::now() - Duration::weeks(weeks));
        }
    }
    if let Some(num_str) = input.strip_suffix("weeks") {
        if let Ok(weeks) = num_str.parse::<i64>() {
            return Some(Local::now() - Duration::weeks(weeks));
        }
    }
    if let Some(num_str) = input.strip_suffix("month") {
        if let Ok(months) = num_str.parse::<i64>() {
            return Some(Local::now() - Duration::days(months * 30));
        }
    }
    if let Some(num_str) = input.strip_suffix("months") {
        if let Ok(months) = num_str.parse::<i64>() {
            return Some(Local::now() - Duration::days(months * 30));
        }
    }

    // Parse absolute date (YYYY-MM-DD)
    if let Ok(date) = NaiveDate::parse_from_str(&input, "%Y-%m-%d") {
        let datetime = date.and_hms_opt(0, 0, 0)?;
        return datetime.and_local_timezone(Local).single();
    }

    None
}

/// Parse a commit type string
fn parse_commit_type(input: &str) -> Option<GitEventKind> {
    match input.to_lowercase().as_str() {
        "commit" => Some(GitEventKind::Commit),
        "merge" => Some(GitEventKind::Merge),
        "switch" => Some(GitEventKind::BranchSwitch),
        _ => None,
    }
}

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

    fn create_test_event(message: &str, author: &str) -> GitEvent {
        GitEvent::commit(
            "abc1234".to_string(),
            message.to_string(),
            author.to_string(),
            Local::now(),
            0,
            0,
        )
    }

    // ===== parse() tests =====

    #[test]
    fn test_parse_empty_returns_default() {
        let query = FilterQuery::parse("");
        assert!(query.is_empty());
    }

    #[test]
    fn test_parse_plain_text_without_slash() {
        let query = FilterQuery::parse("fix bug");
        assert_eq!(query.plain_text, Some("fix bug".to_string()));
        assert!(query.author.is_none());
    }

    #[test]
    fn test_parse_author_filter() {
        let query = FilterQuery::parse("/author:john");
        assert_eq!(query.author, Some("john".to_string()));
    }

    #[test]
    fn test_parse_message_filter() {
        let query = FilterQuery::parse("/message:fix");
        assert_eq!(query.message_pattern, Some("fix".to_string()));
    }

    #[test]
    fn test_parse_type_merge() {
        let query = FilterQuery::parse("/type:merge");
        assert_eq!(query.commit_type, Some(GitEventKind::Merge));
    }

    #[test]
    fn test_parse_type_commit() {
        let query = FilterQuery::parse("/type:commit");
        assert_eq!(query.commit_type, Some(GitEventKind::Commit));
    }

    #[test]
    fn test_parse_file_filter() {
        let query = FilterQuery::parse("/file:src/auth");
        assert_eq!(query.file_pattern, Some("src/auth".to_string()));
    }

    #[test]
    fn test_parse_since_relative_days() {
        let query = FilterQuery::parse("/since:7days");
        assert!(query.since.is_some());
        let since = query.since.unwrap();
        let expected = Local::now() - Duration::days(7);
        // Allow up to 1 second of difference
        assert!((since - expected).num_seconds().abs() < 1);
    }

    #[test]
    fn test_parse_since_relative_week() {
        let query = FilterQuery::parse("/since:1week");
        assert!(query.since.is_some());
        let since = query.since.unwrap();
        let expected = Local::now() - Duration::weeks(1);
        assert!((since - expected).num_seconds().abs() < 1);
    }

    #[test]
    fn test_parse_since_absolute_date() {
        let query = FilterQuery::parse("/since:2024-01-15");
        assert!(query.since.is_some());
    }

    #[test]
    fn test_parse_combined_query() {
        let query = FilterQuery::parse("/author:john since:1week fix");
        assert_eq!(query.author, Some("john".to_string()));
        assert!(query.since.is_some());
        assert_eq!(query.message_pattern, Some("fix".to_string()));
    }

    #[test]
    fn test_parse_multiple_keywords() {
        let query = FilterQuery::parse("/author:john message:fix bug");
        assert_eq!(query.author, Some("john".to_string()));
        assert_eq!(query.message_pattern, Some("fix bug".to_string()));
    }

    // ===== matches() tests =====

    #[test]
    fn test_matches_plain_text_in_message() {
        let query = FilterQuery::parse("feat");
        let event = create_test_event("feat: add feature", "author");
        assert!(query.matches(&event, None));
    }

    #[test]
    fn test_matches_plain_text_in_author() {
        let query = FilterQuery::parse("john");
        let event = create_test_event("some message", "John Doe");
        assert!(query.matches(&event, None));
    }

    #[test]
    fn test_matches_plain_text_in_hash() {
        let query = FilterQuery::parse("abc");
        let event = create_test_event("message", "author");
        assert!(query.matches(&event, None));
    }

    #[test]
    fn test_matches_plain_text_case_insensitive() {
        let query = FilterQuery::parse("FEAT");
        let event = create_test_event("feat: add feature", "author");
        assert!(query.matches(&event, None));
    }

    #[test]
    fn test_matches_author_filter() {
        let query = FilterQuery::parse("/author:john");
        let event = create_test_event("message", "John Doe");
        assert!(query.matches(&event, None));
    }

    #[test]
    fn test_matches_author_filter_no_match() {
        let query = FilterQuery::parse("/author:alice");
        let event = create_test_event("message", "John Doe");
        assert!(!query.matches(&event, None));
    }

    #[test]
    fn test_matches_message_filter() {
        let query = FilterQuery::parse("/message:fix");
        let event = create_test_event("fix: bug fix", "author");
        assert!(query.matches(&event, None));
    }

    #[test]
    fn test_matches_type_merge() {
        let query = FilterQuery::parse("/type:merge");
        let event = GitEvent::merge(
            "abc1234".to_string(),
            "Merge branch".to_string(),
            "author".to_string(),
            Local::now(),
        );
        assert!(query.matches(&event, None));
    }

    #[test]
    fn test_matches_type_commit_not_merge() {
        let query = FilterQuery::parse("/type:commit");
        let event = GitEvent::merge(
            "abc1234".to_string(),
            "Merge branch".to_string(),
            "author".to_string(),
            Local::now(),
        );
        assert!(!query.matches(&event, None));
    }

    #[test]
    fn test_matches_since_filter() {
        let query = FilterQuery::parse("/since:1day");
        let event = create_test_event("message", "author");
        assert!(query.matches(&event, None));
    }

    #[test]
    fn test_matches_since_filter_old_event() {
        let query = FilterQuery {
            since: Some(Local::now()),
            ..Default::default()
        };
        let mut event = create_test_event("message", "author");
        event.timestamp = Local::now() - Duration::days(2);
        assert!(!query.matches(&event, None));
    }

    #[test]
    fn test_matches_file_filter_with_files() {
        let query = FilterQuery::parse("/file:src/auth");
        let event = create_test_event("message", "author");
        let files = vec!["src/auth/login.rs".to_string(), "README.md".to_string()];
        assert!(query.matches(&event, Some(&files)));
    }

    #[test]
    fn test_matches_file_filter_no_match() {
        let query = FilterQuery::parse("/file:src/auth");
        let event = create_test_event("message", "author");
        let files = vec!["src/main.rs".to_string(), "README.md".to_string()];
        assert!(!query.matches(&event, Some(&files)));
    }

    #[test]
    fn test_matches_file_filter_without_files() {
        let query = FilterQuery::parse("/file:src/auth");
        let event = create_test_event("message", "author");
        assert!(!query.matches(&event, None));
    }

    #[test]
    fn test_matches_combined_filters() {
        let query = FilterQuery::parse("/author:john message:fix");
        let event = create_test_event("fix: bug fix", "John Doe");
        assert!(query.matches(&event, None));
    }

    #[test]
    fn test_matches_combined_filters_partial_fail() {
        let query = FilterQuery::parse("/author:john message:fix");
        let event = create_test_event("feat: new feature", "John Doe");
        assert!(!query.matches(&event, None));
    }

    // ===== Japanese text tests =====

    #[test]
    fn test_matches_japanese_message() {
        let query = FilterQuery::parse("修正");
        let event = create_test_event("バグ修正: ログイン問題を解決", "田中太郎");
        assert!(query.matches(&event, None));
    }

    #[test]
    fn test_matches_japanese_author() {
        let query = FilterQuery::parse("/author:田中");
        let event = create_test_event("feat: new feature", "田中太郎");
        assert!(query.matches(&event, None));
    }

    // ===== Helper method tests =====

    #[test]
    fn test_has_file_filter_true() {
        let query = FilterQuery::parse("/file:src");
        assert!(query.has_file_filter());
    }

    #[test]
    fn test_has_file_filter_false() {
        let query = FilterQuery::parse("/author:john");
        assert!(!query.has_file_filter());
    }

    #[test]
    fn test_is_empty_true() {
        let query = FilterQuery::parse("");
        assert!(query.is_empty());
    }

    #[test]
    fn test_is_empty_false() {
        let query = FilterQuery::parse("/author:john");
        assert!(!query.is_empty());
    }

    #[test]
    fn test_description_plain_text() {
        let query = FilterQuery::parse("fix bug");
        assert_eq!(query.description(), "\"fix bug\"");
    }

    #[test]
    fn test_description_smart_filter() {
        let query = FilterQuery::parse("/author:john type:merge");
        let desc = query.description();
        assert!(desc.contains("author:john"));
        assert!(desc.contains("type:merge"));
    }

    // ===== Hash range filter tests =====

    #[test]
    fn test_parse_hash_range_filter() {
        let query = FilterQuery::parse("/hash:abc1234..def5678");
        assert!(query.hash_range.is_some());
        let (start, end) = query.hash_range.unwrap();
        assert_eq!(start, "abc1234");
        assert_eq!(end, "def5678");
    }

    #[test]
    fn test_parse_hash_range_with_other_filters() {
        let query = FilterQuery::parse("/hash:abc..def author:john");
        assert!(query.hash_range.is_some());
        assert_eq!(query.author, Some("john".to_string()));
        let (start, end) = query.hash_range.unwrap();
        assert_eq!(start, "abc");
        assert_eq!(end, "def");
    }

    #[test]
    fn test_parse_hash_range_invalid_format() {
        // Incomplete format is ignored
        let query = FilterQuery::parse("/hash:abc");
        assert!(query.hash_range.is_none());
    }

    #[test]
    fn test_parse_hash_range_empty_parts() {
        // Empty parts are ignored
        let query = FilterQuery::parse("/hash:..def");
        assert!(query.hash_range.is_none());

        let query = FilterQuery::parse("/hash:abc..");
        assert!(query.hash_range.is_none());
    }

    #[test]
    fn test_has_hash_range_true() {
        let query = FilterQuery::parse("/hash:abc..def");
        assert!(query.has_hash_range());
    }

    #[test]
    fn test_has_hash_range_false() {
        let query = FilterQuery::parse("/author:john");
        assert!(!query.has_hash_range());
    }

    #[test]
    fn test_is_empty_false_with_hash_range() {
        let query = FilterQuery::parse("/hash:abc..def");
        assert!(!query.is_empty());
    }

    #[test]
    fn test_description_with_hash_range() {
        let query = FilterQuery::parse("/hash:abc..def");
        let desc = query.description();
        assert!(desc.contains("hash:abc..def"));
    }
}