Coverage for merco/utils/helpers.py: 0%

23 statements  

« prev     ^ index     » next       coverage.py v7.15.0, created at 2026-07-07 14:04 +0800

1"""通用辅助函数""" 

2 

3import os 

4import re 

5from pathlib import Path 

6 

7 

8def expand_path(path: str) -> Path: 

9 """展开路径中的 ~ 和环境变量""" 

10 return Path(os.path.expandvars(os.path.expanduser(path))) 

11 

12 

13def truncate(text: str, max_length: int = 1000, suffix: str = "...") -> str: 

14 """截断文本""" 

15 if len(text) <= max_length: 

16 return text 

17 return text[: max_length - len(suffix)] + suffix 

18 

19 

20def extract_urls(text: str) -> list[str]: 

21 """提取文本中的 URL""" 

22 url_pattern = r"https?://[^\s<>\"]+|www\.[^\s<>\"]+" 

23 return re.findall(url_pattern, text) 

24 

25 

26def slugify(text: str) -> str: 

27 """将文本转换为 slug 格式""" 

28 text = text.lower().strip() 

29 text = re.sub(r"[^\w\s-]", "", text) 

30 text = re.sub(r"[\s_-]+", "-", text) 

31 return text.strip("-") 

32 

33 

34def format_bytes(bytes: int) -> str: 

35 """格式化字节数为可读格式""" 

36 for unit in ["B", "KB", "MB", "GB"]: 

37 if bytes < 1024: 

38 return f"{bytes:.1f} {unit}" 

39 bytes /= 1024 

40 return f"{bytes:.1f} TB"