Coverage for src/content_editor.py: 88%
49 statements
« prev ^ index » next coverage.py v7.10.7, created at 2025-10-08 05:40 +0000
« prev ^ index » next coverage.py v7.10.7, created at 2025-10-08 05:40 +0000
1from pathlib import Path
2from typing import Dict, Optional, List
4try:
5 from .document_parser import Section
6except ImportError:
7 # Fallback for when run as script without src module in path
8 from document_parser import Section
10class ContentEditor:
11 def __init__(self, project_root: Path):
12 self.project_root = Path(project_root) if isinstance(project_root, str) else project_root
13 self.file_contents: Dict[str, List[str]] = {}
15 def load_file_content(self, file_path: Path) -> List[str]:
16 """Load file content as list of lines"""
17 file_key = str(file_path)
18 if file_key not in self.file_contents:
19 try:
20 content = file_path.read_text(encoding='utf-8')
21 self.file_contents[file_key] = content.split('\n')
22 except Exception:
23 self.file_contents[file_key] = []
24 return self.file_contents[file_key]
26 def update_section(self, section: Section, new_content: str, source_file: Path) -> bool:
27 """Update section content in source file"""
28 lines = self.load_file_content(source_file)
30 if section.line_start >= len(lines) or section.line_end >= len(lines):
31 return False
33 # Keep header line, replace content
34 header_line = lines[section.line_start]
35 content_lines = new_content.split('\n')
37 # Replace section content
38 new_lines = lines[:section.line_start + 1] + content_lines + lines[section.line_end + 1:]
40 try:
41 source_file.write_text('\n'.join(new_lines), encoding='utf-8')
42 self.file_contents[str(source_file)] = new_lines
43 return True
44 except Exception:
45 return False
47 def insert_section(self, parent_section: Section, title: str, content: str,
48 position: str, source_file: Path) -> bool:
49 """Insert new section relative to parent"""
50 lines = self.load_file_content(source_file)
52 # Determine header level
53 level_char = '=' if source_file.suffix in ['.adoc', '.asciidoc'] else '#'
54 header_prefix = level_char * (parent_section.level + 1)
56 # Create new section lines
57 new_section_lines = [
58 f"{header_prefix} {title}",
59 content
60 ]
62 # Determine insertion point
63 if position == "append":
64 insert_pos = parent_section.line_end + 1
65 elif position == "before":
66 insert_pos = parent_section.line_start
67 else: # after
68 insert_pos = parent_section.line_end + 1
70 # Insert new content
71 new_lines = lines[:insert_pos] + new_section_lines + lines[insert_pos:]
73 try:
74 source_file.write_text('\n'.join(new_lines), encoding='utf-8')
75 self.file_contents[str(source_file)] = new_lines
76 return True
77 except Exception:
78 return False