Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Colorise search text #9

Merged
merged 3 commits into from
Oct 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 93 additions & 10 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ edition = "2021"

[dependencies]
clap = { version = "4.5.20", features = ["derive"] }
colored = "2.1.0"
67 changes: 39 additions & 28 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
mod args;

use args::Config;
use colored::*;
use std::cmp::PartialEq;
use std::error::Error;
use std::fs;
Expand All @@ -17,15 +18,15 @@ fn main() {

pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
let contents = fs::read_to_string(config.filename)?;
let results: Vec<SearchResult> = if config.ignore_case {
search_case_insensitive(&config.pattern, &contents)
} else {
search(&config.pattern, &contents)
};
let results = search(&config.pattern, &contents, config.ignore_case);

for line in results {
if config.line_number {
println!("{}: {}", line.line_number, line.line_text);
println!(
"{}: {}",
line.line_number.to_string().blue(),
line.line_text
);
} else {
println!("{}", line.line_text);
}
Expand All @@ -46,30 +47,40 @@ impl PartialEq for SearchResult {
}
}

pub fn search(query: &str, contents: &str) -> Vec<SearchResult> {
pub fn search(query: &str, contents: &str, ignore_case: bool) -> Vec<SearchResult> {
contents
.lines()
.enumerate()
.filter(|(_, line)| line.contains(query))
.map(|(index, line)| SearchResult {
line_number: (index + 1) as u32,
line_text: line.to_string(),
})
.collect()
}
.filter_map(|(index, line)| {
let matches = if ignore_case {
line.to_lowercase().contains(&query.to_lowercase())
} else {
line.contains(query)
};

pub fn search_case_insensitive(query: &str, contents: &str) -> Vec<SearchResult> {
contents
.lines()
.enumerate()
.filter(|(_, line)| line.to_lowercase().contains(&query.to_lowercase()))
.map(|(index, line)| SearchResult {
line_number: (index + 1) as u32,
line_text: line.to_string(),
if matches {
let colored_line = if ignore_case {
let mut colored_line = line.to_string();
for (start, part) in line.to_lowercase().match_indices(&query.to_lowercase()) {
let end = start + part.len();
let colored_part = &line[start..end].red().to_string();
colored_line.replace_range(start..end, colored_part);
}
colored_line
} else {
line.replace(query, &query.red().to_string())
};

Some(SearchResult {
line_number: (index + 1) as u32,
line_text: colored_line,
})
} else {
None
}
})
.collect()
}

#[cfg(test)]
mod tests {
use super::*;
Expand All @@ -85,9 +96,9 @@ Duct tape.";

let expected = vec![SearchResult {
line_number: 2,
line_text: "safe, fast, productive.".to_string(),
line_text: "safe, fast, pro".to_string() + &"duct".red().to_string() + "ive.",
}];
assert_eq!(expected, search(query, contents));
assert_eq!(expected, search(query, contents, false));
}

#[test]
Expand All @@ -102,13 +113,13 @@ Trust me.";
let expected = vec![
SearchResult {
line_number: 1,
line_text: "Rust:".to_string(),
line_text: "Rust".red().to_string() + ":",
},
SearchResult {
line_number: 4,
line_text: "Trust me.".to_string(),
line_text: "T".to_string() + &"rust".red().to_string() + " me.",
},
];
assert_eq!(expected, search_case_insensitive(query, contents));
assert_eq!(expected, search(query, contents, true));
}
}
Loading