Last active
December 24, 2020 09:52
-
-
Save changkun/46ab1ac4a60e98b9de5967cf15b427f9 to your computer and use it in GitHub Desktop.
为 Hexo 博客文章分配全局唯一 ID
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import yaml | |
import glob | |
import time | |
POST_DIR = 'source/_posts/' | |
def loader(): | |
posts = glob.glob(POST_DIR + '*.md') | |
settings = [] | |
for post in posts: | |
raw = open(post).read() | |
head = raw.split('---')[1] | |
try: | |
setting = yaml.load(head) | |
if set(['title', 'date', 'tags', 'id']).issubset(setting): | |
setting['path'] = post | |
settings.append(setting) | |
else: | |
print('YAML parsing error: ', post) | |
except Exception as e: | |
print('YAML head not avaliable: ', post) | |
return len(settings) == len(posts), settings | |
def id_repair(): | |
all_correct, settings = loader() | |
if all_correct: | |
print('ALL SUCCESS') | |
fixed = sorted(settings, key=lambda head: head['date']) | |
for index, fix in enumerate(fixed): | |
fix['id'] = index + 1 | |
return fixed, settings | |
else: | |
print('PLEASE FIX YAML HEAD FORMAT FIRST') | |
def id_writer(): | |
# goal: | |
# repair id: ../images/posts/old/* => /images/posts/fixed/* | |
fixed, old = id_repair() | |
for i, fix in enumerate(fixed): | |
try: | |
with open(fix['path'], 'r', encoding='utf-8') as f: | |
raw = f.read() | |
try: | |
content = raw.split('---', 1)[1].split('---', 1)[1] | |
content = content.replace('](../images/posts/', '](/images/posts/') | |
content = content.replace( | |
'/images/posts/' + str(old[i]['id']), '/images/posts/' + str(fix['id'])) | |
except Exception as e: | |
print('ERROR: ', fix['path']) | |
print(e) | |
with open(fix['path'], 'w', encoding='utf-8') as f: | |
f.write('---\n') | |
stream = yaml.dump( | |
fix, default_flow_style=False, allow_unicode=True) | |
f.write(stream.replace('\n- ', '\n - ')) | |
f.write('---') | |
f.write(content) | |
f.close() | |
print('SUCCESS: ', fix['path']) | |
except Exception as e: | |
print('FAILED: ', fix['path']) | |
print('REASON: ', e) | |
def main(): | |
id_writer() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment