Files
soul-yongping/scripts/sync_book_to_feishu_export.py
2026-03-07 22:58:43 +08:00

82 lines
3.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
"""
《一场soul的创业实验》全书 → 飞书同步用导出
按飞书「创业实验」下结构导出所有 md 正文,便于复制到飞书对应子页面。
用法:
python3 sync_book_to_feishu_export.py [--book-root /path/to/书] [--out ./feishu_export]
"""
import argparse
import os
from pathlib import Path
# 默认书稿根目录(与上传 README 一致)
DEFAULT_BOOK_ROOT = Path("/Users/karuo/Documents/个人/2、我写的书/《一场soul的创业实验》")
FEISHU_WIKI_URL = "https://cunkebao.feishu.cn/wiki/FNP6wdvNKij7yMkb3xCce0CYnpd"
def collect_md_files(book_root: Path):
"""收集所有 md返回 (相对路径, 绝对路径) 列表,按路径排序"""
book_root = book_root.resolve()
out = []
for p in book_root.rglob("*.md"):
if not p.name.startswith("."):
try:
rel = p.relative_to(book_root)
out.append((str(rel), p))
except ValueError:
pass
out.sort(key=lambda x: x[0])
return out
def main():
parser = argparse.ArgumentParser(description="导出全书 md 供飞书同步")
parser.add_argument("--book-root", type=Path, default=DEFAULT_BOOK_ROOT, help="书稿根目录")
parser.add_argument("--out", type=Path, default=Path(__file__).resolve().parent / "feishu_export", help="导出目录")
args = parser.parse_args()
book_root = args.book_root.resolve()
if not book_root.is_dir():
print(f"错误: 书稿根目录不存在: {book_root}")
return 1
out_dir = args.out.resolve()
out_dir.mkdir(parents=True, exist_ok=True)
files = collect_md_files(book_root)
print(f"找到 {len(files)} 个 md 文件,导出到 {out_dir}")
# 导出:按「篇/章/节」扁平化命名,避免文件名过长或非法字符
for rel, abspath in files:
name = rel.replace("/", "_").replace("", "_").replace("?", "_").replace(":", "_")
if len(name) > 180:
name = name[:177] + ".md"
elif not name.endswith(".md"):
name = name + ".md"
dest = out_dir / name
try:
content = abspath.read_text(encoding="utf-8")
dest.write_text(content, encoding="utf-8")
except Exception as e:
print(f" 跳过 {rel}: {e}")
# 生成索引
index_path = out_dir / "_飞书同步索引.txt"
with open(index_path, "w", encoding="utf-8") as f:
f.write(f"飞书知识库:{FEISHU_WIKI_URL}\n")
f.write("本书根节点名称:创业实验\n\n")
f.write("以下文件与「飞书同步说明.md」中的结构对应复制到飞书对应子页面即可。\n\n")
for rel, _ in files:
name = rel.replace("/", "_").replace("", "_").replace("?", "_").replace(":", "_")
if not name.endswith(".md"):
name = name + ".md"
f.write(f" {rel}\n → 导出文件: {name}\n\n")
print(f"已生成索引: {index_path}")
return 0
if __name__ == "__main__":
exit(main())