Add cancellation check to grep_search tool

Add periodic ctrlc_request checks during directory traversal and file
processing in the grep_search tool. This allows the tool to respect user
cancellation (Ctrl+C) during recursive directory scanning of large codebases.

- Changed process_file to return bool indicating cancellation
- Added ctrlc_request check in directory iteration loop
- Added ctrlc_request check in file processing loop
- Returns early with cancellation message when cancelled

Closes issue #189
This commit is contained in:
2026-08-05 23:39:59 +00:00
parent d2451f3484
commit 304a1ba133
+18 -6
View File
@@ -1,5 +1,6 @@
#include "grep_tool.hpp"
#include "json_types.hpp"
#include "utility.hpp"
#include <filesystem>
#include <fstream>
#include <regex>
@@ -63,11 +64,11 @@ 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;
auto process_file = [&](const std::string& file_path) -> bool {
if (!is_text_file(file_path)) return false;
std::ifstream file(file_path);
if (!file.is_open()) return;
if (!file.is_open()) return false;
std::vector<std::string> lines;
std::string line;
@@ -77,12 +78,15 @@ Tool make_grep_tool() {
int last_printed_line = -1;
for (size_t i = 0; i < lines.size(); ++i) {
if (ctrlc_request) {
return true;
}
std::smatch match;
if (std::regex_search(lines[i], match, re)) {
if (displayed_matches >= params.max_matches)
{
return;
return false;
}
displayed_matches++;
@@ -102,6 +106,7 @@ Tool make_grep_tool() {
output += "=== " + file_path + " ===\n";
}
}
return false;
};
std::error_code ec;
@@ -109,7 +114,9 @@ Tool make_grep_tool() {
if (ec) {
output += "Error checking path: " + ec.message() + "\n";
} else {
process_file(params.path);
if (process_file(params.path)) {
return "[user requested halt of program]\n" + output;
}
}
} else if (std::filesystem::is_directory(params.path, ec)) {
if (ec) {
@@ -121,9 +128,14 @@ Tool make_grep_tool() {
} else {
auto end = std::filesystem::recursive_directory_iterator();
while (it != end) {
if (ctrlc_request) {
return "[user requested halt of program]\n" + output;
}
if (std::filesystem::is_regular_file(it->path(), ec)) {
if (!ec) {
process_file(it->path().string());
if (process_file(it->path().string())) {
return "[user requested halt of program]\n" + output;
}
}
}
it.increment(ec);