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
use std::cmp;
use std::collections::{BTreeMap, VecDeque};
use std::sync::Arc;

use log::error;

use crate::utils::display::{Display, DisplayContext};
use crate::utils::lines::LinesReader;
use crate::utils::matcher::{Match, Matcher, MatcherOptions};

pub type Grep = Arc<Box<dyn Fn(Arc<dyn LinesReader>, Matcher, Arc<dyn Display>) + Send + Sync>>;

type OnMatch = Box<dyn Fn(DisplayContext) -> bool>;
type OnEnd = Box<dyn Fn(usize, usize)>;

fn fuzzy_grep(reader: &Arc<dyn LinesReader>, matcher: &Matcher) -> Option<()> {
    let res = reader.map();
    if res.is_err() {
        // Some readers do not support map
        return Some(());
    }
    res.ok()
        .and_then(|map| matcher(map, MatcherOptions::Fuzzy).and(Some(())))
}

fn generic_grep(reader: Arc<dyn LinesReader>, matcher: Matcher, on_match: OnMatch, on_end: OnEnd) {
    if fuzzy_grep(&reader, &matcher).is_none() {
        on_end(0, 0);
        return;
    }
    let mut matches = 0;
    let mut total = 0;
    match reader.lines() {
        Ok(mut lines) => {
            while let Some(line) = lines.next() {
                total += 1;
                if let Some(needle) = matcher(line, MatcherOptions::Exact(usize::MAX)) {
                    matches += 1;
                    if on_match(DisplayContext::new(total, line.to_string(), needle)) {
                        break;
                    }
                }
            }
        }
        Err(e) => error!("Failed to read '{}': {}", reader.path().display(), e),
    }
    on_end(total, matches);
}

pub fn grep() -> Grep {
    Arc::new(Box::new(
        move |reader: Arc<dyn LinesReader>, matcher: Matcher, display: Arc<dyn Display>| {
            let path = reader.path().clone();
            let display = display.clone();
            generic_grep(
                reader,
                matcher,
                Box::new(move |context| {
                    display.display(&path, Some(context));
                    false
                }),
                Box::new(move |_, _| {}),
            );
        },
    ))
}

fn _grep_with_context(
    reader: Arc<dyn LinesReader>,
    matcher: Matcher,
    display: Arc<dyn Display>,
    before: usize,
    after: usize,
) {
    if fuzzy_grep(&reader, &matcher).is_none() {
        return;
    }
    let path = reader.path().clone();
    let mut lqueue: VecDeque<String> = VecDeque::with_capacity(before + 1);
    let mut lno = 0;
    let mut pcount: isize = 0;
    let mut output = BTreeMap::new();
    match reader.lines() {
        Ok(mut lines) => {
            while let Some(line) = lines.next() {
                lno += 1;
                let needle = matcher(line, MatcherOptions::Exact(usize::MAX));

                if pcount > 0 {
                    output.entry(lno).or_insert_with(|| {
                        DisplayContext::with_lno_separator(lno, line.to_owned(), vec![], "-")
                    });
                    pcount -= 1;
                }
                if let Some(needle) = needle {
                    for i in 0..cmp::min(before, lqueue.len()) {
                        output.entry(lno - i - 1).or_insert_with(|| {
                            DisplayContext::with_lno_separator(
                                lno - i - 1,
                                lqueue.pop_front().unwrap(),
                                vec![],
                                "-",
                            )
                        });
                    }
                    output.insert(lno, DisplayContext::new(lno, line.to_owned(), needle));
                    pcount = after as isize;
                }
                lqueue.push_back(line.to_string());
                if lqueue.len() == before + 1 {
                    lqueue.pop_front();
                }
            }
            let mut plno = 0;
            for (lno, context) in output {
                if plno > 0 && lno - plno > 1 {
                    display.match_separator();
                }
                plno = lno;
                display.display(&path, Some(context));
            }
        }
        Err(e) => error!("Failed to read '{}': {}", reader.path().display(), e),
    }
}

pub fn grep_with_context(before: usize, after: usize) -> Grep {
    Arc::new(Box::new(
        move |reader: Arc<dyn LinesReader>, matcher: Matcher, display: Arc<dyn Display>| {
            _grep_with_context(reader, matcher, display, before, after)
        },
    ))
}

pub fn grep_matches_once() -> Grep {
    Arc::new(Box::new(
        move |reader: Arc<dyn LinesReader>, matcher: Matcher, display: Arc<dyn Display>| {
            let path = reader.path().clone();
            let display = display.clone();
            generic_grep(
                reader,
                matcher,
                Box::new(move |context| {
                    display.display(&path, Some(context));
                    true
                }),
                Box::new(move |_, _| {}),
            );
        },
    ))
}

pub fn grep_matches_all_lines() -> Grep {
    Arc::new(Box::new(
        move |reader: Arc<dyn LinesReader>, matcher: Matcher, display: Arc<dyn Display>| {
            let path = reader.path().clone();
            let display = display.clone();
            generic_grep(
                reader,
                matcher,
                Box::new(move |_| false),
                Box::new(move |total, matches| {
                    if matches == total && total != 0 {
                        display.display(&path, None);
                    }
                }),
            );
        },
    ))
}

pub fn grep_count() -> Grep {
    Arc::new(Box::new(
        move |reader: Arc<dyn LinesReader>, matcher: Matcher, display: Arc<dyn Display>| {
            let path = reader.path().clone();
            let display = display.clone();
            generic_grep(
                reader,
                matcher,
                Box::new(move |_| false),
                Box::new(move |_, matches| {
                    if matches > 0 {
                        let matches = matches.to_string();
                        let matches_len = matches.len();
                        display.display(
                            &path,
                            Some(DisplayContext::new(
                                0,
                                matches,
                                vec![Match::new(0, matches_len)],
                            )),
                        );
                    }
                }),
            );
        },
    ))
}