|
| 1 | +""" |
| 2 | +TOML 工具函数 |
| 3 | +
|
| 4 | +提供 TOML 文件的格式化保存功能,确保数组等元素以美观的多行格式输出。 |
| 5 | +""" |
| 6 | + |
| 7 | +from typing import Any |
| 8 | +import re |
| 9 | +import tomlkit |
| 10 | +from tomlkit.items import AoT, Array, Table |
| 11 | + |
| 12 | + |
| 13 | +def _format_toml_value(obj: Any, threshold: int, depth: int = 0) -> Any: |
| 14 | + """递归格式化 TOML 值,将数组转换为多行格式""" |
| 15 | + # 处理 AoT (Array of Tables) - 保持原样,递归处理内部 |
| 16 | + if isinstance(obj, AoT): |
| 17 | + for item in obj: |
| 18 | + _format_toml_value(item, threshold, depth) |
| 19 | + return obj |
| 20 | + |
| 21 | + # 处理字典类型 (dict 或 Table) |
| 22 | + if isinstance(obj, (dict, Table)): |
| 23 | + for k, v in obj.items(): |
| 24 | + obj[k] = _format_toml_value(v, threshold, depth) |
| 25 | + return obj |
| 26 | + |
| 27 | + # 处理列表类型 (list 或 Array) |
| 28 | + if isinstance(obj, (list, Array)): |
| 29 | + if isinstance(obj, list) and not isinstance(obj, Array) and obj and isinstance(obj[0], (dict, Table)): |
| 30 | + for i, item in enumerate(obj): |
| 31 | + obj[i] = _format_toml_value(item, threshold, depth) |
| 32 | + return obj |
| 33 | + |
| 34 | + should_multiline = depth == 0 and len(obj) > threshold |
| 35 | + |
| 36 | + if isinstance(obj, Array): |
| 37 | + obj.multiline(should_multiline) |
| 38 | + for i, item in enumerate(obj): |
| 39 | + obj[i] = _format_toml_value(item, threshold, depth + 1) |
| 40 | + return obj |
| 41 | + |
| 42 | + arr = tomlkit.array() |
| 43 | + arr.multiline(should_multiline) |
| 44 | + |
| 45 | + for item in obj: |
| 46 | + arr.append(_format_toml_value(item, threshold, depth + 1)) |
| 47 | + return arr |
| 48 | + |
| 49 | + return obj |
| 50 | + |
| 51 | + |
| 52 | +def _update_toml_doc(target: Any, source: Any) -> None: |
| 53 | + """ |
| 54 | + 递归合并字典,将 source 的值更新到 target 中,保留 target 的注释和格式。 |
| 55 | + """ |
| 56 | + if isinstance(source, list) or not isinstance(source, dict) or not isinstance(target, dict): |
| 57 | + return |
| 58 | + |
| 59 | + for key, value in source.items(): |
| 60 | + if key == "version": |
| 61 | + continue |
| 62 | + if key in target: |
| 63 | + target_value = target[key] |
| 64 | + if isinstance(value, dict) and isinstance(target_value, dict): |
| 65 | + _update_toml_doc(target_value, value) |
| 66 | + else: |
| 67 | + try: |
| 68 | + target[key] = tomlkit.item(value) |
| 69 | + except (TypeError, ValueError): |
| 70 | + target[key] = value |
| 71 | + else: |
| 72 | + try: |
| 73 | + target[key] = tomlkit.item(value) |
| 74 | + except (TypeError, ValueError): |
| 75 | + target[key] = value |
| 76 | + |
| 77 | + |
| 78 | +def save_toml_with_format( |
| 79 | + data: Any, file_path: str, multiline_threshold: int = 1, preserve_comments: bool = True |
| 80 | +) -> None: |
| 81 | + """ |
| 82 | + 格式化 TOML 数据并保存到文件。 |
| 83 | +
|
| 84 | + Args: |
| 85 | + data: 要保存的数据(dict 或 tomlkit 文档) |
| 86 | + file_path: 保存路径 |
| 87 | + multiline_threshold: 数组多行格式化阈值,-1 表示不格式化 |
| 88 | + preserve_comments: 是否保留原文件的注释和格式 |
| 89 | + """ |
| 90 | + import os |
| 91 | + |
| 92 | + from tomlkit import TOMLDocument |
| 93 | + |
| 94 | + if preserve_comments and os.path.exists(file_path) and not isinstance(data, TOMLDocument): |
| 95 | + with open(file_path, "r", encoding="utf-8") as f: |
| 96 | + doc = tomlkit.load(f) |
| 97 | + _update_toml_doc(doc, data) |
| 98 | + data = doc |
| 99 | + |
| 100 | + formatted = _format_toml_value(data, multiline_threshold) if multiline_threshold >= 0 else data |
| 101 | + output = tomlkit.dumps(formatted) |
| 102 | + output = re.sub(r"\n{3,}", "\n\n", output) |
| 103 | + with open(file_path, "w", encoding="utf-8") as f: |
| 104 | + f.write(output) |
0 commit comments