janito 0.7.0__py3-none-any.whl → 0.9.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 (114) hide show
  1. janito/__init__.py +5 -2
  2. janito/__main__.py +151 -142
  3. janito/callbacks.py +130 -0
  4. janito/cli.py +202 -0
  5. janito/config.py +57 -96
  6. janito/data/instructions.txt +6 -0
  7. janito/test_file.py +4 -0
  8. janito/token_report.py +73 -0
  9. janito/tools/__init__.py +10 -0
  10. janito/tools/decorators.py +84 -0
  11. janito/tools/delete_file.py +44 -0
  12. janito/tools/find_files.py +154 -0
  13. janito/tools/search_text.py +197 -0
  14. janito/tools/str_replace_editor/__init__.py +6 -0
  15. janito/tools/str_replace_editor/editor.py +43 -0
  16. janito/tools/str_replace_editor/handlers.py +338 -0
  17. janito/tools/str_replace_editor/utils.py +88 -0
  18. {janito-0.7.0.dist-info/licenses → janito-0.9.0.dist-info}/LICENSE +20 -20
  19. janito-0.9.0.dist-info/METADATA +9 -0
  20. janito-0.9.0.dist-info/RECORD +23 -0
  21. {janito-0.7.0.dist-info → janito-0.9.0.dist-info}/WHEEL +2 -1
  22. janito-0.9.0.dist-info/entry_points.txt +2 -0
  23. janito-0.9.0.dist-info/top_level.txt +1 -0
  24. janito/agents/__init__.py +0 -22
  25. janito/agents/agent.py +0 -28
  26. janito/agents/claudeai.py +0 -45
  27. janito/agents/openai.py +0 -57
  28. janito/agents/test.py +0 -34
  29. janito/change/__init__.py +0 -32
  30. janito/change/__main__.py +0 -0
  31. janito/change/analysis/__init__.py +0 -23
  32. janito/change/analysis/__main__.py +0 -7
  33. janito/change/analysis/analyze.py +0 -62
  34. janito/change/analysis/formatting.py +0 -78
  35. janito/change/analysis/options.py +0 -81
  36. janito/change/analysis/prompts.py +0 -90
  37. janito/change/analysis/view/__init__.py +0 -9
  38. janito/change/analysis/view/terminal.py +0 -181
  39. janito/change/applier/__init__.py +0 -5
  40. janito/change/applier/file.py +0 -58
  41. janito/change/applier/main.py +0 -156
  42. janito/change/applier/text.py +0 -247
  43. janito/change/applier/workspace_dir.py +0 -58
  44. janito/change/core.py +0 -124
  45. janito/change/history.py +0 -44
  46. janito/change/operations.py +0 -7
  47. janito/change/parser.py +0 -287
  48. janito/change/play.py +0 -54
  49. janito/change/preview.py +0 -82
  50. janito/change/prompts.py +0 -121
  51. janito/change/test.py +0 -0
  52. janito/change/validator.py +0 -269
  53. janito/change/viewer/__init__.py +0 -11
  54. janito/change/viewer/content.py +0 -66
  55. janito/change/viewer/diff.py +0 -43
  56. janito/change/viewer/panels.py +0 -533
  57. janito/change/viewer/styling.py +0 -114
  58. janito/change/viewer/themes.py +0 -55
  59. janito/clear_statement_parser/clear_statement_format.txt +0 -328
  60. janito/clear_statement_parser/examples.txt +0 -326
  61. janito/clear_statement_parser/models.py +0 -104
  62. janito/clear_statement_parser/parser.py +0 -496
  63. janito/cli/__init__.py +0 -2
  64. janito/cli/base.py +0 -30
  65. janito/cli/commands.py +0 -88
  66. janito/cli/functions.py +0 -111
  67. janito/cli/history.py +0 -61
  68. janito/cli/registry.py +0 -26
  69. janito/common.py +0 -80
  70. janito/demo/__init__.py +0 -4
  71. janito/demo/data.py +0 -13
  72. janito/demo/mock_data.py +0 -20
  73. janito/demo/operations.py +0 -45
  74. janito/demo/runner.py +0 -59
  75. janito/demo/scenarios.py +0 -32
  76. janito/prompt.py +0 -36
  77. janito/qa.py +0 -57
  78. janito/review.py +0 -13
  79. janito/search_replace/README.md +0 -192
  80. janito/search_replace/__init__.py +0 -7
  81. janito/search_replace/__main__.py +0 -21
  82. janito/search_replace/core.py +0 -120
  83. janito/search_replace/logger.py +0 -35
  84. janito/search_replace/parser.py +0 -52
  85. janito/search_replace/play.py +0 -61
  86. janito/search_replace/replacer.py +0 -36
  87. janito/search_replace/searcher.py +0 -411
  88. janito/search_replace/strategy_result.py +0 -10
  89. janito/shell/__init__.py +0 -38
  90. janito/shell/bus.py +0 -31
  91. janito/shell/commands.py +0 -136
  92. janito/shell/history.py +0 -20
  93. janito/shell/processor.py +0 -32
  94. janito/shell/prompt.py +0 -48
  95. janito/shell/registry.py +0 -60
  96. janito/tui/__init__.py +0 -21
  97. janito/tui/base.py +0 -22
  98. janito/tui/flows/__init__.py +0 -5
  99. janito/tui/flows/changes.py +0 -65
  100. janito/tui/flows/content.py +0 -128
  101. janito/tui/flows/selection.py +0 -117
  102. janito/tui/screens/__init__.py +0 -3
  103. janito/tui/screens/app.py +0 -1
  104. janito/version.py +0 -23
  105. janito/workspace/__init__.py +0 -6
  106. janito/workspace/analysis.py +0 -121
  107. janito/workspace/show.py +0 -141
  108. janito/workspace/stats.py +0 -43
  109. janito/workspace/types.py +0 -98
  110. janito/workspace/workset.py +0 -108
  111. janito/workspace/workspace.py +0 -114
  112. janito-0.7.0.dist-info/METADATA +0 -167
  113. janito-0.7.0.dist-info/RECORD +0 -96
  114. janito-0.7.0.dist-info/entry_points.txt +0 -2
@@ -1,9 +0,0 @@
1
- """View package for analysis UI components."""
2
-
3
- from .terminal import format_analysis, prompt_user, get_option_selection
4
-
5
- __all__ = [
6
- 'format_analysis',
7
- 'prompt_user',
8
- 'get_option_selection'
9
- ]
@@ -1,181 +0,0 @@
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 rich.style import Style
13
- from rich.segment import Segment
14
- from rich.containers import Renderables
15
- from pathlib import Path
16
-
17
- from ..options import AnalysisOption
18
- from ..formatting import (
19
- COLUMN_SPACING,
20
- MIN_PANEL_WIDTH,
21
- SECTION_PADDING,
22
- STATUS_COLORS,
23
- STRUCTURAL_COLORS,
24
- create_header,
25
- create_section_header,
26
- format_file_path
27
- )
28
-
29
- def prompt_user(message: str, choices: List[str] = None) -> str:
30
- """Display a prominent user prompt with optional choices"""
31
- console = Console()
32
- term_width = console.width or 80
33
- console.print()
34
- console.print(Rule(" User Input Required ", style="bold cyan", align="center"))
35
-
36
- if choices:
37
- choice_text = f"[cyan]Options: {', '.join(choices)}[/cyan]"
38
- console.print(Panel(choice_text, box=box.ROUNDED, justify="center"))
39
-
40
- message_text = Text(message, style="bold cyan")
41
- padded_message = Padding(message_text, pad=(0, "center"))
42
- console.print(padded_message)
43
- return Prompt.ask("")
44
-
45
- def get_option_selection() -> str:
46
- """Get user input for option selection with modify option"""
47
- console = Console()
48
- term_width = console.width or 80
49
- message = "Enter option letter or 'M' to modify request"
50
- padding = (term_width - len(message)) // 2
51
- padded_message = " " * padding + message
52
-
53
- console.print(f"\n[cyan]{padded_message}[/cyan]")
54
- while True:
55
- letter = prompt_user("Select option").strip().upper()
56
- if letter == 'M' or (letter.isalpha() and len(letter) == 1):
57
- return letter
58
-
59
- error_msg = "Please enter a valid letter or 'M'"
60
- error_text = Text(error_msg, style="red")
61
- padded_error = Padding(error_text, pad=(0, "center"))
62
- console.print(padded_error)
63
-
64
- def _create_option_content(option: AnalysisOption) -> Text:
65
- """Create rich formatted content for a single option."""
66
- content = Text()
67
- content.append("\n")
68
-
69
- header = create_header(f"Option {option.letter} - {option.summary}")
70
- content.append(header)
71
- content.append("\n")
72
-
73
- if option.description_items:
74
- for item in option.description_items:
75
- content.append("• ", style="cyan")
76
- content.append(f"{item}\n")
77
- content.append("\n")
78
-
79
- # Add consistent padding before file list
80
- content.append("\n" * 2)
81
-
82
- if option.affected_files:
83
- files = {status: [] for status in ['New', 'Modified', 'Removed']}
84
- for file in option.affected_files:
85
- if '(new)' in file.lower():
86
- files['New'].append(file)
87
- elif '(removed)' in file.lower():
88
- files['Removed'].append(file)
89
- else:
90
- files['Modified'].append(file)
91
-
92
- for status, status_files in files.items():
93
- if status_files:
94
- content.append(create_section_header(f"{status} Files"))
95
- content.append("\n")
96
- sorted_files = sorted(status_files)
97
- prev_path = None
98
- seen_dirs = {}
99
- for file in sorted_files:
100
- path = option.get_clean_path(file)
101
- current_parts = Path(path).parts
102
- parent_dir = str(Path(path).parent)
103
-
104
- if parent_dir != '.':
105
- is_repeated = parent_dir in seen_dirs
106
- if not is_repeated:
107
- content.append(parent_dir, style=STRUCTURAL_COLORS['directory'])
108
- content.append("/", style=STRUCTURAL_COLORS['separator'])
109
- seen_dirs[parent_dir] = True
110
- else:
111
- dir_width = len(parent_dir)
112
- # Calculate padding to match full directory width
113
- arrow = "↑"
114
- total_padding = dir_width - len(arrow)
115
- left_padding = total_padding // 2
116
- right_padding = total_padding - left_padding
117
- content.append(" " * left_padding + arrow + " " * right_padding,
118
- style=STRUCTURAL_COLORS['repeat'])
119
- content.append("/", style=STRUCTURAL_COLORS['separator'])
120
- content.append(current_parts[-1], style=STATUS_COLORS[status.lower()])
121
- else:
122
- content.append(current_parts[-1], style=STATUS_COLORS[status.lower()])
123
- content.append("\n")
124
- content.append("\n")
125
-
126
- content.append("\n")
127
-
128
- return content
129
-
130
- def create_columns_layout(options_content: List[Text], term_width: int) -> Columns:
131
- """Create a columns layout with consistent spacing."""
132
- num_columns = len(options_content)
133
- spacing = COLUMN_SPACING * (num_columns - 1)
134
- safety_margin = 4 + 2
135
-
136
- usable_width = term_width - spacing - safety_margin
137
- column_width = max((usable_width // num_columns), MIN_PANEL_WIDTH)
138
-
139
- # Create padded content items
140
- rendered_items: List[Renderables] = [
141
- Padding(content, (0, COLUMN_SPACING // 2))
142
- for content in options_content
143
- ]
144
-
145
- return Columns(
146
- rendered_items,
147
- equal=True,
148
- expand=True,
149
- width=column_width,
150
- align="left",
151
- padding=(0, 0),
152
- )
153
-
154
- def format_analysis(analysis: str, raw: bool = False) -> None:
155
- """Format and display the analysis output."""
156
- from ..options import parse_analysis_options
157
-
158
- console = Console()
159
- term_width = console.width or 100
160
-
161
- if raw:
162
- console.print(analysis)
163
- return
164
-
165
- options = parse_analysis_options(analysis)
166
- if not options:
167
- console.print("\n[yellow]Warning: No valid options found in response.[/yellow]\n")
168
- console.print(analysis)
169
- return
170
-
171
- columns_content = [_create_option_content(options[letter])
172
- for letter in sorted(options.keys())]
173
-
174
- columns = create_columns_layout(columns_content, term_width)
175
-
176
- console.print("\n")
177
- console.print(Text("Analysis Options", style="bold cyan"))
178
- console.print(Text("─" * term_width, style="cyan dim"))
179
- console.print(columns)
180
- console.print(Text("─" * term_width, style="cyan dim"))
181
- console.print("\n")
@@ -1,5 +0,0 @@
1
- from .file import FileChangeApplier
2
- from .text import TextChangeApplier
3
- from .workspace_dir import apply_changes
4
-
5
- __all__ = ['FileChangeApplier', 'TextChangeApplier', 'apply_changes']
@@ -1,58 +0,0 @@
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
@@ -1,156 +0,0 @@
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())
@@ -1,247 +0,0 @@
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
- # Validate operation
87
- is_valid, error = self._validate_operation(mod)
88
- if not is_valid:
89
- self.console.print(f"[yellow]Warning: Invalid text operation for {target_path}: {error}[/yellow]")
90
- continue
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
- warning_msg = self._handle_failed_search(target_path, mod.search_content, modified)
125
- self.console.print(f"[yellow]Warning: {warning_msg}[/yellow]")
126
- continue
127
-
128
- return (True, modified, None) if any_changes else (False, content, "No changes were applied")
129
-
130
- def _append_content(self, content: str, new_content: str) -> str:
131
- """Append content with proper indentation matching.
132
-
133
- The indentation rules are:
134
- 1. If new content starts with empty lines, preserve original indentation
135
- 2. Otherwise, use indentation from the last non-empty line of existing content as base
136
- 3. Preserves relative indentation between lines in new content
137
- 4. Adjusts indentation if new content would go into negative space
138
- """
139
- if not content.endswith('\n'):
140
- content += '\n'
141
-
142
- # Add empty line if the last line is not empty
143
- if content.rstrip('\n').splitlines()[-1].strip():
144
- content += '\n'
145
-
146
- # If new content starts with empty lines, preserve original indentation
147
- lines = new_content.splitlines()
148
- if not lines or not lines[0].strip():
149
- return content + new_content
150
-
151
- # Get base indentation from last non-empty line
152
- base_indent = self._get_last_line_indent(content)
153
-
154
- # Get the first non-empty line from new content
155
- first_line, _ = self.searcher.get_first_non_empty_line(new_content)
156
- if first_line:
157
- # Get the indentation of the first line of new content
158
- new_base_indent = self.searcher.get_indentation(first_line)
159
-
160
- # Calculate how much we need to shift if new content would go into negative space
161
- indent_delta = len(base_indent) + (len(new_base_indent) - len(new_base_indent))
162
- left_shift = abs(min(0, indent_delta))
163
-
164
- result_lines = []
165
- for line in new_content.splitlines():
166
- if not line.strip():
167
- result_lines.append('')
168
- continue
169
-
170
- # Calculate final indentation:
171
- # 1. Get current line's indentation
172
- line_indent = self.searcher.get_indentation(line)
173
- # 2. Calculate relative indent compared to new content's first line
174
- rel_indent = len(line_indent) - len(new_base_indent)
175
- # 3. Apply base indent + relative indent, adjusting for negative space
176
- final_indent_len = max(0, len(line_indent) - left_shift + (len(base_indent) - len(new_base_indent)))
177
- final_indent = ' ' * final_indent_len
178
- result_lines.append(final_indent + line.lstrip())
179
-
180
- new_content = '\n'.join(result_lines)
181
-
182
- return content + new_content
183
-
184
- def _handle_failed_search(self, filepath: Path, search_text: str, content: str) -> str:
185
- """Handle failed search by logging debug info in a test case format"""
186
- failed_file = config.workspace_dir / '.janito' / 'change_history' / f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_changes_failed.txt"
187
- failed_file.parent.mkdir(parents=True, exist_ok=True)
188
-
189
- # Create test case format debug info
190
- debug_info = f"""Test: Failed search in {filepath.name}
191
- ========================================
192
- Original:
193
- {content}
194
- ========================================
195
- Search pattern:
196
- {search_text}
197
- ========================================"""
198
-
199
- failed_file.write_text(debug_info)
200
-
201
- self.console.print(f"[yellow]Changes failed saved to: {failed_file}[/yellow]")
202
- self.console.print("[yellow]Run with 'python -m janito.search_replace {failed_file}' to debug[/yellow]")
203
-
204
- return f"Could not apply change to {filepath} - pattern not found"
205
-
206
- def debug_failed_finds(self, search_content: str, file_content: str, filepath: str) -> None:
207
- """Debug find operations without applying changes"""
208
- if not search_content or not file_content:
209
- self.console.print("[yellow]Missing search or file content for debugging[/yellow]")
210
- return
211
-
212
- self.console.print(f"\n[cyan]Debugging finds for {filepath}:[/cyan]")
213
- self.debugger.debug_find(file_content, search_content)
214
-
215
- def extract_debug_info(self, content: str) -> tuple[Optional[str], Optional[str], Optional[str]]:
216
- """Extract search text and file content from failed change debug info.
217
-
218
- Only matches section markers ("========================================")
219
- when they appear alone on a line.
220
- """
221
- try:
222
- marker = "=" * 40
223
- lines = content.splitlines()
224
- section_starts = [i for i, line in enumerate(lines) if line.strip() == marker]
225
-
226
- if len(section_starts) < 3:
227
- raise ValueError("Missing section markers in debug file")
228
-
229
- # Extract content between markers
230
- original_start = section_starts[0] + 2 # +1 for section header, +1 for marker
231
- search_start = section_starts[1] + 2
232
- original_content = "\n".join(lines[original_start:section_starts[1]])
233
- search_content = "\n".join(lines[search_start:section_starts[2]])
234
-
235
- # Extract filename from first line
236
- if not lines[0].startswith("Test: Failed search in "):
237
- raise ValueError("Invalid debug file format")
238
- filepath = lines[0].replace("Test: Failed search in ", "").strip()
239
-
240
- if not all([filepath, search_content, original_content]):
241
- raise ValueError("Missing required sections in debug file")
242
-
243
- return filepath, search_content, original_content
244
-
245
- except Exception as e:
246
- self.console.print(f"[red]Error parsing debug info: {e}[/red]")
247
- return None, None, None