import os import shutil import frontmatter from pathlib import Path # 配置路径 CONTENT_DIR = 'content' SOURCE_SECTIONS = ['essays', 'posts'] TARGET_SECTION = 'articles' def process_file(file_path, root_section_name): """ 处理 Markdown 文件 file_path: 当前文件的 Path 对象 root_section_name: 所属的根分区名 ('essays' 或 'posts') """ # 1. 加载 Front Matter (使用 TOML) try: with open(file_path, 'r', encoding='utf-8') as f: post = frontmatter.load(f, handler=frontmatter.TOMLHandler()) except Exception as e: print(f"解析错误 {file_path}: {e}") return # 2. 确定基础标识 (Stem) # 如果是 index.md,标识取其父文件夹名;否则取文件名本身 is_bundle = (file_path.name == 'index.md') file_stem = file_path.parent.name if is_bundle else file_path.stem # 3. 确定最终文件名与 Slug 逻辑 # 只有当 slug 存在且不为空字符串时才使用它 slug = post.get('slug') final_identifier = slug if (slug and str(slug).strip()) else file_stem # 4. 构造 URL # 保持原有的 section 路径前缀 if 'url' not in post: post['url'] = f"/{root_section_name}/{final_identifier}/" # 5. 确定目标路径 (统一移到 articles/ 下) target_dir = Path(CONTENT_DIR) / TARGET_SECTION target_dir.mkdir(parents=True, exist_ok=True) target_file_path = target_dir / f"{final_identifier}.md" # 6. 回写并清理 new_content = frontmatter.dumps(post, handler=frontmatter.TOMLHandler()) with open(target_file_path, 'w', encoding='utf-8') as f: f.write(new_content) # 清理原文件/文件夹 if is_bundle: shutil.rmtree(file_path.parent) else: file_path.unlink() print(f"✓ 转换: {file_path.relative_to(CONTENT_DIR)} -> articles/{final_identifier}.md") def main(): content_root = Path(CONTENT_DIR) for section in SOURCE_SECTIONS: section_path = content_root / section if not section_path.exists(): continue print(f"\n正在递归扫描分区: {section}...") # 使用 rglob 递归查找所有 .md 文件 (包括二级目录、Page Bundles) # 注意:使用 list 固化搜索结果,因为我们会边处理边删除 all_md_files = list(section_path.rglob("*.md")) # 排除 _index.md (分区首页通常不需要这样迁移) files_to_process = [f for f in all_md_files if f.name != "_index.md"] for md_file in files_to_process: if not md_file.exists(): # 防止 bundle 模式下 index.md 已被父目录删除 continue process_file(md_file, section) print("\n--- 迁移完成 ---") if __name__ == "__main__": main()