janito 1.9.0__py3-none-any.whl → 1.11.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.
Files changed (106) hide show
  1. janito/__init__.py +1 -1
  2. janito/agent/api_exceptions.py +4 -0
  3. janito/agent/config.py +1 -1
  4. janito/agent/config_defaults.py +2 -26
  5. janito/agent/conversation.py +163 -122
  6. janito/agent/conversation_api.py +246 -168
  7. janito/agent/conversation_ui.py +1 -1
  8. janito/agent/{conversation_history.py → llm_conversation_history.py} +30 -1
  9. janito/agent/openai_client.py +38 -23
  10. janito/agent/openai_schema_generator.py +162 -129
  11. janito/agent/platform_discovery.py +134 -77
  12. janito/agent/profile_manager.py +5 -5
  13. janito/agent/rich_message_handler.py +80 -31
  14. janito/agent/templates/profiles/system_prompt_template_base.txt.j2 +20 -4
  15. janito/agent/test_openai_schema_generator.py +93 -0
  16. janito/agent/tool_base.py +7 -2
  17. janito/agent/tool_executor.py +54 -49
  18. janito/agent/tool_registry.py +5 -2
  19. janito/agent/tool_use_tracker.py +26 -5
  20. janito/agent/tools/__init__.py +8 -3
  21. janito/agent/tools/create_directory.py +3 -1
  22. janito/agent/tools/create_file.py +7 -1
  23. janito/agent/tools/fetch_url.py +40 -3
  24. janito/agent/tools/find_files.py +29 -14
  25. janito/agent/tools/get_file_outline/core.py +7 -8
  26. janito/agent/tools/get_file_outline/python_outline.py +139 -95
  27. janito/agent/tools/get_file_outline/search_outline.py +3 -1
  28. janito/agent/tools/get_lines.py +98 -64
  29. janito/agent/tools/move_file.py +59 -31
  30. janito/agent/tools/open_url.py +31 -0
  31. janito/agent/tools/present_choices.py +3 -1
  32. janito/agent/tools/python_command_runner.py +149 -0
  33. janito/agent/tools/python_file_runner.py +147 -0
  34. janito/agent/tools/python_stdin_runner.py +153 -0
  35. janito/agent/tools/remove_directory.py +3 -1
  36. janito/agent/tools/remove_file.py +5 -1
  37. janito/agent/tools/replace_file.py +12 -2
  38. janito/agent/tools/replace_text_in_file.py +195 -149
  39. janito/agent/tools/run_bash_command.py +30 -69
  40. janito/agent/tools/run_powershell_command.py +138 -105
  41. janito/agent/tools/search_text/__init__.py +1 -0
  42. janito/agent/tools/search_text/core.py +176 -0
  43. janito/agent/tools/search_text/match_lines.py +58 -0
  44. janito/agent/tools/search_text/pattern_utils.py +65 -0
  45. janito/agent/tools/search_text/traverse_directory.py +127 -0
  46. janito/agent/tools/validate_file_syntax/core.py +43 -30
  47. janito/agent/tools/validate_file_syntax/html_validator.py +21 -5
  48. janito/agent/tools/validate_file_syntax/markdown_validator.py +77 -34
  49. janito/agent/tools_utils/action_type.py +7 -0
  50. janito/agent/tools_utils/dir_walk_utils.py +3 -2
  51. janito/agent/tools_utils/formatting.py +47 -21
  52. janito/agent/tools_utils/gitignore_utils.py +89 -40
  53. janito/agent/tools_utils/test_gitignore_utils.py +46 -0
  54. janito/agent/tools_utils/utils.py +7 -1
  55. janito/cli/_print_config.py +63 -61
  56. janito/cli/arg_parser.py +13 -12
  57. janito/cli/cli_main.py +137 -147
  58. janito/cli/config_commands.py +112 -109
  59. janito/cli/main.py +152 -174
  60. janito/cli/one_shot.py +40 -26
  61. janito/i18n/__init__.py +1 -1
  62. janito/rich_utils.py +46 -8
  63. janito/shell/commands/__init__.py +2 -4
  64. janito/shell/commands/conversation_restart.py +3 -1
  65. janito/shell/commands/edit.py +3 -0
  66. janito/shell/commands/history_view.py +3 -3
  67. janito/shell/commands/lang.py +3 -0
  68. janito/shell/commands/livelogs.py +5 -3
  69. janito/shell/commands/prompt.py +6 -0
  70. janito/shell/commands/session.py +3 -0
  71. janito/shell/commands/session_control.py +3 -0
  72. janito/shell/commands/termweb_log.py +8 -0
  73. janito/shell/commands/tools.py +3 -0
  74. janito/shell/commands/track.py +36 -0
  75. janito/shell/commands/utility.py +13 -18
  76. janito/shell/commands/verbose.py +3 -4
  77. janito/shell/input_history.py +62 -0
  78. janito/shell/main.py +160 -181
  79. janito/shell/session/config.py +83 -75
  80. janito/shell/session/manager.py +0 -21
  81. janito/shell/ui/interactive.py +97 -75
  82. janito/termweb/static/editor.css +32 -33
  83. janito/termweb/static/editor.css.bak +140 -22
  84. janito/termweb/static/editor.html +12 -7
  85. janito/termweb/static/editor.html.bak +16 -11
  86. janito/termweb/static/editor.js +94 -40
  87. janito/termweb/static/editor.js.bak +97 -65
  88. janito/termweb/static/index.html +1 -2
  89. janito/termweb/static/index.html.bak +1 -1
  90. janito/termweb/static/termweb.css +1 -22
  91. janito/termweb/static/termweb.css.bak +6 -4
  92. janito/termweb/static/termweb.js +0 -6
  93. janito/termweb/static/termweb.js.bak +1 -2
  94. janito/tests/test_rich_utils.py +44 -0
  95. janito/web/app.py +0 -75
  96. {janito-1.9.0.dist-info → janito-1.11.0.dist-info}/METADATA +61 -42
  97. janito-1.11.0.dist-info/RECORD +163 -0
  98. {janito-1.9.0.dist-info → janito-1.11.0.dist-info}/WHEEL +1 -1
  99. janito/agent/providers.py +0 -77
  100. janito/agent/tools/run_python_command.py +0 -161
  101. janito/agent/tools/search_text.py +0 -204
  102. janito/shell/commands/sum.py +0 -49
  103. janito-1.9.0.dist-info/RECORD +0 -151
  104. {janito-1.9.0.dist-info → janito-1.11.0.dist-info}/entry_points.txt +0 -0
  105. {janito-1.9.0.dist-info → janito-1.11.0.dist-info}/licenses/LICENSE +0 -0
  106. {janito-1.9.0.dist-info → janito-1.11.0.dist-info}/top_level.txt +0 -0
@@ -1,7 +1,9 @@
1
1
  from janito.agent.tool_base import ToolBase
2
+ from janito.agent.tools_utils.action_type import ActionType
2
3
  from janito.agent.tool_registry import register_tool
3
4
  from janito.i18n import tr
4
5
  import subprocess
6
+ import os
5
7
  import tempfile
6
8
  import threading
7
9
 
@@ -18,30 +20,16 @@ class RunPowerShellCommandTool(ToolBase):
18
20
  command (str): The PowerShell command to execute. This string is passed directly to PowerShell using the --Command argument (not as a script file).
19
21
  timeout (int, optional): Timeout in seconds for the command. Defaults to 60.
20
22
  require_confirmation (bool, optional): If True, require user confirmation before running. Defaults to False.
21
- interactive (bool, optional): If True, warns that the command may require user interaction. Defaults to False. Non-interactive commands are preferred for automation and reliability.
23
+ requires_user_input (bool, optional): 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.
22
24
  Returns:
23
25
  str: Output and status message, or file paths/line counts if output is large.
24
26
  """
25
27
 
26
- def run(
27
- self,
28
- command: str,
29
- timeout: int = 60,
30
- require_confirmation: bool = False,
31
- interactive: bool = False,
32
- ) -> str:
33
- if not command.strip():
34
- self.report_warning(tr("ℹ️ Empty command provided."))
35
- return tr("Warning: Empty command provided. Operation skipped.")
36
- encoding_prefix = "$OutputEncoding = [Console]::OutputEncoding = [System.Text.Encoding]::UTF8; "
37
- command_with_encoding = encoding_prefix + command
38
- self.report_info(
39
- tr("🖥️ Running PowerShell command: {command} ...\n", command=command)
40
- )
41
- if interactive:
28
+ def _confirm_and_warn(self, command, require_confirmation, requires_user_input):
29
+ if requires_user_input:
42
30
  self.report_warning(
43
31
  tr(
44
- "⚠️ Warning: This command might be interactive, require user input, and might hang."
32
+ "\u26a0\ufe0f Warning: This command might be interactive, require user input, and might hang."
45
33
  )
46
34
  )
47
35
  if require_confirmation:
@@ -52,11 +40,112 @@ class RunPowerShellCommandTool(ToolBase):
52
40
  )
53
41
  )
54
42
  if not confirmed:
55
- self.report_warning(tr("⚠️ Execution cancelled by user."))
56
- return tr("❌ Command execution cancelled by user.")
57
- from janito.agent.platform_discovery import is_windows
43
+ self.report_warning(tr("\u26a0\ufe0f Execution cancelled by user."))
44
+ return False
45
+ return True
58
46
 
59
- shell_exe = "powershell.exe" if is_windows() else "pwsh"
47
+ def _launch_process(self, shell_exe, command_with_encoding):
48
+ env = os.environ.copy()
49
+ env["PYTHONIOENCODING"] = "utf-8"
50
+ return subprocess.Popen(
51
+ [
52
+ shell_exe,
53
+ "-NoProfile",
54
+ "-ExecutionPolicy",
55
+ "Bypass",
56
+ "-Command",
57
+ command_with_encoding,
58
+ ],
59
+ stdout=subprocess.PIPE,
60
+ stderr=subprocess.PIPE,
61
+ text=True,
62
+ bufsize=1,
63
+ universal_newlines=True,
64
+ encoding="utf-8",
65
+ env=env,
66
+ )
67
+
68
+ def _stream_output(self, stream, file_obj, report_func, count_func, counter):
69
+ for line in stream:
70
+ file_obj.write(line)
71
+ file_obj.flush()
72
+ report_func(line)
73
+ if count_func == "stdout":
74
+ counter["stdout"] += 1
75
+ else:
76
+ counter["stderr"] += 1
77
+
78
+ def _format_result(
79
+ self, requires_user_input, return_code, stdout_file, stderr_file, max_lines=100
80
+ ):
81
+ warning_msg = ""
82
+ if requires_user_input:
83
+ warning_msg = tr(
84
+ "\u26a0\ufe0f Warning: This command might be interactive, require user input, and might hang.\n"
85
+ )
86
+ with open(stdout_file.name, "r", encoding="utf-8", errors="replace") as out_f:
87
+ stdout_content = out_f.read()
88
+ with open(stderr_file.name, "r", encoding="utf-8", errors="replace") as err_f:
89
+ stderr_content = err_f.read()
90
+ stdout_lines = stdout_content.count("\n")
91
+ stderr_lines = stderr_content.count("\n")
92
+ if stdout_lines <= max_lines and stderr_lines <= max_lines:
93
+ result = warning_msg + tr(
94
+ "Return code: {return_code}\n--- STDOUT ---\n{stdout_content}",
95
+ return_code=return_code,
96
+ stdout_content=stdout_content,
97
+ )
98
+ if stderr_content.strip():
99
+ result += tr(
100
+ "\n--- STDERR ---\n{stderr_content}",
101
+ stderr_content=stderr_content,
102
+ )
103
+ return result
104
+ else:
105
+ result = warning_msg + tr(
106
+ "stdout_file: {stdout_file} (lines: {stdout_lines})\n",
107
+ stdout_file=stdout_file.name,
108
+ stdout_lines=stdout_lines,
109
+ )
110
+ if stderr_lines > 0 and stderr_content.strip():
111
+ result += tr(
112
+ "stderr_file: {stderr_file} (lines: {stderr_lines})\n",
113
+ stderr_file=stderr_file.name,
114
+ stderr_lines=stderr_lines,
115
+ )
116
+ result += tr(
117
+ "returncode: {return_code}\nUse the get_lines tool to inspect the contents of these files when needed.",
118
+ return_code=return_code,
119
+ )
120
+ return result
121
+
122
+ def run(
123
+ self,
124
+ command: str,
125
+ timeout: int = 60,
126
+ require_confirmation: bool = False,
127
+ requires_user_input: bool = False,
128
+ ) -> str:
129
+ if not command.strip():
130
+ self.report_warning(tr("\u2139\ufe0f Empty command provided."))
131
+ return tr("Warning: Empty command provided. Operation skipped.")
132
+ encoding_prefix = "$OutputEncoding = [Console]::OutputEncoding = [System.Text.Encoding]::UTF8; "
133
+ command_with_encoding = encoding_prefix + command
134
+ self.report_info(
135
+ ActionType.EXECUTE,
136
+ tr(
137
+ "\U0001f5a5\ufe0f Running PowerShell command: {command} ...\n",
138
+ command=command,
139
+ ),
140
+ )
141
+ if not self._confirm_and_warn(
142
+ command, require_confirmation, requires_user_input
143
+ ):
144
+ return tr("\u274c Command execution cancelled by user.")
145
+ from janito.agent.platform_discovery import PlatformDiscovery
146
+
147
+ pd = PlatformDiscovery()
148
+ shell_exe = "powershell.exe" if pd.is_windows() else "pwsh"
60
149
  try:
61
150
  with (
62
151
  tempfile.NamedTemporaryFile(
@@ -72,44 +161,27 @@ class RunPowerShellCommandTool(ToolBase):
72
161
  encoding="utf-8",
73
162
  ) as stderr_file,
74
163
  ):
75
- process = subprocess.Popen(
76
- [
77
- shell_exe,
78
- "-NoProfile",
79
- "-ExecutionPolicy",
80
- "Bypass",
81
- "-Command",
82
- command_with_encoding,
83
- ],
84
- stdout=subprocess.PIPE,
85
- stderr=subprocess.PIPE,
86
- text=True,
87
- bufsize=1,
88
- universal_newlines=True,
89
- encoding="utf-8",
90
- )
91
-
92
- stdout_lines = 0
93
- stderr_lines = 0
94
-
95
- def stream_output(stream, file_obj, report_func, count_func):
96
- nonlocal stdout_lines, stderr_lines
97
- for line in stream:
98
- file_obj.write(line)
99
- file_obj.flush()
100
- report_func(line)
101
- if count_func == "stdout":
102
- stdout_lines += 1
103
- else:
104
- stderr_lines += 1
105
-
164
+ process = self._launch_process(shell_exe, command_with_encoding)
165
+ counter = {"stdout": 0, "stderr": 0}
106
166
  stdout_thread = threading.Thread(
107
- target=stream_output,
108
- args=(process.stdout, stdout_file, self.report_stdout, "stdout"),
167
+ target=self._stream_output,
168
+ args=(
169
+ process.stdout,
170
+ stdout_file,
171
+ self.report_stdout,
172
+ "stdout",
173
+ counter,
174
+ ),
109
175
  )
110
176
  stderr_thread = threading.Thread(
111
- target=stream_output,
112
- args=(process.stderr, stderr_file, self.report_stderr, "stderr"),
177
+ target=self._stream_output,
178
+ args=(
179
+ process.stderr,
180
+ stderr_file,
181
+ self.report_stderr,
182
+ "stderr",
183
+ counter,
184
+ ),
113
185
  )
114
186
  stdout_thread.start()
115
187
  stderr_thread.start()
@@ -118,7 +190,10 @@ class RunPowerShellCommandTool(ToolBase):
118
190
  except subprocess.TimeoutExpired:
119
191
  process.kill()
120
192
  self.report_error(
121
- tr(" ❌ Timed out after {timeout} seconds.", timeout=timeout)
193
+ tr(
194
+ " \u274c Timed out after {timeout} seconds.",
195
+ timeout=timeout,
196
+ )
122
197
  )
123
198
  return tr(
124
199
  "Command timed out after {timeout} seconds.", timeout=timeout
@@ -127,54 +202,12 @@ class RunPowerShellCommandTool(ToolBase):
127
202
  stderr_thread.join()
128
203
  stdout_file.flush()
129
204
  stderr_file.flush()
130
-
131
205
  self.report_success(
132
- tr(" return code {return_code}", return_code=return_code)
206
+ tr(" \u2705 return code {return_code}", return_code=return_code)
207
+ )
208
+ return self._format_result(
209
+ requires_user_input, return_code, stdout_file, stderr_file
133
210
  )
134
- warning_msg = ""
135
- if interactive:
136
- warning_msg = tr(
137
- "⚠️ Warning: This command might be interactive, require user input, and might hang.\n"
138
- )
139
- # Read back the content for summary if not too large
140
- with open(
141
- stdout_file.name, "r", encoding="utf-8", errors="replace"
142
- ) as out_f:
143
- stdout_content = out_f.read()
144
- with open(
145
- stderr_file.name, "r", encoding="utf-8", errors="replace"
146
- ) as err_f:
147
- stderr_content = err_f.read()
148
- max_lines = 100
149
- if stdout_lines <= max_lines and stderr_lines <= max_lines:
150
- result = warning_msg + tr(
151
- "Return code: {return_code}\n--- STDOUT ---\n{stdout_content}",
152
- return_code=return_code,
153
- stdout_content=stdout_content,
154
- )
155
- if stderr_content.strip():
156
- result += tr(
157
- "\n--- STDERR ---\n{stderr_content}",
158
- stderr_content=stderr_content,
159
- )
160
- return result
161
- else:
162
- result = warning_msg + tr(
163
- "stdout_file: {stdout_file} (lines: {stdout_lines})\n",
164
- stdout_file=stdout_file.name,
165
- stdout_lines=stdout_lines,
166
- )
167
- if stderr_lines > 0 and stderr_content.strip():
168
- result += tr(
169
- "stderr_file: {stderr_file} (lines: {stderr_lines})\n",
170
- stderr_file=stderr_file.name,
171
- stderr_lines=stderr_lines,
172
- )
173
- result += tr(
174
- "returncode: {return_code}\nUse the get_lines tool to inspect the contents of these files when needed.",
175
- return_code=return_code,
176
- )
177
- return result
178
211
  except Exception as e:
179
- self.report_error(tr(" Error: {error}", error=e))
212
+ self.report_error(tr(" \u274c Error: {error}", error=e))
180
213
  return tr("Error running command: {error}", error=e)
@@ -0,0 +1 @@
1
+ from .core import SearchTextTool
@@ -0,0 +1,176 @@
1
+ from janito.agent.tool_base import ToolBase
2
+ from janito.agent.tools_utils.action_type import ActionType
3
+ from janito.agent.tool_registry import register_tool
4
+ from janito.agent.tools_utils.utils import pluralize, display_path
5
+ from janito.i18n import tr
6
+ import os
7
+ from .pattern_utils import prepare_pattern, format_result, summarize_total
8
+ from .match_lines import read_file_lines
9
+ from .traverse_directory import traverse_directory
10
+
11
+
12
+ @register_tool(name="search_text")
13
+ class SearchTextTool(ToolBase):
14
+ """
15
+ Search for a text pattern (regex or plain string) in all files within one or more directories or file paths and return matching lines or counts. Respects .gitignore.
16
+ Args:
17
+ paths (str): String of one or more paths (space-separated) to search in. Each path can be a directory or a file.
18
+ pattern (str): Regex pattern or plain text substring to search for in files. Must not be empty. Tries regex first, falls back to substring if regex is invalid.
19
+ is_regex (bool): If True, treat pattern as a regular expression. If False, treat as plain text (default).
20
+ 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.
21
+ max_results (int, optional): Maximum number of results to return. Defaults to 100. 0 means no limit.
22
+ count_only (bool): If True, return only the count of matches per file and total, not the matching lines. Default is False.
23
+ Returns:
24
+ str: If count_only is False, matching lines from files as a newline-separated string, each formatted as 'filepath:lineno: line'.
25
+ If count_only is True, returns per-file and total match counts.
26
+ If max_results is reached, appends a note to the output.
27
+ """
28
+
29
+ def _handle_file(
30
+ self,
31
+ search_path,
32
+ pattern,
33
+ regex,
34
+ use_regex,
35
+ max_results,
36
+ total_results,
37
+ count_only,
38
+ ):
39
+ if count_only:
40
+ match_count, dir_limit_reached, _ = read_file_lines(
41
+ search_path,
42
+ pattern,
43
+ regex,
44
+ use_regex,
45
+ True,
46
+ max_results,
47
+ total_results,
48
+ )
49
+ per_file_counts = [(search_path, match_count)] if match_count > 0 else []
50
+ return [], dir_limit_reached, per_file_counts
51
+ else:
52
+ dir_output, dir_limit_reached, match_count_list = read_file_lines(
53
+ search_path,
54
+ pattern,
55
+ regex,
56
+ use_regex,
57
+ False,
58
+ max_results,
59
+ total_results,
60
+ )
61
+ per_file_counts = (
62
+ [(search_path, len(match_count_list))]
63
+ if match_count_list and len(match_count_list) > 0
64
+ else []
65
+ )
66
+ return dir_output, dir_limit_reached, per_file_counts
67
+
68
+ def _handle_path(
69
+ self,
70
+ search_path,
71
+ pattern,
72
+ regex,
73
+ use_regex,
74
+ max_depth,
75
+ max_results,
76
+ total_results,
77
+ count_only,
78
+ ):
79
+ info_str = tr(
80
+ "\U0001f50d Search {search_type} '{pattern}' in '{disp_path}'",
81
+ search_type=("regex" if use_regex else "text"),
82
+ pattern=pattern,
83
+ disp_path=display_path(search_path),
84
+ )
85
+ if max_depth > 0:
86
+ info_str += tr(" [max_depth={max_depth}]", max_depth=max_depth)
87
+ if count_only:
88
+ info_str += " [count]"
89
+ self.report_info(ActionType.READ, info_str)
90
+ if os.path.isfile(search_path):
91
+ dir_output, dir_limit_reached, per_file_counts = self._handle_file(
92
+ search_path,
93
+ pattern,
94
+ regex,
95
+ use_regex,
96
+ max_results,
97
+ total_results,
98
+ count_only,
99
+ )
100
+ else:
101
+ if count_only:
102
+ per_file_counts, dir_limit_reached, _ = traverse_directory(
103
+ search_path,
104
+ pattern,
105
+ regex,
106
+ use_regex,
107
+ max_depth,
108
+ max_results,
109
+ total_results,
110
+ True,
111
+ )
112
+ dir_output = []
113
+ else:
114
+ dir_output, dir_limit_reached, per_file_counts = traverse_directory(
115
+ search_path,
116
+ pattern,
117
+ regex,
118
+ use_regex,
119
+ max_depth,
120
+ max_results,
121
+ total_results,
122
+ False,
123
+ )
124
+ count = sum(count for _, count in per_file_counts)
125
+ file_word = pluralize("match", count)
126
+ self.report_success(
127
+ tr(" \u2705 {count} {file_word}", count=count, file_word=file_word)
128
+ )
129
+ return info_str, dir_output, dir_limit_reached, per_file_counts
130
+
131
+ def run(
132
+ self,
133
+ paths: str,
134
+ pattern: str,
135
+ is_regex: bool = False,
136
+ max_depth: int = 0,
137
+ max_results: int = 100,
138
+ count_only: bool = False,
139
+ ) -> str:
140
+ regex, use_regex, error_msg = prepare_pattern(
141
+ pattern, is_regex, self.report_error, self.report_warning
142
+ )
143
+ if error_msg:
144
+ return error_msg
145
+ paths_list = paths.split()
146
+ results = []
147
+ all_per_file_counts = []
148
+ for search_path in paths_list:
149
+ info_str, dir_output, dir_limit_reached, per_file_counts = (
150
+ self._handle_path(
151
+ search_path,
152
+ pattern,
153
+ regex,
154
+ use_regex,
155
+ max_depth,
156
+ max_results,
157
+ 0,
158
+ count_only,
159
+ )
160
+ )
161
+ if count_only:
162
+ all_per_file_counts.extend(per_file_counts)
163
+ result_str = format_result(
164
+ pattern,
165
+ use_regex,
166
+ dir_output,
167
+ dir_limit_reached,
168
+ count_only,
169
+ per_file_counts,
170
+ )
171
+ results.append(info_str + "\n" + result_str)
172
+ if dir_limit_reached:
173
+ break
174
+ if count_only:
175
+ results.append(summarize_total(all_per_file_counts))
176
+ return "\n\n".join(results)
@@ -0,0 +1,58 @@
1
+ import re
2
+ from janito.agent.tools_utils.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, pattern, regex, use_regex):
24
+ if use_regex:
25
+ return regex and regex.search(line)
26
+ return pattern in line
27
+
28
+
29
+ def should_limit(max_results, total_results, match_count, count_only, dir_output):
30
+ if max_results > 0:
31
+ current_count = total_results + (match_count if count_only else len(dir_output))
32
+ return current_count >= max_results
33
+ return False
34
+
35
+
36
+ def read_file_lines(
37
+ path, pattern, regex, use_regex, count_only, max_results, total_results
38
+ ):
39
+ dir_output = []
40
+ dir_limit_reached = False
41
+ match_count = 0
42
+ if not is_binary_file(path):
43
+ try:
44
+ open_kwargs = {"mode": "r", "encoding": "utf-8"}
45
+ with open(path, **open_kwargs) as f:
46
+ for lineno, line in enumerate(f, 1):
47
+ if match_line(line, pattern, regex, use_regex):
48
+ match_count += 1
49
+ if not count_only:
50
+ dir_output.append(f"{path}:{lineno}: {line.rstrip()}")
51
+ if should_limit(
52
+ max_results, total_results, match_count, count_only, dir_output
53
+ ):
54
+ dir_limit_reached = True
55
+ break
56
+ except Exception:
57
+ pass
58
+ return match_count, dir_limit_reached, dir_output
@@ -0,0 +1,65 @@
1
+ import re
2
+ from janito.i18n import tr
3
+ from janito.agent.tools_utils.utils import pluralize
4
+
5
+
6
+ def prepare_pattern(pattern, is_regex, report_error, report_warning):
7
+ if not pattern:
8
+ report_error(tr("Error: Empty search pattern provided. Operation aborted."))
9
+ return (
10
+ None,
11
+ False,
12
+ tr("Error: Empty search pattern provided. Operation aborted."),
13
+ )
14
+ regex = None
15
+ use_regex = False
16
+ if is_regex:
17
+ try:
18
+ regex = re.compile(pattern)
19
+ use_regex = True
20
+ except re.error as e:
21
+ report_warning(tr("\u26a0\ufe0f Invalid regex pattern."))
22
+ return (
23
+ None,
24
+ False,
25
+ tr(
26
+ "Error: Invalid regex pattern: {error}. Operation aborted.", error=e
27
+ ),
28
+ )
29
+ else:
30
+ # Do not compile as regex if is_regex is False; treat as plain text
31
+ regex = None
32
+ use_regex = False
33
+ return regex, use_regex, None
34
+
35
+
36
+ def format_result(
37
+ pattern, use_regex, output, limit_reached, count_only=False, per_file_counts=None
38
+ ):
39
+ # Ensure output is always a list for joining
40
+ if output is None or not isinstance(output, (list, tuple)):
41
+ output = []
42
+ if count_only:
43
+ lines = []
44
+ total = 0
45
+ if per_file_counts:
46
+ for file_path, count in per_file_counts:
47
+ lines.append(f"{file_path}: {count}")
48
+ total += count
49
+ lines.append(f"Total matches: {total}")
50
+ if limit_reached:
51
+ lines.append(tr("[Max results reached. Output truncated.]"))
52
+ return "\n".join(lines)
53
+ else:
54
+ if not output:
55
+ return tr("No matches found.")
56
+ result = "\n".join(output)
57
+ if limit_reached:
58
+ result += tr("\n[Max results reached. Output truncated.]")
59
+ return result
60
+
61
+
62
+ def summarize_total(all_per_file_counts):
63
+ total = sum(count for _, count in all_per_file_counts)
64
+ summary = f"\nGrand total matches: {total}"
65
+ return summary