janito 0.5.0__py3-none-any.whl → 0.7.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 (110) hide show
  1. janito/__init__.py +0 -47
  2. janito/__main__.py +105 -17
  3. janito/agents/__init__.py +9 -9
  4. janito/agents/agent.py +10 -3
  5. janito/agents/claudeai.py +15 -34
  6. janito/agents/openai.py +5 -1
  7. janito/change/__init__.py +29 -16
  8. janito/change/__main__.py +0 -0
  9. janito/{analysis → change/analysis}/__init__.py +5 -15
  10. janito/change/analysis/__main__.py +7 -0
  11. janito/change/analysis/analyze.py +62 -0
  12. janito/change/analysis/formatting.py +78 -0
  13. janito/change/analysis/options.py +81 -0
  14. janito/{analysis → change/analysis}/prompts.py +33 -18
  15. janito/change/analysis/view/__init__.py +9 -0
  16. janito/change/analysis/view/terminal.py +181 -0
  17. janito/change/applier/__init__.py +5 -0
  18. janito/change/applier/file.py +58 -0
  19. janito/change/applier/main.py +156 -0
  20. janito/change/applier/text.py +247 -0
  21. janito/change/applier/workspace_dir.py +58 -0
  22. janito/change/core.py +124 -0
  23. janito/{changehistory.py → change/history.py} +12 -14
  24. janito/change/operations.py +7 -0
  25. janito/change/parser.py +287 -0
  26. janito/change/play.py +54 -0
  27. janito/change/preview.py +82 -0
  28. janito/change/prompts.py +121 -0
  29. janito/change/test.py +0 -0
  30. janito/change/validator.py +269 -0
  31. janito/{changeviewer → change/viewer}/__init__.py +3 -4
  32. janito/change/viewer/content.py +66 -0
  33. janito/{changeviewer → change/viewer}/diff.py +19 -4
  34. janito/change/viewer/panels.py +533 -0
  35. janito/change/viewer/styling.py +114 -0
  36. janito/{changeviewer → change/viewer}/themes.py +3 -5
  37. janito/clear_statement_parser/clear_statement_format.txt +328 -0
  38. janito/clear_statement_parser/examples.txt +326 -0
  39. janito/clear_statement_parser/models.py +104 -0
  40. janito/clear_statement_parser/parser.py +496 -0
  41. janito/cli/base.py +30 -0
  42. janito/cli/commands.py +75 -40
  43. janito/cli/functions.py +19 -194
  44. janito/cli/history.py +61 -0
  45. janito/common.py +65 -8
  46. janito/config.py +70 -5
  47. janito/demo/__init__.py +4 -0
  48. janito/demo/data.py +13 -0
  49. janito/demo/mock_data.py +20 -0
  50. janito/demo/operations.py +45 -0
  51. janito/demo/runner.py +59 -0
  52. janito/demo/scenarios.py +32 -0
  53. janito/prompt.py +36 -0
  54. janito/qa.py +6 -14
  55. janito/search_replace/README.md +192 -0
  56. janito/search_replace/__init__.py +7 -0
  57. janito/search_replace/__main__.py +21 -0
  58. janito/search_replace/core.py +120 -0
  59. janito/search_replace/logger.py +35 -0
  60. janito/search_replace/parser.py +52 -0
  61. janito/search_replace/play.py +61 -0
  62. janito/search_replace/replacer.py +36 -0
  63. janito/search_replace/searcher.py +411 -0
  64. janito/search_replace/strategy_result.py +10 -0
  65. janito/shell/__init__.py +38 -0
  66. janito/shell/bus.py +31 -0
  67. janito/shell/commands.py +136 -0
  68. janito/shell/history.py +20 -0
  69. janito/shell/processor.py +32 -0
  70. janito/shell/prompt.py +48 -0
  71. janito/shell/registry.py +60 -0
  72. janito/tui/__init__.py +21 -0
  73. janito/tui/base.py +22 -0
  74. janito/tui/flows/__init__.py +5 -0
  75. janito/tui/flows/changes.py +65 -0
  76. janito/tui/flows/content.py +128 -0
  77. janito/tui/flows/selection.py +117 -0
  78. janito/tui/screens/__init__.py +3 -0
  79. janito/tui/screens/app.py +1 -0
  80. janito/workspace/__init__.py +6 -0
  81. janito/workspace/analysis.py +121 -0
  82. janito/workspace/show.py +141 -0
  83. janito/workspace/stats.py +43 -0
  84. janito/workspace/types.py +98 -0
  85. janito/workspace/workset.py +108 -0
  86. janito/workspace/workspace.py +114 -0
  87. janito-0.7.0.dist-info/METADATA +167 -0
  88. janito-0.7.0.dist-info/RECORD +96 -0
  89. {janito-0.5.0.dist-info → janito-0.7.0.dist-info}/WHEEL +1 -1
  90. janito/_contextparser.py +0 -113
  91. janito/analysis/display.py +0 -149
  92. janito/analysis/options.py +0 -112
  93. janito/change/applier.py +0 -269
  94. janito/change/content.py +0 -62
  95. janito/change/indentation.py +0 -33
  96. janito/change/position.py +0 -169
  97. janito/changeviewer/panels.py +0 -268
  98. janito/changeviewer/styling.py +0 -59
  99. janito/console/__init__.py +0 -3
  100. janito/console/commands.py +0 -112
  101. janito/console/core.py +0 -62
  102. janito/console/display.py +0 -157
  103. janito/fileparser.py +0 -334
  104. janito/prompts.py +0 -81
  105. janito/scan.py +0 -176
  106. janito/tests/test_fileparser.py +0 -26
  107. janito-0.5.0.dist-info/METADATA +0 -146
  108. janito-0.5.0.dist-info/RECORD +0 -45
  109. {janito-0.5.0.dist-info → janito-0.7.0.dist-info}/entry_points.txt +0 -0
  110. {janito-0.5.0.dist-info → janito-0.7.0.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,45 @@
1
+ from dataclasses import dataclass
2
+ from typing import List, Optional
3
+ from enum import Enum, auto
4
+ from pathlib import Path
5
+
6
+ class MockOperationType(Enum):
7
+ CREATE = auto()
8
+ MODIFY = auto()
9
+ REMOVE = auto()
10
+
11
+ @dataclass
12
+ class MockOperation:
13
+ """Base class for mock operations"""
14
+ operation_type: MockOperationType
15
+ name: str
16
+ reason: str
17
+
18
+ @dataclass
19
+ class CreateOperation(MockOperation):
20
+ """Operation for creating new files"""
21
+ content: str
22
+
23
+ def __init__(self, name: str, content: str, reason: str = "Create new file"):
24
+ super().__init__(MockOperationType.CREATE, name, reason)
25
+ self.content = content
26
+
27
+ @dataclass
28
+ class ModifyOperation(MockOperation):
29
+ """Operation for modifying existing files"""
30
+ content: str
31
+ original_content: str
32
+
33
+ def __init__(self, name: str, content: str, original_content: str, reason: str = "Modify existing file"):
34
+ super().__init__(MockOperationType.MODIFY, name, reason)
35
+ self.content = content
36
+ self.original_content = original_content
37
+
38
+ @dataclass
39
+ class RemoveOperation(MockOperation):
40
+ """Operation for removing files"""
41
+ original_content: Optional[str] = None
42
+
43
+ def __init__(self, name: str, original_content: Optional[str] = None, reason: str = "Remove file"):
44
+ super().__init__(MockOperationType.REMOVE, name, reason)
45
+ self.original_content = original_content
janito/demo/runner.py ADDED
@@ -0,0 +1,59 @@
1
+ from typing import List, Optional
2
+ from pathlib import Path
3
+ from rich.console import Console
4
+ from rich.panel import Panel
5
+ from rich.progress import Progress, SpinnerColumn, TextColumn
6
+ from .scenarios import DemoScenario
7
+ from .operations import MockOperationType
8
+ from ..change.viewer import preview_all_changes
9
+ from ..change.parser import FileChange, ChangeOperation
10
+
11
+ class DemoRunner:
12
+ def __init__(self):
13
+ self.console = Console()
14
+ self.scenarios: List[DemoScenario] = []
15
+
16
+ def add_scenario(self, scenario: DemoScenario) -> None:
17
+ """Add a demo scenario to the runner"""
18
+ self.scenarios.append(scenario)
19
+
20
+ def run_all(self) -> None:
21
+ """Run all registered demo scenarios"""
22
+ with Progress(
23
+ SpinnerColumn(),
24
+ TextColumn("[progress.description]{task.description}"),
25
+ console=self.console
26
+ ) as progress:
27
+ for scenario in self.scenarios:
28
+ task = progress.add_task(f"Running scenario: {scenario.name}")
29
+ self.preview_changes(scenario)
30
+ progress.update(task, completed=True)
31
+
32
+ def preview_changes(self, scenario: Optional[DemoScenario] = None) -> None:
33
+ """Preview changes for a scenario using change viewer"""
34
+ if scenario is None:
35
+ if not self.scenarios:
36
+ self.console.print("[yellow]No scenarios to preview[/yellow]")
37
+ return
38
+ scenario = self.scenarios[0]
39
+
40
+ # Convert mock changes to FileChange objects
41
+ changes = []
42
+ for mock in scenario.changes:
43
+ # Map mock operation type to ChangeOperation
44
+ operation_map = {
45
+ MockOperationType.CREATE: ChangeOperation.CREATE_FILE,
46
+ MockOperationType.MODIFY: ChangeOperation.MODIFY_FILE,
47
+ MockOperationType.REMOVE: ChangeOperation.REMOVE_FILE
48
+ }
49
+ operation = operation_map[mock.operation_type]
50
+ change = FileChange(
51
+ operation=operation,
52
+ name=Path(mock.name),
53
+ content=mock.content if hasattr(mock, 'content') else None,
54
+ original_content=mock.original_content if hasattr(mock, 'original_content') else None
55
+ )
56
+ changes.append(change)
57
+
58
+ # Show changes using change viewer
59
+ preview_all_changes(self.console, changes)
@@ -0,0 +1,32 @@
1
+ from dataclasses import dataclass
2
+ from typing import List, Dict, Optional
3
+ from rich.text import Text
4
+ from pathlib import Path
5
+ from .operations import MockOperation
6
+ from .mock_data import get_mock_changes
7
+
8
+ @dataclass
9
+ class DemoScenario:
10
+ name: str
11
+ description: str
12
+ changes: List[MockOperation]
13
+
14
+ def get_preview(self) -> Text:
15
+ """Get a preview of the changes"""
16
+ text = Text()
17
+ text.append(f"Description: {self.description}\n\n", style="cyan")
18
+
19
+ # Group changes by operation
20
+ by_operation = {}
21
+ for change in self.changes:
22
+ if change.operation not in by_operation:
23
+ by_operation[change.operation] = []
24
+ by_operation[change.operation].append(change)
25
+
26
+ # Show changes grouped by operation
27
+ for operation_type, changes in by_operation.items():
28
+ text.append(f"\n{operation_type.name.title()} Operations:\n", style="yellow")
29
+ for change in changes:
30
+ text.append(f"• {change.name}\n", style="white")
31
+
32
+ return text
janito/prompt.py ADDED
@@ -0,0 +1,36 @@
1
+ from .workspace import workset
2
+
3
+ SYSTEM_PROMPT = """I am Janito, your friendly software development buddy.
4
+
5
+ I help you with coding tasks while being clear and concise in my responses.
6
+
7
+ I have received the following workset for analysis:
8
+
9
+ {workset}
10
+
11
+ """
12
+
13
+ def build_system_prompt() -> dict:
14
+
15
+ system_prompt = [
16
+ {
17
+ "type": "text",
18
+ "text": "You Janito, an AI assistant tasked with analyzing worksets of code. You have received the following workset for analysis:",
19
+ }
20
+ ]
21
+
22
+ blocks = workset.get_cache_blocks()
23
+ for block in blocks:
24
+ if not block:
25
+ continue
26
+ block_content = ""
27
+ for file in block:
28
+ block_content += f'<file name="{file.name}"\n"'
29
+ block_content += f'<content>\n"{file.content}"\n</content>\n</file>\n'
30
+ system_prompt.append( {
31
+ "type": "text",
32
+ "text": block_content,
33
+ "cache_control": {"type": "ephemeral"}
34
+ }
35
+ )
36
+ return system_prompt
janito/qa.py CHANGED
@@ -1,34 +1,26 @@
1
1
  from rich.console import Console
2
2
  from rich.markdown import Markdown
3
3
  from rich.panel import Panel
4
- from rich.syntax import Syntax
5
- from rich.table import Table
6
4
  from rich.rule import Rule
7
- from janito.agents import AIAgent
8
5
  from janito.common import progress_send_message
9
- from janito.scan import show_content_stats
6
+ from janito.workspace import workset # Updated import
10
7
 
11
- QA_PROMPT = """Please provide a clear and concise answer to the following question about the codebase:
12
8
 
13
- Question: {question}
9
+ QA_PROMPT = """Please provide a clear and concise answer to the following question about the workset you received above.
14
10
 
15
- Current files:
16
- <files>
17
- {files_content}
18
- </files>
11
+ Question: {question}
19
12
 
20
13
  Focus on providing factual information and explanations. Do not suggest code changes.
21
14
  Format your response using markdown with appropriate headers and code blocks.
22
15
  """
23
16
 
24
- def ask_question(question: str, files_content: str) -> str:
17
+ def ask_question(question: str) -> str:
25
18
  """Process a question about the codebase and return the answer"""
26
- # Show content stats before processing
27
- show_content_stats(files_content)
19
+ # Ensure content is refreshed and analyzed
20
+ workset.show()
28
21
 
29
22
  prompt = QA_PROMPT.format(
30
23
  question=question,
31
- files_content=files_content
32
24
  )
33
25
  return progress_send_message(prompt)
34
26
 
@@ -0,0 +1,192 @@
1
+ # Search/Replace Module
2
+
3
+ A smart search and replace module that handles code indentation and provides debugging capabilities for failed searches.
4
+
5
+ ## Usage
6
+
7
+ ### As a Module
8
+
9
+ ```python
10
+ from janito.search_replace import SearchReplacer
11
+
12
+ # Basic search/replace
13
+ source_code = """
14
+ def hello():
15
+ print("Hello")
16
+ print("World")
17
+ """
18
+
19
+ search = """ print("Hello")
20
+ print("World")"""
21
+
22
+ replacement = """ print("Hi")
23
+ print("Universe")"""
24
+
25
+ replacer = SearchReplacer(source_code, search, replacement)
26
+ modified = replacer.replace()
27
+ ```
28
+
29
+ ### Command Line Debugging
30
+
31
+ When a search fails, a debug file is automatically created in `.janito/change_history/`. You can debug these files using:
32
+
33
+ ```bash
34
+ python -m janito.search_replace <debug_file>
35
+ ```
36
+
37
+ Example debug file format:
38
+ ```
39
+ Test: Failed search in example.py
40
+ ========================================
41
+ Original:
42
+ def hello():
43
+ print("Hello")
44
+ print("World")
45
+ ========================================
46
+ Search pattern:
47
+ print("Hi")
48
+ print("World")
49
+ ========================================
50
+ ```
51
+
52
+ ## Features
53
+
54
+ - Indentation-aware searching
55
+ - Multiple search strategies:
56
+ - ExactMatch: Matches content with exact indentation
57
+ - ExactContent: Matches content ignoring indentation
58
+ - IndentAware: Matches preserving relative indentation
59
+ - Debug mode with detailed indentation analysis
60
+ - File extension specific behavior
61
+ - Automatic debug file generation for failed searches
62
+
63
+ ## Search Strategies
64
+
65
+ The module employs multiple search strategies in a fallback chain to find the best match. Each strategy has specific behaviors and use cases:
66
+
67
+ ### ExactMatch Strategy
68
+ - Matches content exactly, including all whitespace and indentation
69
+ - Strictest matching strategy
70
+ - Best for precise replacements where indentation matters
71
+ - Example:
72
+ ```python
73
+ # Pattern:
74
+ def hello():
75
+ print("Hi")
76
+
77
+ # Will only match exact indentation:
78
+ def hello():
79
+ print("Hi")
80
+
81
+ # Won't match different indentation:
82
+ def hello():
83
+ print("Hi")
84
+ ```
85
+
86
+ ### IndentAware Strategy
87
+ - Preserves relative indentation between lines
88
+ - Allows different base indentation levels
89
+ - Ideal for matching code blocks inside functions/classes
90
+ - Example:
91
+ ```python
92
+ # Pattern:
93
+ print("Hello")
94
+ print("World")
95
+
96
+ # Matches with different base indentation:
97
+ def test():
98
+ print("Hello")
99
+ print("World")
100
+
101
+ def other():
102
+ print("Hello")
103
+ print("World")
104
+
105
+ # Won't match if relative indentation differs:
106
+ def wrong():
107
+ print("Hello")
108
+ print("World")
109
+ ```
110
+
111
+ ### ExactContent Strategy
112
+ - Ignores all indentation
113
+ - Matches content after stripping whitespace
114
+ - Useful for matching code regardless of formatting
115
+ - Example:
116
+ ```python
117
+ # Pattern:
118
+ print("Hello")
119
+ print("World")
120
+
121
+ # Matches any indentation:
122
+ print("Hello")
123
+ print("World")
124
+
125
+ # Also matches:
126
+ print("Hello")
127
+ print("World")
128
+ ```
129
+
130
+ ### ExactContentNoComments Strategy
131
+ - Ignores indentation, comments, and empty lines
132
+ - Most flexible strategy
133
+ - Perfect for matching code with varying comments/formatting
134
+ - Example:
135
+ ```python
136
+ # Pattern:
137
+ print("Hello") # greeting
138
+
139
+ print("World") # message
140
+
141
+ # Matches all these variations:
142
+ def test():
143
+ print("Hello") # different comment
144
+ # some comment
145
+ print("World")
146
+
147
+ # Or:
148
+ print("Hello") # no comment
149
+ print("World") # different note
150
+ ```
151
+
152
+ ### ExactContentNoCommentsFirstLinePartial Strategy
153
+ - Matches first line partially, ignoring comments
154
+ - Useful for finding code fragments or partial matches
155
+ - Example:
156
+ ```python
157
+ # Pattern:
158
+ print("Hello")
159
+
160
+ # Matches partial content:
161
+ message = print("Hello") + "extra"
162
+ result = print("Hello, World")
163
+ ```
164
+
165
+ ### Strategy Selection and File Types
166
+
167
+ Strategies are tried in the following order:
168
+ 1. ExactMatch
169
+ 2. IndentAware
170
+ 3. ExactContent
171
+ 4. ExactContentNoComments
172
+ 5. ExactContentNoCommentsFirstLinePartial
173
+
174
+ File extension specific behavior:
175
+
176
+ | File Type | Available Strategies |
177
+ |-----------|---------------------|
178
+ | Python (.py) | All strategies |
179
+ | Java (.java) | All strategies |
180
+ | JavaScript (.js) | All strategies |
181
+ | TypeScript (.ts) | All strategies |
182
+ | Other files | ExactMatch, ExactContent, ExactContentNoComments, ExactContentNoCommentsFirstLinePartial |
183
+
184
+ The module automatically selects the appropriate strategies based on the file type and tries them in order until a match is found.
185
+
186
+ ## Debug Output
187
+
188
+ When debugging failed searches, the module provides:
189
+ - Visual whitespace markers (· for spaces, → for tabs)
190
+ - Indentation analysis
191
+ - Line-by-line matching attempts
192
+ - Strategy selection information
@@ -0,0 +1,7 @@
1
+ from .core import SearchReplacer, PatternNotFoundException
2
+ from .searcher import Searcher
3
+ from .replacer import Replacer
4
+ from .parser import parse_test_file
5
+ from .strategy_result import StrategyResult
6
+
7
+ __all__ = ['SearchReplacer', 'PatternNotFoundException', 'Searcher', 'Replacer', 'parse_test_file', 'StrategyResult']
@@ -0,0 +1,21 @@
1
+ """Main entry point for search/replace module."""
2
+
3
+ from pathlib import Path
4
+ import sys
5
+ import argparse
6
+ from .play import play_file
7
+
8
+ def main():
9
+ parser = argparse.ArgumentParser(description="Debug search/replace patterns")
10
+ parser.add_argument('file', type=Path, help='Test file to analyze')
11
+
12
+ args = parser.parse_args()
13
+
14
+ if not args.file.exists():
15
+ print(f"Error: Test file not found: {args.file}")
16
+ sys.exit(1)
17
+
18
+ play_file(args.file)
19
+
20
+ if __name__ == "__main__":
21
+ main()
@@ -0,0 +1,120 @@
1
+ from typing import Optional, List
2
+ from pathlib import Path
3
+ import os
4
+ from datetime import datetime
5
+ from .logger import log_match, log_failure
6
+ from .searcher import Searcher
7
+ from .replacer import Replacer
8
+
9
+ class PatternNotFoundException(Exception):
10
+ """Raised when the search pattern is not found in the source code."""
11
+ pass
12
+
13
+ class SearchReplacer:
14
+ """Handles indentation-aware search and replace operations on Python source code."""
15
+
16
+ def __init__(self, source_code: str, search_pattern: str, replacement: Optional[str] = None,
17
+ file_ext: Optional[str] = None, debug: bool = False):
18
+ """Initialize with source code and patterns."""
19
+ self.source_code = source_code.rstrip()
20
+ self.search_pattern = search_pattern.rstrip()
21
+ self.replacement = replacement.rstrip() if replacement else None
22
+ self.file_ext = file_ext.lower() if file_ext else None
23
+ self.pattern_found = False
24
+ self.searcher = Searcher(debug=debug)
25
+ self.replacer = Replacer(debug=debug)
26
+
27
+ # Initialize pattern base indent
28
+ first_line, _ = self.searcher.get_first_non_empty_line(self.search_pattern)
29
+ self.pattern_base_indent = len(self.searcher.get_indentation(first_line)) if first_line else 0
30
+
31
+ def find_pattern(self) -> bool:
32
+ """Search for pattern with indentation awareness."""
33
+ try:
34
+ source_lines = self.source_code.splitlines()
35
+ search_first, _ = self.searcher.get_first_non_empty_line(self.search_pattern)
36
+ search_indent = self.searcher.get_indentation(search_first)
37
+ normalized_pattern = self.searcher.normalize_pattern(self.search_pattern, search_indent)
38
+ matches = self._find_matches(source_lines, normalized_pattern)
39
+ return bool(self.searcher._find_best_match_position(matches, source_lines, self.pattern_base_indent))
40
+ except Exception:
41
+ return False
42
+
43
+ def replace(self) -> str:
44
+ """Perform the search and replace operation."""
45
+ if self.replacement is None:
46
+ if not self.find_pattern():
47
+ raise PatternNotFoundException("Pattern not found")
48
+ return self.source_code
49
+
50
+ source_lines = self.source_code.splitlines()
51
+ search_first, _ = self.searcher.get_first_non_empty_line(self.search_pattern)
52
+ search_indent = self.searcher.get_indentation(search_first)
53
+ normalized_pattern = self.searcher.normalize_pattern(self.search_pattern, search_indent)
54
+
55
+ matches = self._find_matches(source_lines, normalized_pattern)
56
+ best_pos = self.searcher._find_best_match_position(matches, source_lines, self.pattern_base_indent)
57
+
58
+ if best_pos is None:
59
+ # Log failed match if not in debug mode
60
+ if not self.searcher.debug_mode:
61
+ log_failure(self.file_ext)
62
+ raise PatternNotFoundException("Pattern not found")
63
+
64
+ if self.searcher.debug_mode:
65
+ pattern_lines = len(normalized_pattern.splitlines())
66
+ replacement_lines = len(self.replacement.splitlines()) if self.replacement else 0
67
+ print(f"\n[DEBUG] Replacing {pattern_lines} lines with {replacement_lines} lines")
68
+ context_start = max(0, best_pos - 2)
69
+ context_end = min(len(source_lines), best_pos + len(normalized_pattern.splitlines()) + 2)
70
+ print("\n[DEBUG] Context before replacement:")
71
+ for i in range(context_start, context_end):
72
+ prefix = ">>> " if context_start <= i < best_pos + len(normalized_pattern.splitlines()) else " "
73
+ print(f"[DEBUG] {prefix}Line {i + 1}: {source_lines[i]}")
74
+
75
+ result = self._apply_replacement(source_lines, best_pos, normalized_pattern)
76
+
77
+ if self.searcher.debug_mode:
78
+ print("\n[DEBUG] Context after replacement:")
79
+ result_lines = result.splitlines()
80
+ for i in range(context_start, context_end):
81
+ prefix = ">>> " if context_start <= i < best_pos + len(self.replacement.splitlines()) else " "
82
+ print(f"[DEBUG] {prefix}Line {i + 1}: {result_lines[i]}")
83
+
84
+ return result
85
+
86
+ def _find_matches(self, source_lines, normalized_pattern):
87
+ """Find all possible matches in source."""
88
+ pattern_lines = normalized_pattern.splitlines()
89
+ return self.searcher._find_matches(source_lines, pattern_lines, self.file_ext)
90
+
91
+ def _apply_replacement(self, source_lines, match_pos, normalized_pattern):
92
+ """Apply replacement at the matched position."""
93
+ result_lines = []
94
+ i = 0
95
+ while i < len(source_lines):
96
+ if i == match_pos:
97
+ self.pattern_found = True
98
+ # Log successful match if not in debug mode
99
+ # get the
100
+ if not self.searcher.debug_mode:
101
+ log_match("Strategy", self.file_ext)
102
+ match_indent = self.searcher.get_indentation(source_lines[i])
103
+ replacement_lines = self.replacer.create_indented_replacement(
104
+ match_indent, self.search_pattern, self.replacement
105
+ )
106
+ result_lines.extend(replacement_lines)
107
+ i += len(normalized_pattern.splitlines())
108
+ else:
109
+ result_lines.append(source_lines[i])
110
+ i += 1
111
+ return '\n'.join(result_lines)
112
+
113
+ def _try_match_at_position(self, pos, source_lines, normalized_pattern):
114
+ """Check if pattern matches at given position."""
115
+ pattern_lines = normalized_pattern.splitlines()
116
+ strategies = self.searcher.get_strategies(self.file_ext)
117
+ result = self.searcher.try_match_with_strategies(source_lines, pattern_lines, pos, strategies)
118
+ if result.success and not self.searcher.debug_mode:
119
+ log_match(result.strategy_name, self.file_ext)
120
+ return result.success
@@ -0,0 +1,35 @@
1
+ import logging
2
+ from datetime import datetime
3
+ from pathlib import Path
4
+ from typing import Optional
5
+
6
+ # Configure logging
7
+ logger = logging.getLogger("janito.search_replace")
8
+ logger.setLevel(logging.INFO)
9
+
10
+ # Create formatter
11
+ formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
12
+
13
+ # Create file handler
14
+ def setup_file_handler():
15
+ """Setup file handler for logging if .janito directory exists"""
16
+ if Path(".janito").exists():
17
+ fh = logging.FileHandler(".janito/search_logs.txt")
18
+ fh.setFormatter(formatter)
19
+ logger.addHandler(fh)
20
+
21
+ setup_file_handler()
22
+
23
+ def log_match(strategy_name: str, file_type: Optional[str] = None):
24
+ """Log successful match with strategy info"""
25
+ msg = f"Match found using {strategy_name}"
26
+ if file_type:
27
+ msg += f" for file type {file_type}"
28
+ logger.info(msg)
29
+
30
+ def log_failure(file_type: Optional[str] = None):
31
+ """Log failed match attempt"""
32
+ msg = "Failed to match pattern"
33
+ if file_type:
34
+ msg += f" for file type {file_type}"
35
+ logger.warning(msg)
@@ -0,0 +1,52 @@
1
+ from pathlib import Path
2
+ from typing import List, Dict
3
+
4
+ def parse_test_file(filepath: Path) -> List[Dict]:
5
+ """Parse a test file containing test cases. Replacement section is optional."""
6
+ test_cases = []
7
+ current_test = {}
8
+ current_section = None
9
+ current_content = []
10
+
11
+ try:
12
+ content = filepath.read_text()
13
+ lines = content.splitlines()
14
+
15
+ for line in lines:
16
+ if line.startswith("Test: "):
17
+ if current_test:
18
+ if current_section and current_content:
19
+ current_test[current_section] = "\n".join(current_content)
20
+ test_cases.append(current_test)
21
+ current_test = {"name": line[6:].strip(), "expect_success": True}
22
+ current_section = None
23
+ current_content = []
24
+ elif line.startswith("Original:"):
25
+ if current_section and current_content:
26
+ current_test[current_section] = "\n".join(current_content)
27
+ current_section = "source"
28
+ current_content = []
29
+ elif line.startswith("Search pattern:"):
30
+ if current_section and current_content:
31
+ current_test[current_section] = "\n".join(current_content)
32
+ current_section = "search"
33
+ current_content = []
34
+ elif line.startswith("Replacement:"):
35
+ if current_section and current_content:
36
+ current_test[current_section] = "\n".join(current_content)
37
+ current_section = "replacement"
38
+ current_content = []
39
+ elif not line.startswith("="): # Skip separator lines
40
+ if current_section:
41
+ current_content.append(line)
42
+
43
+ # Add last test case
44
+ if current_test:
45
+ if current_section and current_content:
46
+ current_test[current_section] = "\n".join(current_content)
47
+ test_cases.append(current_test)
48
+
49
+ return test_cases
50
+ except Exception as e:
51
+ print(f"Error parsing test file: {e}")
52
+ return []