(file_path)
| 109 | |
| 110 | # 排序脚本元数据 |
| 111 | def sort_userscript_section(file_path): |
| 112 | with open(file_path, "r", encoding="utf-8") as file: |
| 113 | content = file.readlines() |
| 114 | # 找到 // ==UserScript== 和 // ==/UserScript== 的范围 |
| 115 | start_index = None |
| 116 | end_index = None |
| 117 | for i, line in enumerate(content): |
| 118 | if "// ==UserScript==" in line: |
| 119 | start_index = i |
| 120 | elif "// ==/UserScript==" in line: |
| 121 | end_index = i |
| 122 | break |
| 123 | # 如果没有找到对应范围,直接返回 |
| 124 | if start_index is None or end_index is None: |
| 125 | print("未找到有效的 UserScript 区域") |
| 126 | return |
| 127 | # 提取范围内的内容 |
| 128 | userscript_section = content[start_index + 1:end_index] |
| 129 | # 按类别分组 |
| 130 | descriptions = [] |
| 131 | names = [] |
| 132 | others = [] |
| 133 | for line in userscript_section: |
| 134 | if re.match(r"// @description", line): |
| 135 | descriptions.append(line.strip()) |
| 136 | elif re.match(r"// @name", line) and not re.match(r"// @namespace", line): |
| 137 | names.append(line.strip()) |
| 138 | else: |
| 139 | others.append(line.strip()) |
| 140 | # 按语言后缀排序(按规范排列规则,语言后缀优先) |
| 141 | |
| 142 | def sort_by_suffix(lines): |
| 143 | return sorted(lines, key=lambda x: re.search(r"[:\-]([a-zA-Z\-]*)", x).group(1) if re.search(r"[:\-]([a-zA-Z\-]*)", x) else "") |
| 144 | |
| 145 | sorted_descriptions = sort_by_suffix(descriptions) |
| 146 | sorted_names = sort_by_suffix(names) |
| 147 | # 合并排序结果 |
| 148 | sorted_section = sorted_names + sorted_descriptions + others |
| 149 | # 替换原始内容中的 UserScript 区域 |
| 150 | content[start_index + 1:end_index] = [line + "\n" for line in sorted_section] |
| 151 | # 写入文件 |
| 152 | with open(file_path, "w", encoding="utf-8", newline='\n') as file: |
| 153 | file.writelines(content) |
| 154 | |
| 155 | |
| 156 | def format_str(input_str, lang=""): |
no test coverage detected