fix(core): strip trailing spaces and dots in template formatting to prevent WinError 3

- Clean up redundant spaces and separators when conditional tags (e.g. {year?}) are omitted.
- Strip leading and trailing spaces and dots in sanitize_filename and TemplateFormatter.
- Prevent FileNotFoundError [WinError 3] caused by trailing spaces in Windows directory paths.
This commit is contained in:
CodeName393
2026-07-26 18:16:36 +09:00
committed by GitHub
parent d60d8abf53
commit 41106b0d24
2 changed files with 7 additions and 2 deletions
+1
View File
@@ -142,6 +142,7 @@ def sanitize_filename(filename: str, spacer: str = ".") -> str:
filename = re.sub(r"[:; ]", spacer, filename) # structural chars to (spacer)
filename = re.sub(r"[\\*!?¿,'\"" "<>|$#~]", "", filename) # not filename safe chars
filename = re.sub(rf"[{spacer}]{{2,}}", spacer, filename) # remove extra neighbouring (spacer)s
filename = filename.strip(" .") # strip leading and trailing spaces and dots for OS path safety
return filename
+6 -2
View File
@@ -96,11 +96,13 @@ class TemplateFormatter:
# Clean up multiple consecutive dots/separators and other artifacts
result = re.sub(r"\.{2,}", ".", result) # Multiple dots -> single dot
result = re.sub(r"\s{2,}", " ", result) # Multiple spaces -> single space
result = re.sub(r"-{2,}", "-", result) # Multiple dashes -> single dash
result = re.sub(r"^[\.\s\-]+|[\.\s\-]+$", "", result) # Remove leading/trailing dots, spaces, dashes
result = re.sub(r"(?:-\s*)+-", "-", result) # Multiple dashes (with optional spaces) -> single dash
result = re.sub(r"\.-", "-", result) # Remove dots before dashes (for dot-based templates)
result = re.sub(r"[\.\s]+\)", ")", result) # Remove dots/spaces before closing parentheses
result = re.sub(r"\(\s*\)", "", result) # Remove empty parentheses (empty conditional)
result = re.sub(r"\s{2,}", " ", result) # Multiple spaces after parenthesis removal -> single space
result = re.sub(r"(?:-\s*)+-", "-", result) # Multiple dashes (with optional spaces) -> single dash
result = re.sub(r"^[\.\s\-]+|[\.\s\-]+$", "", result) # Remove leading/trailing dots, spaces, dashes
# Determine the appropriate separator based on template style
# Count separator characters between variables (between } and {)
@@ -114,6 +116,8 @@ class TemplateFormatter:
else:
result = sanitize_filename(result, spacer=".")
result = result.strip(" .")
if not result or result.isspace():
log.warning("Template formatting resulted in empty filename, using fallback")
return "untitled"