Files
Server-scripts/serverlibary/core.py
T

49 lines
1.0 KiB
Python
Raw Normal View History

2026-04-14 23:53:03 +02:00
from pathlib import Path
import shutil
# -----------------------------
# Helpers
# -----------------------------
def safe_delete(path: Path):
if path.is_dir():
shutil.rmtree(path)
else:
path.unlink()
2026-07-16 10:54:33 +02:00
def safe_rename(src: Path, dst: Path, dry: bool=False, confirm: bool=False, silent=False):
2026-04-14 23:53:03 +02:00
"""
Safely rename a file or directory without overwriting existing files.
Automatically appends _1, _2, ... if needed.
"""
src = Path(src)
dst = Path(dst)
# nothing to do
if src.resolve() == dst.resolve():
return
directory = dst.parent
base = dst.stem
ext = dst.suffix
final_dst = dst
counter = 1
# find free name
while final_dst.exists():
final_dst = directory / f"{base}_{counter}{ext}"
counter += 1
2026-07-16 10:54:33 +02:00
if not silent:
print(f"{src} → {dst}")
2026-04-14 23:53:03 +02:00
if dry:
return
if confirm:
input("Press Enter to confirm...")
dst.parent.mkdir(parents=True, exist_ok=True)
src.rename(dst)