Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
Sagi-Rastar committed Oct 26, 2024
1 parent f616920 commit 64f9a66
Show file tree
Hide file tree
Showing 4 changed files with 107 additions and 11 deletions.
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,5 @@ jobs:
- run: pip install mkdocs-material
- run: pip install mkdocs-macros-plugin
- run: pip install mkdocs-changelog-plugin
- run: mkdocs build
- run: mkdocs gh-deploy --force
4 changes: 2 additions & 2 deletions .obsidian/workspace.json
Original file line number Diff line number Diff line change
Expand Up @@ -174,8 +174,9 @@
"terminal:Open terminal": false
}
},
"active": "cbf64a1ff82d7d66",
"active": "3fb23f5db3f883e4",
"lastOpenFiles": [
"docs/_CS/index.md",
"docs/_Embedded/241010-硬件设计相关知识/image-20241017111440015.png",
"docs/_Embedded/ESP32项目汇总.md",
"docs/_秋招/秋招进度.md",
Expand Down Expand Up @@ -205,7 +206,6 @@
"site/_秋招/秋招进度/index.html",
"site/_秋招/秋招进度",
"site/_秋招/常见问题起草模板/index.html",
"site/assets/images/favicon.png",
"docs/_Embedded/240924-通讯协议总结.md",
"docs/_CS/240905-C语言语法特性.md",
"docs/_Embedded/240905-更新storage以及mqtt模块部分,逐步实现私有json协议.md",
Expand Down
9 changes: 9 additions & 0 deletions docs/_CS/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
changelog: true
render_macros: true
---


{{m generate_changelog_yaml_for_subfolder('_CS') m}}

{{ _CS }}
104 changes: 95 additions & 9 deletions mymacros.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import json
import re # 导入正则表达式模块


class DoubleQuotedDumper(yaml.Dumper):
def represent_scalar(self, tag, value, style=None):
if style is None:
Expand Down Expand Up @@ -45,7 +46,7 @@ def generate_grid_cards(dir):
# 使用文件夹名和 "index.md" 生成 MkDocs 路径
doc_path = f"{folder_name}"
grid_cards.append(
f"- :material-clock-fast:{{ '.lg .middle' }} [__{title}__](/sagi_database/{doc_path})")
f"- :material-clock-fast:{{ '.lg .middle' }} [__{title}__](/{doc_path})")
return "\n".join(grid_cards)
except Exception as e:
return f"Error generating grid cards: {e}"
Expand All @@ -59,7 +60,8 @@ def generate_changelog_yaml():
# 遍历 docs 目录下的所有以 '_' 开头的文件夹
for folder_name in os.listdir('docs'): # 列出docs目录中的所有文件和文件夹
folder_path = os.path.join('docs', folder_name) # 构建每个文件夹的完整路径
if os.path.isdir(folder_path) and folder_name.startswith('_'): # 检查路径是否为目录且目录名为_开头
# 检查路径是否为目录且目录名为_开头
if os.path.isdir(folder_path) and folder_name.startswith('_'):
# 遍历文件夹下所有的以 yymdd- 开头的 md 文件
for file_name in os.listdir(folder_path):
if file_name.endswith('.md') and re.match(r'^\d{6}-', file_name):
Expand All @@ -69,12 +71,14 @@ def generate_changelog_yaml():
date_str = file_name.split('-')[0]
try:
# 将日期字符串转换为日期对象
date_obj = datetime.datetime.strptime(date_str, "%y%m%d")
date_obj = datetime.datetime.strptime(
date_str, "%y%m%d")
# 将日期对象转换为可读格式
readable_time = date_obj.strftime("%Y-%m-%d")
year = date_obj.strftime("%Y")
# 查找或创建年份条目
year_entry = next((item for item in changelog_data if year in item), None)
year_entry = next(
(item for item in changelog_data if year in item), None)
if not year_entry:
year_entry = {year: []}
changelog_data.append(year_entry)
Expand All @@ -101,17 +105,20 @@ def generate_changelog_yaml():
}]
})
# 对年份条目中的日期进行降序排序
year_entry[year] = sorted(year_entry[year], key=lambda x: list(x.keys())[0], reverse=True)
year_entry[year] = sorted(
year_entry[year], key=lambda x: list(x.keys())[0], reverse=True)
except ValueError:
# 如果日期格式不正确,记录调试信息
debug_info.append(f"Skipping file with invalid date format: {file_name}")
debug_info.append(
f"Skipping file with invalid date format: {file_name}")
continue
# 将调试信息添加到 changelog_data 中
# changelog_data.append({"debug_info": debug_info})
# 保存到 YAML 文件
with open('docs/changelog.yml', 'w', encoding='utf-8') as yaml_file:
yaml.dump(changelog_data, yaml_file, allow_unicode=True, default_flow_style=False, sort_keys=False)
return f"## Timeline "# "Changelog YAML generated successfully."
yaml.dump(changelog_data, yaml_file, allow_unicode=True,
default_flow_style=False, sort_keys=False)
return f"## Timeline " # "Changelog YAML generated successfully."
except Exception as e:
# 记录错误信息
# changelog_data.append({"error": f"Error generating changelog YAML: {e}"})
Expand All @@ -120,6 +127,84 @@ def generate_changelog_yaml():
# yaml.dump(changelog_data, yaml_file, allow_unicode=True, default_flow_style=False)
return f"Error generating changelog YAML: {e}"

@env.macro
def generate_changelog_yaml_for_subfolder(subfolder_name):
"""生成指定次级文件夹中符合 changelog 插件格式的 YAML 内容,并添加到 changelog.yml 文件中。"""
changelog_data = [] # 用于存储新的 changelog 数据
debug_info = [] # 用于存储调试信息
try:
# 构建次级文件夹的完整路径
subfolder_path = os.path.join('docs', subfolder_name)
if os.path.isdir(subfolder_path): # 检查路径是否为目录
# 遍历次级文件夹下所有的以 yymdd- 开头的 md 文件
for file_name in os.listdir(subfolder_path):
if file_name.endswith('.md') and re.match(r'^\d{6}-', file_name):
# 构建文件的完整路径
full_path = os.path.join(subfolder_path, file_name)
# 从文件名中提取日期
date_str = file_name.split('-')[0]
try:
# 将日期字符串转换为日期对象
date_obj = datetime.datetime.strptime(
date_str, "%y%m%d")
# 将日期对象转换为可读格式
readable_time = date_obj.strftime("%Y-%m-%d")
# 查找或创建日期条目
found = False
for entry in changelog_data:
if readable_time in entry: # 如果找到日期条目
found = True
entry[readable_time].append({
"newpage": {
"text": f" [ {subfolder_name.replace('_', '')} ] > {'-'.join(file_name.split('-')[1:]).replace('.md', '')}",
"href": f"/sagi_database/{subfolder_name}/{file_name.replace('.md', '')}"
}
})
break
# 如果没有找到日期条目,则创建新的
if not found:
changelog_data.append({
readable_time: [{
"newpage": {
"text": f" [ {subfolder_name.replace('_', '')} ] > {'-'.join(file_name.split('-')[1:]).replace('.md', '')}",
"href": f"/sagi_database/{subfolder_name}/{file_name.replace('.md', '')}"
}
}]
})
# 对日期条目进行降序排序
changelog_data = sorted(
changelog_data, key=lambda x: list(x.keys())[0], reverse=True)
except ValueError:
# 如果日期格式不正确,记录调试信息
debug_info.append(
f"Skipping file with invalid date format: {file_name}")
continue
else:
return f"Error: {subfolder_name} is not a valid directory."

# 读取现有的 changelog.yml 文件
changelog_file_path = 'docs/changelog.yml'
if os.path.exists(changelog_file_path):
with open(changelog_file_path, 'r', encoding='utf-8') as yaml_file:
existing_data = yaml.load(
yaml_file, Loader=yaml.FullLoader) or []
else:
existing_data = []

# 添加新的次级文件夹条目
new_entry = {subfolder_name: changelog_data}
existing_data.append(new_entry)

# 保存合并后的数据到 changelog.yml 文件
with open(changelog_file_path, 'w', encoding='utf-8') as yaml_file:
yaml.dump(existing_data, yaml_file, allow_unicode=True,
default_flow_style=False, sort_keys=False)

# "Changelog YAML updated successfully for {subfolder_name}."
return f"## Timeline "
except Exception as e:
return f"Error generating changelog YAML for {subfolder_name}: {e}"

@env.macro
def read_changelog_yaml(file_path):
"""读取 YAML 文件并处理可能的编码问题。"""
Expand All @@ -130,8 +215,9 @@ def read_changelog_yaml(file_path):
with open(file_path, 'rb') as yaml_file:
content = yaml_file.read()
return yaml.load(content.decode('utf-8', errors='ignore'), Loader=yaml.FullLoader)

# 注册宏
env.macro(generate_changelog_yaml)
env.macro(list_md_files)
env.macro(generate_grid_cards)
env.macro(generate_changelog_yaml_for_subfolder)

0 comments on commit 64f9a66

Please sign in to comment.