feat: add backup option and move some logic from main to utils
This commit is contained in:
@@ -1,7 +1,9 @@
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
from typing import List
|
||||
|
||||
from config import SYNC_CONFIG
|
||||
from .types import SubtitleEntry
|
||||
|
||||
|
||||
@@ -41,9 +43,28 @@ class SubtitleHandler:
|
||||
entries.append(SubtitleEntry(int(match.group(1)), start, end, match.group(4).strip()))
|
||||
return entries
|
||||
|
||||
@staticmethod
|
||||
def create_backup(filepath: str):
|
||||
"""Creates a .bak copy of the subtitles if one doesn't exist."""
|
||||
backup_path = filepath + ".bak"
|
||||
if not os.path.exists(backup_path):
|
||||
try:
|
||||
shutil.copy2(filepath, backup_path)
|
||||
print(f"Backup created: {os.path.basename(backup_path)}")
|
||||
except IOError as e:
|
||||
print(f"Warning: Could not create backup: {e}")
|
||||
|
||||
@staticmethod
|
||||
def write_srt(filepath: str, entries: List[SubtitleEntry]):
|
||||
with open(filepath, 'w', encoding='utf-8') as f:
|
||||
for entry in entries:
|
||||
f.write(
|
||||
f"{entry.index}\n{SubtitleHandler.format_time(entry.start_ms)} --> {SubtitleHandler.format_time(entry.end_ms)}\n{entry.raw_text}\n\n")
|
||||
# 1. Ensure backup exists before overwriting
|
||||
if SYNC_CONFIG['create_backup']:
|
||||
SubtitleHandler.create_backup(filepath)
|
||||
|
||||
# 2. Overwrite
|
||||
try:
|
||||
with open(filepath, 'w', encoding='utf-8') as f:
|
||||
for entry in entries:
|
||||
f.write(
|
||||
f"{entry.index}\n{SubtitleHandler.format_time(entry.start_ms)} --> {SubtitleHandler.format_time(entry.end_ms)}\n{entry.raw_text}\n\n")
|
||||
except IOError as e:
|
||||
print(f"Error writing subtitle file: {e}")
|
||||
|
||||
Reference in New Issue
Block a user