Files
BABA_YAGA/BABA_YAGA_Updater/services/readme_editor.py
2026-06-07 20:24:36 +07:00

50 lines
1.6 KiB
Python

import os
from config.settings import settings
class ReadmeEditor:
def __init__(self, file_path: str = None):
self.file_path = file_path or settings.README_PATH
def update_whole_readme(self, sections_content: str):
"""
Ghi đè toàn bộ nội dung README.md bằng nội dung đã gộp từ các sections.
"""
try:
# Đảm bảo thư mục cha tồn tại nếu đường dẫn là ../README.md
os.makedirs(os.path.dirname(os.path.abspath(self.file_path)), exist_ok=True)
with open(self.file_path, 'w', encoding='utf-8') as f:
f.write(sections_content)
return True
except Exception as e:
print(f"Error writing to {self.file_path}: {e}")
return False
def inject_content_between_markers(self, file_path: str, content_to_inject: str, start_marker: str, end_marker: str):
"""
Tiêm nội dung vào giữa 2 markers trong một file cụ thể.
"""
import re
if not os.path.exists(file_path):
return False
with open(file_path, 'r', encoding='utf-8') as f:
full_text = f.read()
pattern = re.compile(
f"({re.escape(start_marker)})(.*?)({re.escape(end_marker)})",
re.DOTALL
)
if not pattern.search(full_text):
return False
updated_text = pattern.sub(
f"\\1\n\n{content_to_inject}\n\n\\3",
full_text
)
with open(file_path, 'w', encoding='utf-8') as f:
f.write(updated_text)
return True