更新: 359 个文件 - 2026-03-16 23:30:01

这个提交包含在:
hao
2026-03-16 23:30:01 -07:00
父节点 527990f535
当前提交 2974cd9ad9
修改 359 个文件,包含 6332 行新增673 行删除

103
scripts/lab/utils.py 普通文件
查看文件

@@ -0,0 +1,103 @@
from __future__ import annotations
import json
import shutil
import subprocess
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional
import yaml
UTC = timezone.utc
def now_utc() -> datetime:
return datetime.now(tz=UTC)
def isoformat(dt: datetime) -> str:
return dt.astimezone(UTC).replace(microsecond=0).isoformat()
def ensure_dir(path: Path) -> None:
path.mkdir(parents=True, exist_ok=True)
def read_json(path: Path, default: Any = None) -> Any:
if not path.exists():
return default
return json.loads(path.read_text(encoding="utf-8"))
def write_json(path: Path, data: Any) -> None:
ensure_dir(path.parent)
path.write_text(json.dumps(data, indent=2, ensure_ascii=True, sort_keys=False) + "\n", encoding="utf-8")
def read_yaml(path: Path, default: Any = None) -> Any:
if not path.exists():
return default
with path.open("r", encoding="utf-8") as handle:
return yaml.safe_load(handle)
def write_yaml(path: Path, data: Any) -> None:
ensure_dir(path.parent)
with path.open("w", encoding="utf-8") as handle:
yaml.safe_dump(data, handle, allow_unicode=False, sort_keys=False)
def write_text(path: Path, content: str) -> None:
ensure_dir(path.parent)
path.write_text(content.rstrip() + "\n", encoding="utf-8")
def load_json_dir(path: Path) -> List[Dict[str, Any]]:
if not path.exists():
return []
values: List[Dict[str, Any]] = []
for file_path in sorted(path.glob("*.json")):
content = read_json(file_path, default=None)
if isinstance(content, dict):
values.append(content)
return values
def run(cmd: List[str], cwd: Optional[Path] = None, check: bool = False) -> subprocess.CompletedProcess:
return subprocess.run(
cmd,
cwd=str(cwd) if cwd else None,
text=True,
capture_output=True,
check=check,
)
def command_available(name: str) -> bool:
return shutil.which(name) is not None
def slugify(value: str) -> str:
safe = []
for ch in value.lower().strip():
if ch.isalnum():
safe.append(ch)
else:
safe.append("-")
result = "".join(safe)
while "--" in result:
result = result.replace("--", "-")
return result.strip("-") or "item"
def unique(values: Iterable[str]) -> List[str]:
seen = set()
result = []
for value in values:
if not value or value in seen:
continue
seen.add(value)
result.append(value)
return result