Files

26 lines
959 B
Python

"""Filename rules for uploads: spaces become dashes, duplicates get -2, -3, ..."""
import os
import re
from collections.abc import Callable
def clean_name(filename: str) -> str:
"""Keep only the base name and turn every run of whitespace into one dash."""
base = filename.replace("\\", "/").rsplit("/", 1)[-1].strip()
base = re.sub(r"\s+", "-", base)
return base or "upload"
def split_name(name: str) -> tuple[str, str]:
"""('clip', '.mp4'); a name with no extension gives ('README', '')."""
return os.path.splitext(name)
def next_free_name(stem: str, ext: str, exists: Callable[[str], bool], limit: int = 1000) -> str:
"""First of stem+ext, stem-2+ext, stem-3+ext, ... that does not exist yet."""
for n in range(1, limit + 1):
name = f"{stem}{ext}" if n == 1 else f"{stem}-{n}{ext}"
if not exists(name):
return name
raise RuntimeError(f"no free name for {stem}{ext} after {limit} tries")