diff --git a/wallpaper_changer/src/wallpaper_changer/image_repository.py b/wallpaper_changer/src/wallpaper_changer/image_repository.py index 8c2204c..a74535b 100644 --- a/wallpaper_changer/src/wallpaper_changer/image_repository.py +++ b/wallpaper_changer/src/wallpaper_changer/image_repository.py @@ -371,12 +371,21 @@ class ImageRepository: def _available_path(path: Path) -> Path: if not path.exists(): return path - counter = 1 - while True: - candidate = path.with_name(f"{path.stem}_DOUBLE_{counter}{path.suffix}") - if not candidate.exists(): - return candidate - counter += 1 + match = re.fullmatch(r"(.*?)(\d+)", path.stem) + prefix = match.group(1) if match else path.stem + width = len(match.group(2)) if match else 2 + existing_numbers = [] + for existing_path in path.parent.glob("*"): + if existing_path.suffix.casefold() != path.suffix.casefold(): + continue + numbered_name = re.fullmatch( + rf"{re.escape(prefix)}(\d+)", existing_path.stem, re.IGNORECASE + ) + if numbered_name: + existing_numbers.append(int(numbered_name.group(1))) + + next_number = max(existing_numbers, default=0) + 1 + return path.with_name( f"{prefix}{next_number:0{width}d}{path.suffix}") @staticmethod def _unique_identifier(identifier: str, naming_table: list[FileInfo]) -> str: