Skip to content

Commit 0bd0cf8

Browse files
committed
count all grep patterns correctly if count_flag is set
1 parent 7dccd30 commit 0bd0cf8

File tree

1 file changed

+22
-28
lines changed

1 file changed

+22
-28
lines changed

src/main.rs

Lines changed: 22 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// TODO implement 'mg' features
1+
// TODO refactor
22
use std::{
33
env, fs,
44
io::{self, Write},
@@ -191,40 +191,20 @@ fn main() {
191191
if !captures.is_empty() {
192192
search_hits += 1;
193193

194+
// check if grep_flag is set
194195
if !grep_reg.as_str().is_empty() {
195196
let content =
196197
fs::read_to_string(&fullpath).unwrap_or_else(|_| String::new());
197198

198-
// TODO refactor
199199
if grep_reg.is_match(&content) {
200200
grep_files += 1;
201201

202-
// FIXME if count_flag is set, grep_patterns should be counted as well an printed out
203-
// FIXME currently grep_patterns are shown as '0' , because we don`t search files here
204202
if !count_flag {
205-
let mut linenumber = 0;
206-
207203
if raw_flag {
208204
// don't use "file://" to make the path clickable in Windows Terminal -> otherwise output can't be piped easily to another program
209205
writeln!(handle, "{}", fullpath).unwrap_or_else(|err| {
210206
error!("Error writing to stdout: {err}");
211207
});
212-
213-
for line in content.lines() {
214-
linenumber += 1;
215-
if grep_reg.is_match(&line) {
216-
grep_patterns += 1;
217-
218-
writeln!(
219-
handle,
220-
"{}",
221-
format!(" {}: {}", linenumber, &line)
222-
)
223-
.unwrap_or_else(|err| {
224-
error!("Error writing to stdout: {err}");
225-
});
226-
}
227-
}
228208
} else {
229209
// highlight search pattern in filename
230210
let mut highlighted_name = String::new();
@@ -235,17 +215,31 @@ fn main() {
235215
let highlighted_path = parent + "/" + &highlighted_name;
236216
// TODO check if terminal accepts clickable paths
237217
println!("file://{}", highlighted_path);
218+
}
219+
}
238220

239-
for line in content.lines() {
240-
linenumber += 1;
241-
if grep_reg.is_match(&line) {
242-
grep_patterns += 1;
221+
let mut linenumber = 0;
222+
for line in content.lines() {
223+
linenumber += 1;
224+
let grep_captures: Vec<_> = grep_reg.find_iter(&line).collect();
243225

244-
let grep_captures: Vec<_> =
245-
grep_reg.find_iter(&line).collect();
226+
if !grep_captures.is_empty() {
227+
grep_patterns += grep_captures.len();
246228

229+
if !count_flag {
230+
if raw_flag {
231+
writeln!(
232+
handle,
233+
"{}",
234+
format!(" {}: {}", linenumber, &line)
235+
)
236+
.unwrap_or_else(|err| {
237+
error!("Error writing to stdout: {err}");
238+
});
239+
} else {
247240
let mut highlighted_line = String::new();
248241
for grep_capture in &grep_captures {
242+
// FIXME if more than one capture in line, first one doesn't get highlighted
249243
highlighted_line = highlight_capture(
250244
&line,
251245
&grep_capture,

0 commit comments

Comments
 (0)