Files
cmshoppe/app/config.py
T

49 lines
1.4 KiB
Python
Raw Normal View History

2026-06-27 09:21:33 +08:00
"""Account path helpers for Chrome user-data directories."""
from __future__ import annotations
import hashlib
import os
import re
from . import appconfig
SLUG_PATTERN = re.compile(r"^[a-z0-9_]+$")
class ConfigPathError(RuntimeError):
"""Raised when account path configuration is invalid."""
def make_slug(alias) -> str:
"""Return a stable unique slug for an account alias."""
text = str(alias or "").strip()
if not text:
raise ConfigPathError("别名不能为空")
base = re.sub(r"[^a-z0-9_]+", "_", text.lower()).strip("_")
suffix = hashlib.sha1(text.encode("utf-8")).hexdigest()[:8]
return f"{base}_{suffix}" if base else f"account_{suffix}"
def _validate_slug(slug) -> str:
text = str(slug or "").strip()
if not text:
raise ConfigPathError("slug 不能为空")
if not SLUG_PATTERN.fullmatch(text):
raise ConfigPathError("slug 只能包含小写字母、数字和下划线")
return text
def ensure_user_data_dir(slug, root=None, config=None) -> str:
"""Create and return the absolute user-data-dir path for a slug."""
safe_slug = _validate_slug(slug)
user_data_root = root if root is not None else appconfig.user_data_root(config)
if not str(user_data_root).strip():
raise ConfigPathError("user_data_root 不能为空")
path = os.path.abspath(os.path.join(str(user_data_root), safe_slug))
os.makedirs(path, exist_ok=True)
return path