janito 0.5.0__py3-none-any.whl → 0.6.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 +0 -47
  2. janito/__main__.py +96 -15
  3. janito/agents/__init__.py +2 -8
  4. janito/agents/claudeai.py +3 -12
  5. janito/change/__init__.py +29 -16
  6. janito/change/__main__.py +0 -0
  7. janito/{analysis → change/analysis}/__init__.py +5 -15
  8. janito/change/analysis/__main__.py +7 -0
  9. janito/change/analysis/analyze.py +61 -0
  10. janito/change/analysis/formatting.py +78 -0
  11. janito/change/analysis/options.py +81 -0
  12. janito/{analysis → change/analysis}/prompts.py +35 -12
  13. janito/change/analysis/view/__init__.py +9 -0
  14. janito/change/analysis/view/terminal.py +171 -0
  15. janito/change/applier/__init__.py +5 -0
  16. janito/change/applier/file.py +58 -0
  17. janito/change/applier/main.py +156 -0
  18. janito/change/applier/text.py +245 -0
  19. janito/change/applier/workspace_dir.py +58 -0
  20. janito/change/core.py +131 -0
  21. janito/{changehistory.py → change/history.py} +12 -14
  22. janito/change/operations.py +7 -0
  23. janito/change/parser.py +289 -0
  24. janito/change/play.py +54 -0
  25. janito/change/preview.py +82 -0
  26. janito/change/prompts.py +126 -0
  27. janito/change/test.py +0 -0
  28. janito/change/validator.py +251 -0
  29. janito/{changeviewer → change/viewer}/__init__.py +3 -4
  30. janito/change/viewer/content.py +66 -0
  31. janito/{changeviewer → change/viewer}/diff.py +19 -4
  32. janito/change/viewer/pager.py +56 -0
  33. janito/change/viewer/panels.py +555 -0
  34. janito/change/viewer/styling.py +103 -0
  35. janito/{changeviewer → change/viewer}/themes.py +3 -5
  36. janito/clear_statement_parser/clear_statement_format.txt +328 -0
  37. janito/clear_statement_parser/examples.txt +326 -0
  38. janito/clear_statement_parser/models.py +104 -0
  39. janito/clear_statement_parser/parser.py +496 -0
  40. janito/cli/base.py +30 -0
  41. janito/cli/commands.py +30 -38
  42. janito/cli/functions.py +19 -194
  43. janito/cli/handlers/ask.py +22 -0
  44. janito/cli/handlers/demo.py +22 -0
  45. janito/cli/handlers/request.py +24 -0
  46. janito/cli/handlers/scan.py +9 -0
  47. janito/cli/history.py +61 -0
  48. janito/common.py +34 -3
  49. janito/config.py +71 -6
  50. janito/demo/__init__.py +4 -0
  51. janito/demo/data.py +13 -0
  52. janito/demo/mock_data.py +20 -0
  53. janito/demo/operations.py +45 -0
  54. janito/demo/runner.py +59 -0
  55. janito/demo/scenarios.py +32 -0
  56. janito/prompts.py +1 -80
  57. janito/qa.py +4 -3
  58. janito/search_replace/README.md +146 -0
  59. janito/search_replace/__init__.py +6 -0
  60. janito/search_replace/__main__.py +21 -0
  61. janito/search_replace/core.py +119 -0
  62. janito/search_replace/parser.py +52 -0
  63. janito/search_replace/play.py +61 -0
  64. janito/search_replace/replacer.py +36 -0
  65. janito/search_replace/searcher.py +299 -0
  66. janito/shell/__init__.py +39 -0
  67. janito/shell/bus.py +31 -0
  68. janito/shell/commands.py +195 -0
  69. janito/shell/handlers.py +122 -0
  70. janito/shell/history.py +20 -0
  71. janito/shell/processor.py +52 -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 +7 -0
  81. janito/workspace/analysis.py +121 -0
  82. janito/workspace/manager.py +48 -0
  83. janito/workspace/scan.py +232 -0
  84. janito-0.6.0.dist-info/METADATA +185 -0
  85. janito-0.6.0.dist-info/RECORD +95 -0
  86. {janito-0.5.0.dist-info → janito-0.6.0.dist-info}/WHEEL +1 -1
  87. janito/_contextparser.py +0 -113
  88. janito/analysis/display.py +0 -149
  89. janito/analysis/options.py +0 -112
  90. janito/change/applier.py +0 -269
  91. janito/change/content.py +0 -62
  92. janito/change/indentation.py +0 -33
  93. janito/change/position.py +0 -169
  94. janito/changeviewer/panels.py +0 -268
  95. janito/changeviewer/styling.py +0 -59
  96. janito/console/__init__.py +0 -3
  97. janito/console/commands.py +0 -112
  98. janito/console/core.py +0 -62
  99. janito/console/display.py +0 -157
  100. janito/fileparser.py +0 -334
  101. janito/scan.py +0 -176
  102. janito/tests/test_fileparser.py +0 -26
  103. janito-0.5.0.dist-info/METADATA +0 -146
  104. janito-0.5.0.dist-info/RECORD +0 -45
  105. {janito-0.5.0.dist-info → janito-0.6.0.dist-info}/entry_points.txt +0 -0
  106. {janito-0.5.0.dist-info → janito-0.6.0.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,171 @@
1
+ """Terminal UI components for analysis display."""
2
+
3
+ from typing import Dict, List, Optional
4
+ from rich.console import Console
5
+ from rich.columns import Columns
6
+ from rich.text import Text
7
+ from rich.panel import Panel
8
+ from rich.rule import Rule
9
+ from rich.padding import Padding
10
+ from rich.prompt import Prompt
11
+ from rich import box
12
+ from pathlib import Path
13
+
14
+ from ..options import AnalysisOption
15
+ from ..formatting import (
16
+ COLUMN_SPACING,
17
+ MIN_PANEL_WIDTH,
18
+ SECTION_PADDING,
19
+ STATUS_COLORS,
20
+ STRUCTURAL_COLORS,
21
+ create_header,
22
+ create_section_header,
23
+ format_file_path
24
+ )
25
+
26
+ def prompt_user(message: str, choices: List[str] = None) -> str:
27
+ """Display a prominent user prompt with optional choices"""
28
+ console = Console()
29
+ term_width = console.width or 80
30
+ console.print()
31
+ console.print(Rule(" User Input Required ", style="bold cyan", align="center"))
32
+
33
+ if choices:
34
+ choice_text = f"[cyan]Options: {', '.join(choices)}[/cyan]"
35
+ console.print(Panel(choice_text, box=box.ROUNDED, justify="center"))
36
+
37
+ padding = (term_width - len(message)) // 2
38
+ padded_message = " " * padding + message
39
+ return Prompt.ask(f"[bold cyan]{padded_message}[/bold cyan]")
40
+
41
+ def get_option_selection() -> str:
42
+ """Get user input for option selection with modify option"""
43
+ console = Console()
44
+ term_width = console.width or 80
45
+ message = "Enter option letter or 'M' to modify request"
46
+ padding = (term_width - len(message)) // 2
47
+ padded_message = " " * padding + message
48
+
49
+ console.print(f"\n[cyan]{padded_message}[/cyan]")
50
+ while True:
51
+ letter = prompt_user("Select option").strip().upper()
52
+ if letter == 'M' or (letter.isalpha() and len(letter) == 1):
53
+ return letter
54
+
55
+ error_msg = "Please enter a valid letter or 'M'"
56
+ error_padding = (term_width - len(error_msg)) // 2
57
+ padded_error = " " * error_padding + error_msg
58
+ console.print(f"[red]{padded_error}[/red]")
59
+
60
+ def _create_option_content(option: AnalysisOption) -> Text:
61
+ """Create rich formatted content for a single option."""
62
+ content = Text()
63
+ content.append("\n")
64
+
65
+ header = create_header(f"Option {option.letter} - {option.summary}")
66
+ content.append(header)
67
+ content.append("\n")
68
+
69
+ if option.description_items:
70
+ for item in option.description_items:
71
+ content.append("• ", style="cyan")
72
+ content.append(f"{item}\n")
73
+ content.append("\n")
74
+
75
+ # Add consistent padding before file list
76
+ content.append("\n" * 2)
77
+
78
+ if option.affected_files:
79
+ files = {status: [] for status in ['New', 'Modified', 'Removed']}
80
+ for file in option.affected_files:
81
+ if '(new)' in file.lower():
82
+ files['New'].append(file)
83
+ elif '(removed)' in file.lower():
84
+ files['Removed'].append(file)
85
+ else:
86
+ files['Modified'].append(file)
87
+
88
+ for status, status_files in files.items():
89
+ if status_files:
90
+ content.append(create_section_header(f"{status} Files"))
91
+ content.append("\n")
92
+ sorted_files = sorted(status_files)
93
+ prev_path = None
94
+ seen_dirs = {}
95
+ for file in sorted_files:
96
+ path = option.get_clean_path(file)
97
+ current_parts = Path(path).parts
98
+ parent_dir = str(Path(path).parent)
99
+
100
+ if parent_dir != '.':
101
+ is_repeated = parent_dir in seen_dirs
102
+ if not is_repeated:
103
+ content.append(parent_dir, style=STRUCTURAL_COLORS['directory'])
104
+ content.append("/", style=STRUCTURAL_COLORS['separator'])
105
+ seen_dirs[parent_dir] = True
106
+ else:
107
+ padding = " " * (len(parent_dir) - 1)
108
+ content.append(padding)
109
+ content.append("↑ ", style=STRUCTURAL_COLORS['repeat'])
110
+ content.append("/", style=STRUCTURAL_COLORS['separator'])
111
+ content.append(current_parts[-1], style=STATUS_COLORS[status.lower()])
112
+ else:
113
+ content.append(current_parts[-1], style=STATUS_COLORS[status.lower()])
114
+ content.append("\n")
115
+ content.append("\n")
116
+
117
+ content.append("\n")
118
+
119
+ return content
120
+
121
+ def create_columns_layout(options_content: List[Text], term_width: int) -> Columns:
122
+ """Create a columns layout with consistent spacing."""
123
+ num_columns = len(options_content)
124
+ spacing = COLUMN_SPACING * (num_columns - 1)
125
+ safety_margin = 4 + 2
126
+
127
+ usable_width = term_width - spacing - safety_margin
128
+ column_width = max((usable_width // num_columns), MIN_PANEL_WIDTH)
129
+
130
+ rendered_columns = [
131
+ Padding(content, (0, COLUMN_SPACING // 2))
132
+ for content in options_content
133
+ ]
134
+
135
+ return Columns(
136
+ rendered_columns,
137
+ equal=True,
138
+ expand=True,
139
+ width=column_width,
140
+ align="left",
141
+ padding=(0, 0),
142
+ )
143
+
144
+ def format_analysis(analysis: str, raw: bool = False) -> None:
145
+ """Format and display the analysis output."""
146
+ from ..options import parse_analysis_options
147
+
148
+ console = Console()
149
+ term_width = console.width or 100
150
+
151
+ if raw:
152
+ console.print(analysis)
153
+ return
154
+
155
+ options = parse_analysis_options(analysis)
156
+ if not options:
157
+ console.print("\n[yellow]Warning: No valid options found in response.[/yellow]\n")
158
+ console.print(analysis)
159
+ return
160
+
161
+ columns_content = [_create_option_content(options[letter])
162
+ for letter in sorted(options.keys())]
163
+
164
+ columns = create_columns_layout(columns_content, term_width)
165
+
166
+ console.print("\n")
167
+ console.print(Text("Analysis Options", style="bold cyan"))
168
+ console.print(Text("─" * term_width, style="cyan dim"))
169
+ console.print(columns)
170
+ console.print(Text("─" * term_width, style="cyan dim"))
171
+ console.print("\n")
@@ -0,0 +1,5 @@
1
+ from .file import FileChangeApplier
2
+ from .text import TextChangeApplier
3
+ from .workspace_dir import apply_changes
4
+
5
+ __all__ = ['FileChangeApplier', 'TextChangeApplier', 'apply_changes']
@@ -0,0 +1,58 @@
1
+ from pathlib import Path
2
+ from typing import Tuple, Optional
3
+ from rich.console import Console
4
+ from ..parser import FileChange, ChangeOperation
5
+
6
+ class FileChangeApplier:
7
+ def __init__(self, preview_dir: Path, console: Console = None):
8
+ self.preview_dir = preview_dir
9
+ self.console = console or Console()
10
+
11
+ def apply_file_operation(self, change: FileChange) -> Tuple[bool, Optional[str]]:
12
+ """Apply a file operation (create/replace/remove/rename/move)
13
+ Returns: (success, error_message)"""
14
+ path = self.preview_dir / change.name
15
+ path.parent.mkdir(parents=True, exist_ok=True)
16
+
17
+ # Store original content before any changes
18
+ if path.exists():
19
+ change.original_content = path.read_text()
20
+
21
+ if change.operation == ChangeOperation.REMOVE_FILE:
22
+ return self._handle_remove(path)
23
+ elif change.operation in (ChangeOperation.CREATE_FILE, ChangeOperation.REPLACE_FILE):
24
+ return self._handle_create_replace(path, change)
25
+ elif change.operation in (ChangeOperation.RENAME_FILE, ChangeOperation.MOVE_FILE):
26
+ return self._handle_move(path, change)
27
+
28
+ return False, f"Unsupported operation: {change.operation}"
29
+
30
+ def _handle_remove(self, path: Path) -> Tuple[bool, Optional[str]]:
31
+ """Handle file removal"""
32
+ if path.exists():
33
+ path.unlink()
34
+ return True, None
35
+
36
+ def _handle_create_replace(self, path: Path, change: FileChange) -> Tuple[bool, Optional[str]]:
37
+ """Handle file creation or replacement"""
38
+ if change.operation == ChangeOperation.CREATE_FILE and path.exists():
39
+ return False, f"Cannot create file {path} - already exists"
40
+
41
+ if change.content is not None:
42
+ path.write_text(change.content)
43
+ return True, None
44
+
45
+ return False, "No content provided for create/replace operation"
46
+
47
+ def _handle_move(self, path: Path, change: FileChange) -> Tuple[bool, Optional[str]]:
48
+ """Handle file move/rename operations"""
49
+ if not path.exists():
50
+ return False, f"Cannot move/rename non-existent file {path}"
51
+
52
+ if not change.target:
53
+ return False, "No target path provided for move/rename operation"
54
+
55
+ new_path = self.preview_dir / change.target
56
+ new_path.parent.mkdir(parents=True, exist_ok=True)
57
+ path.rename(new_path)
58
+ return True, None
@@ -0,0 +1,156 @@
1
+ """
2
+ Applies file changes to preview directory and runs tests
3
+
4
+ The following situations should result in error:
5
+ - Creating a file that already exists
6
+ - Replace operation on a non-existent file
7
+ - Rename operation on a non-existent file
8
+ - Modify operation with search text not found
9
+ - No changes applied to a file
10
+ """
11
+
12
+ from pathlib import Path
13
+ from typing import Tuple, Optional, List, Set
14
+ from rich.console import Console
15
+ from rich.panel import Panel
16
+ from rich import box
17
+ import subprocess
18
+ from ..validator import validate_python_syntax
19
+ from .workspace_dir import apply_changes as apply_to_workspace_dir_impl
20
+ from janito.config import config
21
+ from .file import FileChangeApplier
22
+ from .text import TextChangeApplier
23
+ from ..parser import FileChange, ChangeOperation
24
+ from ..validator import validate_all_changes
25
+
26
+
27
+ class ChangeApplier:
28
+ """Handles applying changes to files."""
29
+
30
+ def __init__(self, preview_dir: Path, debug: bool = False):
31
+ self.preview_dir = preview_dir
32
+ self.debug = debug
33
+ self.console = Console()
34
+ self.file_applier = FileChangeApplier(preview_dir, self.console)
35
+ self.text_applier = TextChangeApplier(self.console)
36
+
37
+ def run_test_command(self, test_cmd: str) -> Tuple[bool, str, Optional[str]]:
38
+ """Run test command in preview directory.
39
+ Returns (success, output, error)"""
40
+ try:
41
+ result = subprocess.run(
42
+ test_cmd,
43
+ shell=True,
44
+ cwd=self.preview_dir,
45
+ capture_output=True,
46
+ text=True,
47
+ timeout=300 # 5 minute timeout
48
+ )
49
+ return (
50
+ result.returncode == 0,
51
+ result.stdout,
52
+ result.stderr if result.returncode != 0 else None
53
+ )
54
+ except subprocess.TimeoutExpired:
55
+ return False, "", "Test command timed out after 5 minutes"
56
+ except Exception as e:
57
+ return False, "", f"Error running test: {str(e)}"
58
+
59
+ def apply_changes(self, changes: List[FileChange], debug: bool = None) -> tuple[bool, Set[Path]]:
60
+ """Apply changes in preview directory, runs tests if specified.
61
+ Returns (success, modified_files)"""
62
+ debug = debug if debug is not None else self.debug
63
+ console = Console()
64
+
65
+ # Validate all changes using consolidated validator
66
+ is_valid, error = validate_all_changes(changes, set(Path(c.name) for c in changes))
67
+ if not is_valid:
68
+ console.print(f"\n[red]{error}[/red]")
69
+ return False, set()
70
+
71
+ # Track modified files and apply changes
72
+ modified_files: Set[Path] = set()
73
+ for change in changes:
74
+ if config.verbose:
75
+ console.print(f"[dim]Previewing changes for {change.name}...[/dim]")
76
+ success, error = self.apply_single_change(change, debug)
77
+ if not success:
78
+ console.print(f"\n[red]Error previewing {change.name}: {error}[/red]")
79
+ return False, modified_files
80
+ if not change.operation == 'remove_file':
81
+ modified_files.add(change.name)
82
+ elif change.operation == 'rename_file':
83
+ modified_files.add(change.target)
84
+
85
+ # Validate Python syntax (skip deleted and moved files)
86
+ python_files = {f for f in modified_files if f.suffix == '.py'}
87
+
88
+ for change in changes:
89
+ if change.operation == ChangeOperation.REMOVE_FILE:
90
+ python_files.discard(change.name) # Skip validation for deleted files
91
+ elif change.operation in (ChangeOperation.RENAME_FILE, ChangeOperation.MOVE_FILE):
92
+ python_files.discard(change.source) # Skip validation for moved/renamed sources
93
+
94
+ for path in python_files:
95
+ preview_path = self.preview_dir / path
96
+ is_valid, error_msg = validate_python_syntax(preview_path.read_text(), preview_path)
97
+ if not is_valid:
98
+ console.print(f"\n[red]Python syntax validation failed for {path}:[/red]")
99
+ console.print(f"[red]{error_msg}[/red]")
100
+ return False, modified_files
101
+
102
+ # Show success message with syntax validation status
103
+ console.print("\n[cyan]Changes applied successfully.[/cyan]")
104
+ if python_files:
105
+ console.print(f"[green]✓ Python syntax validated for {len(python_files)} file(s)[/green]")
106
+
107
+ # Run tests if specified
108
+ if config.test_cmd:
109
+ console.print(f"\n[cyan]Testing changes in preview directory:[/cyan] {config.test_cmd}")
110
+ success, output, error = self.run_test_command(config.test_cmd)
111
+ if output:
112
+ console.print("\n[bold]Test Output:[/bold]")
113
+ console.print(Panel(output, box=box.ROUNDED))
114
+ if not success:
115
+ console.print("\n[red bold]Tests failed in preview.[/red bold]")
116
+ if error:
117
+ console.print(Panel(error, title="Error", border_style="red"))
118
+ return False, modified_files
119
+
120
+ return True, modified_files
121
+
122
+ def apply_single_change(self, change: FileChange, debug: bool) -> Tuple[bool, Optional[str]]:
123
+ """Apply a single file change to preview directory"""
124
+ path = self.preview_dir / change.name # Changed back from path to name
125
+
126
+ # Handle file operations first
127
+ if change.operation != ChangeOperation.MODIFY_FILE:
128
+ return self.file_applier.apply_file_operation(change)
129
+
130
+ # Handle text modifications
131
+ if not path.exists():
132
+ original_path = Path(change.name) # Changed back from path to name
133
+ if not original_path.exists():
134
+ return False, f"Original file not found: {original_path}"
135
+ if self.console:
136
+ self.console.print(f"[dim]Copying {original_path} to preview directory {path}[/dim]")
137
+ path.write_text(original_path.read_text())
138
+
139
+ current_content = path.read_text()
140
+ success, modified_content, error = self.text_applier.apply_modifications(
141
+ current_content,
142
+ change.text_changes,
143
+ path,
144
+ debug
145
+ )
146
+
147
+ if not success:
148
+ return False, error
149
+
150
+ path.write_text(modified_content)
151
+ return True, None
152
+
153
+ def apply_to_workspace_dir(self, changes: List[FileChange], debug: bool = None) -> bool:
154
+ """Apply changes from preview to working directory"""
155
+ debug = debug if debug is not None else self.debug
156
+ return apply_to_workspace_dir_impl(changes, self.preview_dir, Console())
@@ -0,0 +1,245 @@
1
+ from typing import Tuple, List, Optional
2
+ from rich.console import Console
3
+ from pathlib import Path
4
+ from datetime import datetime
5
+ from ..parser import TextChange
6
+ from janito.config import config
7
+ from ...clear_statement_parser.parser import StatementParser
8
+ from ...search_replace import SearchReplacer, PatternNotFoundException, Searcher
9
+
10
+ class TextFindDebugger:
11
+ def __init__(self, console: Console):
12
+ self.console = console
13
+ self.find_count = 0
14
+
15
+ def _visualize_whitespace(self, text: str) -> str:
16
+ """Convert whitespace characters to visible markers"""
17
+ return text.replace(' ', '·').replace('\t', '→')
18
+
19
+ def debug_find(self, content: str, search: str) -> List[int]:
20
+ """Debug find operation by showing numbered matches"""
21
+ self.find_count += 1
22
+ matches = []
23
+
24
+ # Show search pattern
25
+ self.console.print(f"\n[cyan]Find #{self.find_count} search pattern:[/cyan]")
26
+ for i, line in enumerate(search.splitlines()):
27
+ self.console.print(f"[dim]{i+1:3d} | {self._visualize_whitespace(line)}[/dim]")
28
+
29
+ # Process content line by line
30
+ lines = content.splitlines()
31
+ for i, line in enumerate(lines):
32
+ if search.strip() in line.strip():
33
+ matches.append(i + 1)
34
+ self.console.print(f"[green]Match at line {i+1}:[/green] {self._visualize_whitespace(line)}")
35
+
36
+ if not matches:
37
+ self.console.print("[yellow]No matches found[/yellow]")
38
+
39
+ return matches
40
+
41
+ class TextChangeApplier:
42
+ def __init__(self, console: Optional[Console] = None):
43
+ self.console = console or Console()
44
+ self.debugger = TextFindDebugger(self.console)
45
+ self.parser = StatementParser()
46
+ self.searcher = Searcher()
47
+
48
+ def _get_last_line_indent(self, content: str) -> str:
49
+ """Extract indentation from the last non-empty line."""
50
+ lines = content.splitlines()
51
+ for line in reversed(lines):
52
+ if line.strip():
53
+ return self.searcher.get_indentation(line)
54
+ return ""
55
+
56
+ def _validate_operation(self, mod: TextChange) -> Tuple[bool, Optional[str]]:
57
+ """Validate text operation type and parameters
58
+ Returns (is_valid, error_message)"""
59
+ if mod.is_append:
60
+ if not mod.replace_content:
61
+ return False, "Append operation requires content"
62
+ return True, None
63
+
64
+ # For delete operations
65
+ if mod.is_delete:
66
+ if not mod.search_content:
67
+ return False, "Delete operation requires search content"
68
+ return True, None
69
+
70
+ # For replace operations
71
+ if not mod.search_content:
72
+ return False, "Replace operation requires search content"
73
+ if mod.replace_content is None:
74
+ return False, "Replace operation requires replacement content"
75
+
76
+ return True, None
77
+
78
+ def apply_modifications(self, content: str, changes: List[TextChange], target_path: Path, debug: bool) -> Tuple[bool, str, Optional[str]]:
79
+ """Apply text modifications to content"""
80
+ modified = content
81
+ any_changes = False
82
+ target_path = target_path.resolve()
83
+ file_ext = target_path.suffix # Get file extension including the dot
84
+
85
+ for mod in changes:
86
+
87
+ # Validate operation
88
+ is_valid, error = self._validate_operation(mod)
89
+ if not is_valid:
90
+ return False, content, f"Invalid text operation for {target_path}: {error}"
91
+
92
+ try:
93
+ # Handle append operations
94
+ if not mod.search_content:
95
+ if mod.replace_content:
96
+ modified = self._append_content(modified, mod.replace_content)
97
+ any_changes = True
98
+ continue
99
+
100
+ # Handle delete operations (either explicit or via empty replacement)
101
+ if mod.is_delete or (mod.replace_content == "" and mod.search_content):
102
+ replacer = SearchReplacer(modified, mod.search_content, "", file_ext, debug=debug)
103
+
104
+ modified = replacer.replace()
105
+ any_changes = True
106
+ continue
107
+
108
+ # Handle search and replace
109
+ if debug:
110
+ print("************************** before replace")
111
+ print(modified)
112
+ print("****************************")
113
+ replacer = SearchReplacer(modified, mod.search_content, mod.replace_content, file_ext, debug=debug)
114
+ modified = replacer.replace()
115
+ if debug:
116
+ print("************************** after replace")
117
+ print(modified)
118
+ print("****************************")
119
+ any_changes = True
120
+
121
+ except PatternNotFoundException:
122
+ if config.debug:
123
+ self.debug_failed_finds(mod.search_content, modified, str(target_path))
124
+ return False, content, self._handle_failed_search(target_path, mod.search_content, modified)
125
+
126
+ return (True, modified, None) if any_changes else (False, content, "No changes were applied")
127
+
128
+ def _append_content(self, content: str, new_content: str) -> str:
129
+ """Append content with proper indentation matching.
130
+
131
+ The indentation rules are:
132
+ 1. If new content starts with empty lines, preserve original indentation
133
+ 2. Otherwise, use indentation from the last non-empty line of existing content as base
134
+ 3. Preserves relative indentation between lines in new content
135
+ 4. Adjusts indentation if new content would go into negative space
136
+ """
137
+ if not content.endswith('\n'):
138
+ content += '\n'
139
+
140
+ # Add empty line if the last line is not empty
141
+ if content.rstrip('\n').splitlines()[-1].strip():
142
+ content += '\n'
143
+
144
+ # If new content starts with empty lines, preserve original indentation
145
+ lines = new_content.splitlines()
146
+ if not lines or not lines[0].strip():
147
+ return content + new_content
148
+
149
+ # Get base indentation from last non-empty line
150
+ base_indent = self._get_last_line_indent(content)
151
+
152
+ # Get the first non-empty line from new content
153
+ first_line, _ = self.searcher.get_first_non_empty_line(new_content)
154
+ if first_line:
155
+ # Get the indentation of the first line of new content
156
+ new_base_indent = self.searcher.get_indentation(first_line)
157
+
158
+ # Calculate how much we need to shift if new content would go into negative space
159
+ indent_delta = len(base_indent) + (len(new_base_indent) - len(new_base_indent))
160
+ left_shift = abs(min(0, indent_delta))
161
+
162
+ result_lines = []
163
+ for line in new_content.splitlines():
164
+ if not line.strip():
165
+ result_lines.append('')
166
+ continue
167
+
168
+ # Calculate final indentation:
169
+ # 1. Get current line's indentation
170
+ line_indent = self.searcher.get_indentation(line)
171
+ # 2. Calculate relative indent compared to new content's first line
172
+ rel_indent = len(line_indent) - len(new_base_indent)
173
+ # 3. Apply base indent + relative indent, adjusting for negative space
174
+ final_indent_len = max(0, len(line_indent) - left_shift + (len(base_indent) - len(new_base_indent)))
175
+ final_indent = ' ' * final_indent_len
176
+ result_lines.append(final_indent + line.lstrip())
177
+
178
+ new_content = '\n'.join(result_lines)
179
+
180
+ return content + new_content
181
+
182
+ def _handle_failed_search(self, filepath: Path, search_text: str, content: str) -> str:
183
+ """Handle failed search by logging debug info in a test case format"""
184
+ failed_file = config.workspace_dir / '.janito' / 'change_history' / f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_changes_failed.txt"
185
+ failed_file.parent.mkdir(parents=True, exist_ok=True)
186
+
187
+ # Create test case format debug info
188
+ debug_info = f"""Test: Failed search in {filepath.name}
189
+ ========================================
190
+ Original:
191
+ {content}
192
+ ========================================
193
+ Search pattern:
194
+ {search_text}
195
+ ========================================"""
196
+
197
+ failed_file.write_text(debug_info)
198
+
199
+ self.console.print(f"\n[red]Failed search saved to: {failed_file}[/red]")
200
+ self.console.print("[yellow]Run with 'python -m janito.search_replace {failed_file}' to debug[/yellow]")
201
+
202
+ return f"Could not find search text in {filepath}"
203
+
204
+ def debug_failed_finds(self, search_content: str, file_content: str, filepath: str) -> None:
205
+ """Debug find operations without applying changes"""
206
+ if not search_content or not file_content:
207
+ self.console.print("[yellow]Missing search or file content for debugging[/yellow]")
208
+ return
209
+
210
+ self.console.print(f"\n[cyan]Debugging finds for {filepath}:[/cyan]")
211
+ self.debugger.debug_find(file_content, search_content)
212
+
213
+ def extract_debug_info(self, content: str) -> tuple[Optional[str], Optional[str], Optional[str]]:
214
+ """Extract search text and file content from failed change debug info.
215
+
216
+ Only matches section markers ("========================================")
217
+ when they appear alone on a line.
218
+ """
219
+ try:
220
+ marker = "=" * 40
221
+ lines = content.splitlines()
222
+ section_starts = [i for i, line in enumerate(lines) if line.strip() == marker]
223
+
224
+ if len(section_starts) < 3:
225
+ raise ValueError("Missing section markers in debug file")
226
+
227
+ # Extract content between markers
228
+ original_start = section_starts[0] + 2 # +1 for section header, +1 for marker
229
+ search_start = section_starts[1] + 2
230
+ original_content = "\n".join(lines[original_start:section_starts[1]])
231
+ search_content = "\n".join(lines[search_start:section_starts[2]])
232
+
233
+ # Extract filename from first line
234
+ if not lines[0].startswith("Test: Failed search in "):
235
+ raise ValueError("Invalid debug file format")
236
+ filepath = lines[0].replace("Test: Failed search in ", "").strip()
237
+
238
+ if not all([filepath, search_content, original_content]):
239
+ raise ValueError("Missing required sections in debug file")
240
+
241
+ return filepath, search_content, original_content
242
+
243
+ except Exception as e:
244
+ self.console.print(f"[red]Error parsing debug info: {e}[/red]")
245
+ return None, None, None