Adding max matches to grep
This commit is contained in:
+18
-1
@@ -39,7 +39,11 @@ Tool make_grep_tool() {
|
||||
{"case_insensitive", {
|
||||
{"type", "boolean"},
|
||||
{"description", "Perform case-insensitive search. Defaults to false."}
|
||||
}}
|
||||
}},
|
||||
{"max_matches", {
|
||||
{"type", "integer"},
|
||||
{"description", "Max number of matches to display (default 5)"}
|
||||
}},
|
||||
}},
|
||||
{"required", {"path", "pattern"}}
|
||||
},
|
||||
@@ -52,12 +56,16 @@ Tool make_grep_tool() {
|
||||
std::string path = args["path"].get<std::string>();
|
||||
std::string pattern = args["pattern"].get<std::string>();
|
||||
int context = 0;
|
||||
size_t max_matches = 0;
|
||||
bool case_insensitive = false;
|
||||
|
||||
if (args.contains("context") && args["context"].is_number_integer())
|
||||
context = args["context"].get<int>();
|
||||
if (context < 0) context = 0;
|
||||
|
||||
if (args.contains("max_matches") && args["max_matches"].is_number_integer())
|
||||
max_matches = args["max_matches"].get<size_t>();
|
||||
|
||||
if (args.contains("case_insensitive") && args["case_insensitive"].is_boolean())
|
||||
case_insensitive = args["case_insensitive"].get<bool>();
|
||||
|
||||
@@ -73,6 +81,7 @@ Tool make_grep_tool() {
|
||||
}
|
||||
|
||||
std::string output;
|
||||
size_t displayed_matches = 0;
|
||||
|
||||
auto process_file = [&](const std::string& file_path) -> void {
|
||||
if (!is_text_file(file_path)) return;
|
||||
@@ -90,6 +99,14 @@ Tool make_grep_tool() {
|
||||
for (size_t i = 0; i < lines.size(); ++i) {
|
||||
std::smatch match;
|
||||
if (std::regex_search(lines[i], match, re)) {
|
||||
|
||||
if (displayed_matches >= max_matches)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
displayed_matches++;
|
||||
|
||||
int start = std::max(0, static_cast<int>(i) - context);
|
||||
int end = std::min(static_cast<int>(lines.size()) - 1, static_cast<int>(i) + context);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user