XXX.github.io
Nobody has claimed this yet.
- Dominant language
- HTML
- Stars
- 0
- Forks
- 0
- PR merge metrics
- No merged PRs in 30d
Description
XXX.github.io#!/usr/bin/env python3
-- coding: utf-8 --
import os
import sys
import json
import requests
from datetime import datetime
import argparse
全局配置
BLOG_BASE_FILE = "blogBase.json"
DOCS_DIR = "docs"
BACKUP_DIR = "backup"
ISSUE_CONTENT_KEY = "content"
def init_dirs():
"""初始化必要目录(docs/backup)"""
for dir_name in [DOCS_DIR, BACKUP_DIR]:
if not os.path.exists(dir_name):
os.makedirs(dir_name)
print(f"✅ 创建目录:{dir_name}")
def load_blog_base():
"""加载博客基础配置(blogBase.json),确保 posts 字段存在"""
if os.path.exists(BLOG_BASE_FILE):
try:
with open(BLOG_BASE_FILE, "r", encoding="utf-8") as f:
blog_base = json.load(f)
# 检查并补充缺失的字段(关键修复)
if "posts" not in blog_base:
blog_base["posts"] = []
print("⚠️ 修复配置文件:添加缺失的 posts 字段")
if "title" not in blog_base:
blog_base["title"] = "My Gmeek Blog"
if "subtitle" not in blog_base:
blog_base["subtitle"] = "Auto-generated by Gmeek"
if "author" not in blog_base:
blog_base["author"] = os.getenv("GITHUB_REPOSITORY_OWNER", "Anonymous")
if "last_update" not in blog_base:
blog_base["last_update"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# 保存修复后的配置
with open(BLOG_BASE_FILE, "w", encoding="utf-8") as f:
json.dump(blog_base, f, ensure_ascii=False, indent=2)
return blog_base
except Exception as e:
print(f"⚠️ 配置文件格式错误,重新生成默认配置:{str(e)}")
os.remove(BLOG_BASE_FILE) # 删除损坏的文件
# 生成全新的默认配置(确保包含所有必需字段)
default_base = {
"title": "My Gmeek Blog",
"subtitle": "Auto-generated by Gmeek",
"author": os.getenv("GITHUB_REPOSITORY_OWNER", "Anonymous"),
"last_update": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"posts": [] # 必含字段,存储文章列表
}
with open(BLOG_BASE_FILE, "w", encoding="utf-8") as f:
json.dump(default_base, f, ensure_ascii=False, indent=2)
print(f"✅ 生成全新默认配置文件:{BLOG_BASE_FILE}")
return default_base
def fetch_issue_content(github_token, repo, issue_number):
"""从 GitHub Issue 获取内容(如果指定了 issue_number)"""
if not issue_number or issue_number == "":
print("ℹ️ 未指定 Issue 编号,跳过获取 Issue 内容")
return None
url = f"https://api.github.com/repos/{repo}/issues/{issue_number}"
headers = {
"Authorization": f"token {github_token}",
"Accept": "application/vnd.github.v3+json"
}
try:
response = requests.get(url, headers=headers)
response.raise_for_status()
issue = response.json()
# 返回 Issue 的标题和内容
return {
"title": issue["title"],
"content": issue["body"],
"created_at": issue["created_at"],
"updated_at": issue["updated_at"]
}
except Exception as e:
print(f"⚠️ 获取 Issue 内容失败:{str(e)}")
return None
def generate_html(blog_base, issue_content=None):
"""生成 HTML 博客页面"""
# 1. 更新博客基础信息
blog_base["last_update"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# 2. 如果有 Issue 内容,添加为新文章(确保 posts 是列表)
if issue_content and isinstance(blog_base["posts"], list):
new_post = {
"id": len(blog_base["posts"]) + 1,
"title": issue_content["title"],
"content": issue_content["content"].replace("\n", "<br>"),
"created_at": issue_content["created_at"].split("T")[0],
"updated_at": issue_content["updated_at"].split("T")[0]
}
blog_base["posts"].append(new_post)
# 保存更新后的 blogBase.json
with open(BLOG_BASE_FILE, "w", encoding="utf-8") as f:
json.dump(blog_base, f, ensure_ascii=False, indent=2)
print(f"✅ 新增文章:{issue_content['title']}")
# 3. 生成首页 HTML(关键修复:CSS 中的 {} 转义为 {{}})
html_template = """
<title>{title}</title>
<style>
body {{ max-width: 1200px; margin: 0 auto; padding: 20px; font-family: Arial, sans-serif; }}
.header {{ text-align: center; margin-bottom: 50px; }}
.post {{ margin: 30px 0; padding: 20px; border-bottom: 1px solid #eee; }}
.post-title {{ color: #2c3e50; margin-bottom: 10px; }}
.post-meta {{ color: #7f8c8d; font-size: 0.9em; margin-bottom: 15px; }}
.post-content {{ line-height: 1.6; color: #34495e; }}
.footer {{ text-align: center; margin-top: 50px; color: #7f8c8d; }}
.no-posts {{ text-align: center; padding: 50px; color: #7f8c8d; }}
</style>
{title}
{subtitle}
作者:{author} | 最后更新:{last_update}
<div class="posts">
{posts_html}
</div>
<div class="footer">
<p>Generated by Gmeek | <a href="https://github.com/Meekdai/Gmeek" target="_blank">Gmeek Official</a></p>
</div>
"""
# 生成文章列表 HTML(处理无文章的情况)
if isinstance(blog_base["posts"], list) and len(blog_base["posts"]) > 0:
posts_html = ""
for post in reversed(blog_base["posts"]): # 倒序显示(最新的在前面)
posts_html += f"""
<div class="post">
<h2 class="post-title">{post['title']}</h2>
<div class="post-meta">创建时间:{post['created_at']} | 更新时间:{post['updated_at']}</div>
<div class="post-content">{post['content']}</div>
</div>
"""
else:
posts_html = '<div class="no-posts">暂无文章,快去创建 Issue 生成第一篇博客吧!</div>'
# 填充模板并生成 index.html
index_html = html_template.format(
title=blog_base["title"],
subtitle=blog_base["subtitle"],
author=blog_base["author"],
last_update=blog_base["last_update"],
posts_html=posts_html
)
# 保存到 docs 目录(GitHub Pages 部署目录)
index_path = os.path.join(DOCS_DIR, "index.html")
with open(index_path, "w", encoding="utf-8") as f:
f.write(index_html)
print(f"✅ 生成首页 HTML:{index_path}")
def backup_blog_base():
"""备份 blogBase.json 到 backup 目录"""
if os.path.exists(BLOG_BASE_FILE):
backup_path = os.path.join(BACKUP_DIR, f"blogBase_{datetime.now().strftime('%Y%m%d%H%M%S')}.json")
with open(BLOG_BASE_FILE, "r", encoding="utf-8") as f_in, open(backup_path, "w", encoding="utf-8") as f_out:
json.dump(json.load(f_in), f_out, ensure_ascii=False, indent=2)
print(f"✅ 备份配置文件:{backup_path}")
def main():
# 解析命令行参数
parser = argparse.ArgumentParser(description="Gmeek Blog Generator")
parser.add_argument("github_token", help="GitHub Token for API access")
parser.add_argument("repo", help="GitHub Repository (owner/repo)")
parser.add_argument("--issue_number", help="GitHub Issue Number to fetch content", default="")
args = parser.parse_args()
try:
print("🚀 开始执行 Gmeek 博客生成流程...")
# 1. 初始化目录
init_dirs()
# 2. 加载博客基础配置(确保 posts 字段存在)
blog_base = load_blog_base()
# 3. (可选)从 Issue 获取内容
issue_content = fetch_issue_content(args.github_token, args.repo, args.issue_number)
# 4. 生成 HTML 页面
generate_html(blog_base, issue_content)
# 5. 备份配置文件
backup_blog_base()
print("🎉 Gmeek 博客生成流程执行完成!")
except Exception as e:
print(f"❌ 执行失败:{str(e)}")
# 输出详细错误栈(方便调试)
import traceback
traceback.print_exc()
sys.exit(1)
if name == "main":
main()
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
The issue body contains a Python entry point in main() that creates docs/index.html, updates blogBase.json, and writes backups under backup. Start by determining the missing requested behavior; no failing test, target file change, or completion criteria are provided, so the intended outcome cannot be verified from the issue alone.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- html, python
- Domain
- tooling, web-dev
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 15/100