"""同步笔记用"""
import os
import frontmatter
import re
import shutil
default_dir = "articles"
article_attribute = "article"
def _need_sync(file_path: str, output_dir: str) -> bool:
"""
判断是否要同步笔记
1 笔记里存在 属性 publish:true
2 笔记日期 > 已发布笔记日期
"""
post = frontmatter.load(file_path)
if not post.get(article_attribute):
return False
old_file = os.path.join(output_dir, default_dir, os.path.basename(file_path))
if os.path.exists(old_file):
current_date = post.get("date")
old_date = frontmatter.load(old_file).get("date")
if current_date == old_date:
return False
return True
def sync_pic(file_path: str, output_dir: str) -> None:
"""copy pic to output dir"""
with open(file_path, "r", encoding="utf-8") as f:
markdown_body = f.read()
pic_str_list = re.findall(r"\!\[.*\]\((.*)\)", markdown_body)
for pic_str in pic_str_list:
print(f" find pic {pic_str}")
pic_file = os.path.join(os.path.dirname(file_path), pic_str)
if not os.path.exists(pic_file):
continue
output_pic_file = os.path.join(output_dir, "images", os.path.basename(pic_file))
print(f" copy {os.path.abspath(pic_file)} to {output_pic_file}")
shutil.copyfile(pic_file, output_pic_file)
return
def handler_file(root: str, file: str, output_dir: str) -> None:
"""处理单个 markdown 文件"""
file_path = os.path.join(root, file)
if not _need_sync(file_path, output_dir):
return
output_file_path = os.path.join(output_dir, default_dir, file)
print(f"copy {file_path} to {output_file_path}")
shutil.copyfile(file_path, output_file_path)
sync_pic(file_path, output_dir)
def main(
markdown_path: str = r"E:\PycharmProjects\WG\note",
output_dir: str = r"E:\PycharmProjects\AngusWG\docs",
) -> None:
"""
遍历 note 文件夹 articles 文件夹下所有的 md 文件
并同步到另一边文件夹下的 articles 文件夹下
- sorce_note_dir: 笔记文件夹
- articles: 可以发布的文章文件夹
- a.md (article: true)
- b.md (article: true)
- c.md (article: false)
- images: 笔记图片 文件夹
- a1.png
- a2.png
- c1.png
- target_note_dir: 笔记文件夹
- articles: 已经发布的博客文件夹
- a.md (article: true)
- b.md (article: true)
- images: 博客图片文件夹
- a1.png
- a2.png
"""
root = os.path.join(markdown_path, default_dir)
for file in os.listdir(root):
if file.endswith(".md"):
handler_file(root, file, output_dir)
if __name__ == "__main__":
main()