janito 2.33.0__py3-none-any.whl → 3.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- janito/cli/chat_mode/bindings.py +26 -0
- janito/cli/chat_mode/session.py +7 -1
- janito/cli/cli_commands/check_tools.py +212 -0
- janito/cli/cli_commands/list_plugins.py +52 -43
- janito/cli/core/getters.py +3 -0
- janito/cli/main_cli.py +9 -12
- janito/cli/prompt_core.py +19 -9
- janito/drivers/openai/driver.py +1 -0
- janito/drivers/zai/driver.py +1 -0
- janito/llm/agent.py +30 -17
- janito/llm/auth_utils.py +14 -5
- janito/llm/cancellation_manager.py +62 -0
- janito/llm/driver.py +7 -0
- janito/llm/enter_cancellation.py +93 -0
- janito/plugin_system/__init__.py +10 -0
- janito/{plugins → plugin_system}/base.py +5 -2
- janito/{plugins/core_loader_fixed.py → plugin_system/core_loader.py} +45 -26
- janito/plugin_system/core_loader_fixed.py +149 -0
- janito/plugins/__init__.py +31 -12
- janito/plugins/auto_loader_fixed.py +12 -11
- janito/plugins/builtin.py +15 -1
- janito/plugins/core/__init__.py +7 -0
- janito/plugins/core/codeanalyzer/__init__.py +43 -0
- janito/plugins/core/filemanager/__init__.py +124 -0
- janito/plugins/core/filemanager/tools/create_file.py +87 -0
- janito/plugins/core/filemanager/tools/replace_text_in_file.py +270 -0
- janito/plugins/core/imagedisplay/__init__.py +14 -0
- janito/plugins/core/imagedisplay/plugin.py +51 -0
- janito/plugins/core/imagedisplay/tools/__init__.py +1 -0
- janito/plugins/core/imagedisplay/tools/show_image.py +83 -0
- janito/{tools/adapters/local → plugins/core/imagedisplay/tools}/show_image_grid.py +13 -5
- janito/plugins/core/system/__init__.py +23 -0
- janito/plugins/core_adapter.py +11 -9
- janito/plugins/dev/__init__.py +7 -0
- janito/plugins/dev/pythondev/__init__.py +37 -0
- janito/plugins/dev/visualization/__init__.py +23 -0
- janito/plugins/discovery.py +5 -5
- janito/plugins/example_plugin.py +108 -0
- janito/plugins/manager.py +1 -1
- janito/plugins/tools/__init__.py +10 -0
- janito/{tools/adapters/local → plugins/tools}/ask_user.py +3 -3
- janito/plugins/tools/copy_file.py +87 -0
- janito/plugins/tools/core_tools_plugin.py +88 -0
- janito/plugins/tools/create_directory.py +70 -0
- janito/{tools/adapters/local → plugins/tools}/create_file.py +4 -4
- janito/plugins/tools/decorators.py +19 -0
- janito/plugins/tools/delete_text_in_file.py +134 -0
- janito/{tools/adapters/local → plugins/tools}/fetch_url.py +3 -3
- janito/plugins/tools/find_files.py +143 -0
- janito/plugins/tools/get_file_outline/__init__.py +7 -0
- janito/plugins/tools/get_file_outline/core.py +122 -0
- janito/plugins/tools/get_file_outline/java_outline.py +47 -0
- janito/plugins/tools/get_file_outline/markdown_outline.py +14 -0
- janito/plugins/tools/get_file_outline/python_outline.py +303 -0
- janito/plugins/tools/get_file_outline/search_outline.py +36 -0
- janito/plugins/tools/move_file.py +131 -0
- janito/plugins/tools/open_html_in_browser.py +51 -0
- janito/plugins/tools/open_url.py +37 -0
- janito/plugins/tools/python_code_run.py +172 -0
- janito/plugins/tools/python_command_run.py +171 -0
- janito/plugins/tools/python_file_run.py +172 -0
- janito/plugins/tools/read_chart.py +259 -0
- janito/plugins/tools/read_files.py +58 -0
- janito/plugins/tools/remove_directory.py +55 -0
- janito/plugins/tools/remove_file.py +58 -0
- janito/{tools/adapters/local → plugins/tools}/replace_text_in_file.py +4 -4
- janito/plugins/tools/run_bash_command.py +183 -0
- janito/plugins/tools/run_powershell_command.py +218 -0
- janito/plugins/tools/search_text/__init__.py +7 -0
- janito/plugins/tools/search_text/core.py +205 -0
- janito/plugins/tools/search_text/match_lines.py +67 -0
- janito/plugins/tools/search_text/pattern_utils.py +73 -0
- janito/plugins/tools/search_text/traverse_directory.py +145 -0
- janito/{tools/adapters/local → plugins/tools}/show_image.py +15 -6
- janito/plugins/tools/show_image_grid.py +85 -0
- janito/plugins/tools/validate_file_syntax/__init__.py +7 -0
- janito/plugins/tools/validate_file_syntax/core.py +114 -0
- janito/plugins/tools/validate_file_syntax/css_validator.py +35 -0
- janito/plugins/tools/validate_file_syntax/html_validator.py +100 -0
- janito/plugins/tools/validate_file_syntax/jinja2_validator.py +50 -0
- janito/plugins/tools/validate_file_syntax/js_validator.py +27 -0
- janito/plugins/tools/validate_file_syntax/json_validator.py +6 -0
- janito/plugins/tools/validate_file_syntax/markdown_validator.py +109 -0
- janito/plugins/tools/validate_file_syntax/ps1_validator.py +32 -0
- janito/plugins/tools/validate_file_syntax/python_validator.py +5 -0
- janito/plugins/tools/validate_file_syntax/xml_validator.py +11 -0
- janito/plugins/tools/validate_file_syntax/yaml_validator.py +6 -0
- janito/plugins/tools/view_file.py +172 -0
- janito/plugins/ui/__init__.py +7 -0
- janito/plugins/ui/userinterface/__init__.py +16 -0
- janito/plugins/ui/userinterface/tools/ask_user.py +110 -0
- janito/plugins/web/__init__.py +7 -0
- janito/plugins/web/webtools/__init__.py +33 -0
- janito/plugins/web/webtools/tools/fetch_url.py +458 -0
- janito/tools/__init__.py +31 -7
- janito/tools/adapters/__init__.py +6 -1
- janito/tools/adapters/local/__init__.py +7 -70
- janito/tools/cli_initializer.py +88 -0
- janito/tools/function_adapter.py +93 -16
- janito/tools/initialize.py +70 -0
- {janito-2.33.0.dist-info → janito-3.1.0.dist-info}/METADATA +1 -2
- {janito-2.33.0.dist-info → janito-3.1.0.dist-info}/RECORD +146 -76
- janito/plugins/core_loader.py +0 -120
- /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/get_file_outline/__init__.py +0 -0
- /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/get_file_outline/core.py +0 -0
- /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/get_file_outline/java_outline.py +0 -0
- /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/get_file_outline/markdown_outline.py +0 -0
- /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/get_file_outline/python_outline.py +0 -0
- /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/get_file_outline/search_outline.py +0 -0
- /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/search_text/__init__.py +0 -0
- /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/search_text/core.py +0 -0
- /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/search_text/match_lines.py +0 -0
- /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/search_text/pattern_utils.py +0 -0
- /janito/{tools/adapters/local → plugins/core/codeanalyzer/tools}/search_text/traverse_directory.py +0 -0
- /janito/{tools/adapters/local → plugins/core/filemanager/tools}/copy_file.py +0 -0
- /janito/{tools/adapters/local → plugins/core/filemanager/tools}/create_directory.py +0 -0
- /janito/{tools/adapters/local → plugins/core/filemanager/tools}/delete_text_in_file.py +0 -0
- /janito/{tools/adapters/local → plugins/core/filemanager/tools}/find_files.py +0 -0
- /janito/{tools/adapters/local → plugins/core/filemanager/tools}/move_file.py +0 -0
- /janito/{tools/adapters/local → plugins/core/filemanager/tools}/read_files.py +0 -0
- /janito/{tools/adapters/local → plugins/core/filemanager/tools}/remove_directory.py +0 -0
- /janito/{tools/adapters/local → plugins/core/filemanager/tools}/remove_file.py +0 -0
- /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/__init__.py +0 -0
- /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/core.py +0 -0
- /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/css_validator.py +0 -0
- /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/html_validator.py +0 -0
- /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/jinja2_validator.py +0 -0
- /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/js_validator.py +0 -0
- /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/json_validator.py +0 -0
- /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/markdown_validator.py +0 -0
- /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/ps1_validator.py +0 -0
- /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/python_validator.py +0 -0
- /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/xml_validator.py +0 -0
- /janito/{tools/adapters/local → plugins/core/filemanager/tools}/validate_file_syntax/yaml_validator.py +0 -0
- /janito/{tools/adapters/local → plugins/core/filemanager/tools}/view_file.py +0 -0
- /janito/{tools/adapters/local → plugins/core/system/tools}/run_bash_command.py +0 -0
- /janito/{tools/adapters/local → plugins/core/system/tools}/run_powershell_command.py +0 -0
- /janito/{tools/adapters/local → plugins/dev/pythondev/tools}/python_code_run.py +0 -0
- /janito/{tools/adapters/local → plugins/dev/pythondev/tools}/python_command_run.py +0 -0
- /janito/{tools/adapters/local → plugins/dev/pythondev/tools}/python_file_run.py +0 -0
- /janito/{tools/adapters/local → plugins/dev/visualization/tools}/read_chart.py +0 -0
- /janito/{tools/adapters/local → plugins/web/webtools/tools}/open_html_in_browser.py +0 -0
- /janito/{tools/adapters/local → plugins/web/webtools/tools}/open_url.py +0 -0
- {janito-2.33.0.dist-info → janito-3.1.0.dist-info}/WHEEL +0 -0
- {janito-2.33.0.dist-info → janito-3.1.0.dist-info}/entry_points.txt +0 -0
- {janito-2.33.0.dist-info → janito-3.1.0.dist-info}/licenses/LICENSE +0 -0
- {janito-2.33.0.dist-info → janito-3.1.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,218 @@
|
|
1
|
+
from janito.tools.tool_base import ToolBase, ToolPermissions
|
2
|
+
from janito.report_events import ReportAction
|
3
|
+
from janito.plugins.tools.decorators import register_core_tool
|
4
|
+
from janito.i18n import tr
|
5
|
+
import subprocess
|
6
|
+
import os
|
7
|
+
from janito.tools.path_utils import expand_path
|
8
|
+
import tempfile
|
9
|
+
import threading
|
10
|
+
|
11
|
+
|
12
|
+
@register_core_tool
|
13
|
+
class RunPowershellCommand(ToolBase):
|
14
|
+
"""
|
15
|
+
Execute a non-interactive command using the PowerShell shell and capture live output.
|
16
|
+
This tool explicitly invokes 'powershell.exe' (on Windows) or 'pwsh' (on other platforms if available).
|
17
|
+
All commands are automatically prepended with UTF-8 output encoding:
|
18
|
+
$OutputEncoding = [Console]::OutputEncoding = [System.Text.Encoding]::UTF8;
|
19
|
+
For file output, it is recommended to use -Encoding utf8 in your PowerShell commands (e.g., Out-File -Encoding utf8) to ensure correct file encoding.
|
20
|
+
|
21
|
+
Args:
|
22
|
+
command (str): The PowerShell command to execute. This string is passed directly to PowerShell using the --Command argument (not as a script file).
|
23
|
+
timeout (int): Timeout in seconds for the command. Defaults to 60.
|
24
|
+
require_confirmation (bool): If True, require user confirmation before running. Defaults to False.
|
25
|
+
requires_user_input (bool): If True, warns that the command may require user input and might hang. Defaults to False. Non-interactive commands are preferred for automation and reliability.
|
26
|
+
silent (bool): If True, suppresses progress and status messages. Defaults to False.
|
27
|
+
|
28
|
+
Returns:
|
29
|
+
str: Output and status message, or file paths/line counts if output is large.
|
30
|
+
"""
|
31
|
+
|
32
|
+
permissions = ToolPermissions(execute=True)
|
33
|
+
tool_name = "run_powershell_command"
|
34
|
+
|
35
|
+
def _confirm_and_warn(self, command, require_confirmation, requires_user_input):
|
36
|
+
if requires_user_input:
|
37
|
+
self.report_warning(
|
38
|
+
tr(
|
39
|
+
"⚠️ Warning: This command might be interactive, require user input, and might hang."
|
40
|
+
),
|
41
|
+
ReportAction.EXECUTE,
|
42
|
+
)
|
43
|
+
if require_confirmation:
|
44
|
+
self.report_warning(
|
45
|
+
tr("⚠️ Confirmation requested, but no handler (auto-confirmed)."),
|
46
|
+
ReportAction.EXECUTE,
|
47
|
+
)
|
48
|
+
return True # Auto-confirm for now
|
49
|
+
return True
|
50
|
+
|
51
|
+
def _launch_process(self, shell_exe, command_with_encoding):
|
52
|
+
env = os.environ.copy()
|
53
|
+
env["PYTHONIOENCODING"] = "utf-8"
|
54
|
+
return subprocess.Popen(
|
55
|
+
[
|
56
|
+
shell_exe,
|
57
|
+
"-NoProfile",
|
58
|
+
"-ExecutionPolicy",
|
59
|
+
"Bypass",
|
60
|
+
"-Command",
|
61
|
+
command_with_encoding,
|
62
|
+
],
|
63
|
+
stdout=subprocess.PIPE,
|
64
|
+
stderr=subprocess.PIPE,
|
65
|
+
text=True,
|
66
|
+
bufsize=1,
|
67
|
+
universal_newlines=True,
|
68
|
+
encoding="utf-8",
|
69
|
+
env=env,
|
70
|
+
)
|
71
|
+
|
72
|
+
def _stream_output(self, stream, file_obj, report_func, count_func, counter):
|
73
|
+
for line in stream:
|
74
|
+
file_obj.write(line)
|
75
|
+
file_obj.flush()
|
76
|
+
report_func(line.rstrip("\r\n"), ReportAction.EXECUTE)
|
77
|
+
if count_func == "stdout":
|
78
|
+
counter["stdout"] += 1
|
79
|
+
else:
|
80
|
+
counter["stderr"] += 1
|
81
|
+
|
82
|
+
def _format_result(
|
83
|
+
self, requires_user_input, return_code, stdout_file, stderr_file, max_lines=100
|
84
|
+
):
|
85
|
+
warning_msg = ""
|
86
|
+
if requires_user_input:
|
87
|
+
warning_msg = tr(
|
88
|
+
"⚠️ Warning: This command might be interactive, require user input, and might hang.\n"
|
89
|
+
)
|
90
|
+
with open(stdout_file.name, "r", encoding="utf-8", errors="replace") as out_f:
|
91
|
+
stdout_content = out_f.read()
|
92
|
+
with open(stderr_file.name, "r", encoding="utf-8", errors="replace") as err_f:
|
93
|
+
stderr_content = err_f.read()
|
94
|
+
stdout_lines = stdout_content.count("\n")
|
95
|
+
stderr_lines = stderr_content.count("\n")
|
96
|
+
if stdout_lines <= max_lines and stderr_lines <= max_lines:
|
97
|
+
result = warning_msg + tr(
|
98
|
+
"Return code: {return_code}\n--- STDOUT ---\n{stdout_content}",
|
99
|
+
return_code=return_code,
|
100
|
+
stdout_content=stdout_content,
|
101
|
+
)
|
102
|
+
if stderr_content.strip():
|
103
|
+
result += tr(
|
104
|
+
"\n--- STDERR ---\n{stderr_content}",
|
105
|
+
stderr_content=stderr_content,
|
106
|
+
)
|
107
|
+
return result
|
108
|
+
else:
|
109
|
+
result = warning_msg + tr(
|
110
|
+
"stdout_file: {stdout_file} (lines: {stdout_lines})\n",
|
111
|
+
stdout_file=stdout_file.name,
|
112
|
+
stdout_lines=stdout_lines,
|
113
|
+
)
|
114
|
+
if stderr_lines > 0 and stderr_content.strip():
|
115
|
+
result += tr(
|
116
|
+
"stderr_file: {stderr_file} (lines: {stderr_lines})\n",
|
117
|
+
stderr_file=stderr_file.name,
|
118
|
+
stderr_lines=stderr_lines,
|
119
|
+
)
|
120
|
+
result += tr(
|
121
|
+
"returncode: {return_code}\nUse the view_file tool to inspect the contents of these files when needed.",
|
122
|
+
return_code=return_code,
|
123
|
+
)
|
124
|
+
return result
|
125
|
+
|
126
|
+
def run(
|
127
|
+
self,
|
128
|
+
command: str,
|
129
|
+
timeout: int = 60,
|
130
|
+
require_confirmation: bool = False,
|
131
|
+
requires_user_input: bool = False,
|
132
|
+
silent: bool = False,
|
133
|
+
) -> str:
|
134
|
+
if not command.strip():
|
135
|
+
self.report_warning(tr("ℹ️ Empty command provided."), ReportAction.EXECUTE)
|
136
|
+
return tr("Warning: Empty command provided. Operation skipped.")
|
137
|
+
encoding_prefix = "$OutputEncoding = [Console]::OutputEncoding = [System.Text.Encoding]::UTF8; "
|
138
|
+
command_with_encoding = encoding_prefix + command
|
139
|
+
if not silent:
|
140
|
+
self.report_action(
|
141
|
+
tr("🖥️ Running PowerShell command: {command} ...\n", command=command),
|
142
|
+
ReportAction.EXECUTE,
|
143
|
+
)
|
144
|
+
else:
|
145
|
+
self.report_action(tr("⚡ Executing..."), ReportAction.EXECUTE)
|
146
|
+
self._confirm_and_warn(command, require_confirmation, requires_user_input)
|
147
|
+
from janito.platform_discovery import PlatformDiscovery
|
148
|
+
|
149
|
+
pd = PlatformDiscovery()
|
150
|
+
shell_exe = "powershell.exe" if pd.is_windows() else "pwsh"
|
151
|
+
try:
|
152
|
+
with (
|
153
|
+
tempfile.NamedTemporaryFile(
|
154
|
+
mode="w+",
|
155
|
+
prefix="run_powershell_stdout_",
|
156
|
+
delete=False,
|
157
|
+
encoding="utf-8",
|
158
|
+
) as stdout_file,
|
159
|
+
tempfile.NamedTemporaryFile(
|
160
|
+
mode="w+",
|
161
|
+
prefix="run_powershell_stderr_",
|
162
|
+
delete=False,
|
163
|
+
encoding="utf-8",
|
164
|
+
) as stderr_file,
|
165
|
+
):
|
166
|
+
process = self._launch_process(shell_exe, command_with_encoding)
|
167
|
+
counter = {"stdout": 0, "stderr": 0}
|
168
|
+
stdout_thread = threading.Thread(
|
169
|
+
target=self._stream_output,
|
170
|
+
args=(
|
171
|
+
process.stdout,
|
172
|
+
stdout_file,
|
173
|
+
self.report_stdout,
|
174
|
+
"stdout",
|
175
|
+
counter,
|
176
|
+
),
|
177
|
+
)
|
178
|
+
stderr_thread = threading.Thread(
|
179
|
+
target=self._stream_output,
|
180
|
+
args=(
|
181
|
+
process.stderr,
|
182
|
+
stderr_file,
|
183
|
+
self.report_stderr,
|
184
|
+
"stderr",
|
185
|
+
counter,
|
186
|
+
),
|
187
|
+
)
|
188
|
+
stdout_thread.start()
|
189
|
+
stderr_thread.start()
|
190
|
+
try:
|
191
|
+
return_code = process.wait(timeout=timeout)
|
192
|
+
except subprocess.TimeoutExpired:
|
193
|
+
process.kill()
|
194
|
+
self.report_error(
|
195
|
+
tr(
|
196
|
+
" ❌ Timed out after {timeout} seconds.",
|
197
|
+
timeout=timeout,
|
198
|
+
),
|
199
|
+
ReportAction.EXECUTE,
|
200
|
+
)
|
201
|
+
return tr(
|
202
|
+
"Command timed out after {timeout} seconds.", timeout=timeout
|
203
|
+
)
|
204
|
+
stdout_thread.join()
|
205
|
+
stderr_thread.join()
|
206
|
+
stdout_file.flush()
|
207
|
+
stderr_file.flush()
|
208
|
+
if not silent:
|
209
|
+
self.report_success(
|
210
|
+
tr(" ✅ return code {return_code}", return_code=return_code),
|
211
|
+
ReportAction.EXECUTE,
|
212
|
+
)
|
213
|
+
return self._format_result(
|
214
|
+
requires_user_input, return_code, stdout_file, stderr_file
|
215
|
+
)
|
216
|
+
except Exception as e:
|
217
|
+
self.report_error(tr(" ❌ Error: {error}", error=e), ReportAction.EXECUTE)
|
218
|
+
return tr("Error running command: {error}", error=e)
|
@@ -0,0 +1,205 @@
|
|
1
|
+
from janito.tools.tool_base import ToolBase, ToolPermissions
|
2
|
+
from janito.report_events import ReportAction
|
3
|
+
from janito.tools.adapters.local.adapter import register_local_tool
|
4
|
+
from janito.tools.tool_utils import pluralize, display_path
|
5
|
+
from janito.i18n import tr
|
6
|
+
import os
|
7
|
+
from janito.tools.path_utils import expand_path
|
8
|
+
from .pattern_utils import prepare_pattern, format_result, summarize_total
|
9
|
+
from .match_lines import read_file_lines
|
10
|
+
from .traverse_directory import traverse_directory
|
11
|
+
from janito.tools.loop_protection_decorator import protect_against_loops
|
12
|
+
|
13
|
+
|
14
|
+
from janito.plugins.tools.decorators import register_core_tool
|
15
|
+
|
16
|
+
|
17
|
+
@register_core_tool
|
18
|
+
class SearchText(ToolBase):
|
19
|
+
"""
|
20
|
+
Search for a text query in all files within one or more directories or file paths and return matching lines or counts. Respects .gitignore.
|
21
|
+
Args:
|
22
|
+
paths (str): String of one or more paths (space-separated) to search in. Each path can be a directory or a file.
|
23
|
+
query (str): Text or regular expression to search for in files. Must not be empty. When use_regex=True, this is treated as a regex pattern; otherwise as plain text.
|
24
|
+
use_regex (bool): If True, treat query as a regular expression. If False, treat as plain text (default).
|
25
|
+
case_sensitive (bool): If False, perform a case-insensitive search. Default is True (case sensitive).
|
26
|
+
max_depth (int, optional): Maximum directory depth to search. If 0 (default), search is recursive with no depth limit. If >0, limits recursion to that depth. Setting max_depth=1 disables recursion (only top-level directory). Ignored for file paths.
|
27
|
+
max_results (int, optional): Maximum number of results to return. Defaults to 100. 0 means no limit.
|
28
|
+
count_only (bool): If True, return only the count of matches per file and total, not the matching lines. Default is False.
|
29
|
+
Returns:
|
30
|
+
str: If count_only is False, matching lines from files as a newline-separated string, each formatted as 'filepath:lineno: line'.
|
31
|
+
If count_only is True, returns per-file and total match counts.
|
32
|
+
If max_results is reached, appends a note to the output.
|
33
|
+
"""
|
34
|
+
|
35
|
+
permissions = ToolPermissions(read=True)
|
36
|
+
tool_name = "search_text"
|
37
|
+
|
38
|
+
def _handle_file(
|
39
|
+
self,
|
40
|
+
search_path,
|
41
|
+
query,
|
42
|
+
regex,
|
43
|
+
use_regex,
|
44
|
+
case_sensitive,
|
45
|
+
max_results,
|
46
|
+
total_results,
|
47
|
+
count_only,
|
48
|
+
):
|
49
|
+
if count_only:
|
50
|
+
match_count, dir_limit_reached, _ = read_file_lines(
|
51
|
+
search_path,
|
52
|
+
query,
|
53
|
+
regex,
|
54
|
+
use_regex,
|
55
|
+
case_sensitive,
|
56
|
+
True,
|
57
|
+
max_results,
|
58
|
+
total_results,
|
59
|
+
)
|
60
|
+
per_file_counts = [(search_path, match_count)] if match_count > 0 else []
|
61
|
+
return [], dir_limit_reached, per_file_counts
|
62
|
+
else:
|
63
|
+
dir_output, dir_limit_reached, match_count_list = read_file_lines(
|
64
|
+
search_path,
|
65
|
+
query,
|
66
|
+
regex,
|
67
|
+
use_regex,
|
68
|
+
case_sensitive,
|
69
|
+
False,
|
70
|
+
max_results,
|
71
|
+
total_results,
|
72
|
+
)
|
73
|
+
per_file_counts = (
|
74
|
+
[(search_path, len(match_count_list))]
|
75
|
+
if match_count_list and len(match_count_list) > 0
|
76
|
+
else []
|
77
|
+
)
|
78
|
+
return dir_output, dir_limit_reached, per_file_counts
|
79
|
+
|
80
|
+
def _handle_path(
|
81
|
+
self,
|
82
|
+
search_path,
|
83
|
+
query,
|
84
|
+
regex,
|
85
|
+
use_regex,
|
86
|
+
case_sensitive,
|
87
|
+
max_depth,
|
88
|
+
max_results,
|
89
|
+
total_results,
|
90
|
+
count_only,
|
91
|
+
):
|
92
|
+
info_str = tr(
|
93
|
+
"🔍 Search {search_type} '{query}' in '{disp_path}'",
|
94
|
+
search_type=("regex" if use_regex else "text"),
|
95
|
+
query=query,
|
96
|
+
disp_path=display_path(search_path),
|
97
|
+
)
|
98
|
+
if max_depth > 0:
|
99
|
+
info_str += tr(" [max_depth={max_depth}]", max_depth=max_depth)
|
100
|
+
if count_only:
|
101
|
+
info_str += " [count]"
|
102
|
+
self.report_action(info_str, ReportAction.READ)
|
103
|
+
if os.path.isfile(search_path):
|
104
|
+
dir_output, dir_limit_reached, per_file_counts = self._handle_file(
|
105
|
+
search_path,
|
106
|
+
query,
|
107
|
+
regex,
|
108
|
+
use_regex,
|
109
|
+
case_sensitive,
|
110
|
+
max_results,
|
111
|
+
total_results,
|
112
|
+
count_only,
|
113
|
+
)
|
114
|
+
else:
|
115
|
+
if count_only:
|
116
|
+
per_file_counts, dir_limit_reached, _ = traverse_directory(
|
117
|
+
search_path,
|
118
|
+
query,
|
119
|
+
regex,
|
120
|
+
use_regex,
|
121
|
+
case_sensitive,
|
122
|
+
max_depth,
|
123
|
+
max_results,
|
124
|
+
total_results,
|
125
|
+
True,
|
126
|
+
)
|
127
|
+
dir_output = []
|
128
|
+
else:
|
129
|
+
dir_output, dir_limit_reached, per_file_counts = traverse_directory(
|
130
|
+
search_path,
|
131
|
+
query,
|
132
|
+
regex,
|
133
|
+
use_regex,
|
134
|
+
case_sensitive,
|
135
|
+
max_depth,
|
136
|
+
max_results,
|
137
|
+
total_results,
|
138
|
+
False,
|
139
|
+
)
|
140
|
+
count = sum(count for _, count in per_file_counts)
|
141
|
+
file_word = pluralize("match", count)
|
142
|
+
num_files = len(per_file_counts)
|
143
|
+
file_label = pluralize("file", num_files)
|
144
|
+
file_word_max = file_word + (" (max)" if dir_limit_reached else "")
|
145
|
+
self.report_success(
|
146
|
+
tr(
|
147
|
+
" ✅ {count} {file_word}/{num_files} {file_label}",
|
148
|
+
count=count,
|
149
|
+
file_word=file_word_max,
|
150
|
+
num_files=num_files,
|
151
|
+
file_label=file_label,
|
152
|
+
),
|
153
|
+
ReportAction.READ,
|
154
|
+
)
|
155
|
+
return info_str, dir_output, dir_limit_reached, per_file_counts
|
156
|
+
|
157
|
+
@protect_against_loops(max_calls=5, time_window=10.0, key_field="paths")
|
158
|
+
def run(
|
159
|
+
self,
|
160
|
+
paths: str,
|
161
|
+
query: str,
|
162
|
+
use_regex: bool = False,
|
163
|
+
case_sensitive: bool = False,
|
164
|
+
max_depth: int = 0,
|
165
|
+
max_results: int = 100,
|
166
|
+
count_only: bool = False,
|
167
|
+
) -> str:
|
168
|
+
regex, use_regex, error_msg = prepare_pattern(
|
169
|
+
query, use_regex, case_sensitive, self.report_error, self.report_warning
|
170
|
+
)
|
171
|
+
if error_msg:
|
172
|
+
return error_msg
|
173
|
+
paths_list = [expand_path(p) for p in paths.split()]
|
174
|
+
results = []
|
175
|
+
all_per_file_counts = []
|
176
|
+
for search_path in paths_list:
|
177
|
+
info_str, dir_output, dir_limit_reached, per_file_counts = (
|
178
|
+
self._handle_path(
|
179
|
+
search_path,
|
180
|
+
query,
|
181
|
+
regex,
|
182
|
+
use_regex,
|
183
|
+
case_sensitive,
|
184
|
+
max_depth,
|
185
|
+
max_results,
|
186
|
+
0,
|
187
|
+
count_only,
|
188
|
+
)
|
189
|
+
)
|
190
|
+
if count_only:
|
191
|
+
all_per_file_counts.extend(per_file_counts)
|
192
|
+
result_str = format_result(
|
193
|
+
query,
|
194
|
+
use_regex,
|
195
|
+
dir_output,
|
196
|
+
dir_limit_reached,
|
197
|
+
count_only,
|
198
|
+
per_file_counts,
|
199
|
+
)
|
200
|
+
results.append(info_str + "\n" + result_str)
|
201
|
+
if dir_limit_reached:
|
202
|
+
break
|
203
|
+
if count_only:
|
204
|
+
results.append(summarize_total(all_per_file_counts))
|
205
|
+
return "\n\n".join(results)
|
@@ -0,0 +1,67 @@
|
|
1
|
+
import re
|
2
|
+
from janito.gitignore_utils import GitignoreFilter
|
3
|
+
import os
|
4
|
+
|
5
|
+
|
6
|
+
def is_binary_file(path, blocksize=1024):
|
7
|
+
try:
|
8
|
+
with open(path, "rb") as f:
|
9
|
+
chunk = f.read(blocksize)
|
10
|
+
if b"\0" in chunk:
|
11
|
+
return True
|
12
|
+
text_characters = bytearray(
|
13
|
+
{7, 8, 9, 10, 12, 13, 27} | set(range(0x20, 0x100))
|
14
|
+
)
|
15
|
+
nontext = chunk.translate(None, text_characters)
|
16
|
+
if len(nontext) / max(1, len(chunk)) > 0.3:
|
17
|
+
return True
|
18
|
+
except Exception:
|
19
|
+
return True
|
20
|
+
return False
|
21
|
+
|
22
|
+
|
23
|
+
def match_line(line, query, regex, use_regex, case_sensitive):
|
24
|
+
if use_regex:
|
25
|
+
return regex and regex.search(line)
|
26
|
+
if not case_sensitive:
|
27
|
+
return query.lower() in line.lower()
|
28
|
+
return query in line
|
29
|
+
|
30
|
+
|
31
|
+
def should_limit(max_results, total_results, match_count, count_only, dir_output):
|
32
|
+
if max_results > 0:
|
33
|
+
current_count = total_results + (match_count if count_only else len(dir_output))
|
34
|
+
return current_count >= max_results
|
35
|
+
return False
|
36
|
+
|
37
|
+
|
38
|
+
def read_file_lines(
|
39
|
+
path,
|
40
|
+
query,
|
41
|
+
regex,
|
42
|
+
use_regex,
|
43
|
+
case_sensitive,
|
44
|
+
count_only,
|
45
|
+
max_results,
|
46
|
+
total_results,
|
47
|
+
):
|
48
|
+
dir_output = []
|
49
|
+
dir_limit_reached = False
|
50
|
+
match_count = 0
|
51
|
+
if not is_binary_file(path):
|
52
|
+
try:
|
53
|
+
open_kwargs = {"mode": "r", "encoding": "utf-8"}
|
54
|
+
with open(path, **open_kwargs) as f:
|
55
|
+
for lineno, line in enumerate(f, 1):
|
56
|
+
if match_line(line, query, regex, use_regex, case_sensitive):
|
57
|
+
match_count += 1
|
58
|
+
if not count_only:
|
59
|
+
dir_output.append(f"{path}:{lineno}: {line.rstrip()}")
|
60
|
+
if should_limit(
|
61
|
+
max_results, total_results, match_count, count_only, dir_output
|
62
|
+
):
|
63
|
+
dir_limit_reached = True
|
64
|
+
break
|
65
|
+
except Exception:
|
66
|
+
pass
|
67
|
+
return match_count, dir_limit_reached, dir_output
|
@@ -0,0 +1,73 @@
|
|
1
|
+
import re
|
2
|
+
from janito.i18n import tr
|
3
|
+
from janito.tools.tool_utils import pluralize
|
4
|
+
|
5
|
+
|
6
|
+
def prepare_pattern(pattern, is_regex, case_sensitive, report_error, report_warning):
|
7
|
+
if not pattern:
|
8
|
+
report_error(
|
9
|
+
tr("Error: Empty search pattern provided. Operation aborted."),
|
10
|
+
ReportAction.SEARCH,
|
11
|
+
)
|
12
|
+
return (
|
13
|
+
None,
|
14
|
+
False,
|
15
|
+
tr("Error: Empty search pattern provided. Operation aborted."),
|
16
|
+
)
|
17
|
+
regex = None
|
18
|
+
use_regex = False
|
19
|
+
if is_regex:
|
20
|
+
try:
|
21
|
+
flags = 0
|
22
|
+
if not case_sensitive:
|
23
|
+
flags |= re.IGNORECASE
|
24
|
+
regex = re.compile(pattern, flags=flags)
|
25
|
+
use_regex = True
|
26
|
+
except re.error as e:
|
27
|
+
report_warning(tr("⚠️ Invalid regex pattern."))
|
28
|
+
return (
|
29
|
+
None,
|
30
|
+
False,
|
31
|
+
tr(
|
32
|
+
"Error: Invalid regex pattern: {error}. Operation aborted.", error=e
|
33
|
+
),
|
34
|
+
)
|
35
|
+
else:
|
36
|
+
# Do not compile as regex if is_regex is False; treat as plain text
|
37
|
+
regex = None
|
38
|
+
use_regex = False
|
39
|
+
if not case_sensitive:
|
40
|
+
pattern = pattern.lower()
|
41
|
+
return regex, use_regex, None
|
42
|
+
|
43
|
+
|
44
|
+
def format_result(
|
45
|
+
query, use_regex, output, limit_reached, count_only=False, per_file_counts=None
|
46
|
+
):
|
47
|
+
# Ensure output is always a list for joining
|
48
|
+
if output is None or not isinstance(output, (list, tuple)):
|
49
|
+
output = []
|
50
|
+
if count_only:
|
51
|
+
lines = []
|
52
|
+
total = 0
|
53
|
+
if per_file_counts:
|
54
|
+
for path, count in per_file_counts:
|
55
|
+
lines.append(f"{path}: {count}")
|
56
|
+
total += count
|
57
|
+
lines.append(f"Total matches: {total}")
|
58
|
+
if limit_reached:
|
59
|
+
lines.append(tr("[Max results reached. Output truncated.]"))
|
60
|
+
return "\n".join(lines)
|
61
|
+
else:
|
62
|
+
if not output:
|
63
|
+
return tr("No matches found.")
|
64
|
+
result = "\n".join(output)
|
65
|
+
if limit_reached:
|
66
|
+
result += tr("\n[Max results reached. Output truncated.]")
|
67
|
+
return result
|
68
|
+
|
69
|
+
|
70
|
+
def summarize_total(all_per_file_counts):
|
71
|
+
total = sum(count for _, count in all_per_file_counts)
|
72
|
+
summary = f"\nGrand total matches: {total}"
|
73
|
+
return summary
|