#!/usr/bin/python
import os
from os import listdir
from os.path import dirname, isdir, isfile, join
from pathlib import Path
from tools import read_file_into_list, read_txt_file
html_tpl = """
道阻且长,行则将至
{category}:
"""
category = os.environ.get("CATEGORY")
sub_dir = os.environ.get("DIR")
if (category is None):
print("[-] Invalid environment variable 'CATEGORY' setting")
exit(-1)
elif (sub_dir is None or isdir(sub_dir) is False):
print("[-] Invalid environment variable 'DIR' setting")
exit(-1)
# 遍历目标目录下 txt 文件,读文件获取文章标题、创建时间和链接,并按创建时间倒序生成列表
cur_dir = dirname(__file__)
target_dir = join(cur_dir, sub_dir)
files = []
for file in listdir(target_dir):
if (isfile(join(target_dir, file)) and file.endswith(".txt")):
files.append(file)
files.sort(reverse=True)
# 记录最新的20篇文章,用于首页最新文章列表展示
# 写入文件前先判断是否已存在
top = files[:20]
# 安全的创建和更新 .top 文件
top_file = join(cur_dir, ".top")
f = Path(top_file)
f.touch(exist_ok=True)
exist_lines = read_file_into_list(top_file)
with open(top_file, "a") as t_file:
for item in top:
line = item + ":::" + target_dir
if not line in exist_lines:
t_file.write(line + "\n")
# 生成指定分类下文章列表
papers = "\n"
for txt_file in files:
txt = read_txt_file(join(target_dir, txt_file))
papers += '{create_time} {title}\n'.format(**txt)
# 生成 html 文件
html_file_path = join(target_dir, "index.html")
with open(html_file_path, "w") as html_file:
print(html_tpl.format(category=category, papers=papers),
file=html_file)
print("[+] Successful build html file: {}".format(html_file_path))