forked from dongweiming/lyanna
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hexo-exporter.py
68 lines (53 loc) · 1.82 KB
/
hexo-exporter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import glob
import argparse
from tortoise import run_async
from tortoise.exceptions import IntegrityError
from ext import init_db
from models import Post
parser = argparse.ArgumentParser(description='Hexo Exporter')
parser.add_argument('source_dirs', metavar='DIR', type=str, nargs='+',
help='Markdown file directories')
parser.add_argument('--uid', type=int, help='Author ID')
args = parser.parse_args()
source_dirs = args.source_dirs
if not args.uid:
print('the `uid` argument are required!')
exit(1)
files = []
for dir in source_dirs:
files.extend(sum([glob.glob(f'{dir}/*.{pattern}')
for pattern in ('md', 'markdown')], []))
files = sorted(files, reverse=False)
async def write_post(file):
title = None
date = None
tags = []
flag = False
with open(file) as f:
for i in f:
i = i.strip()
if i == '---' and flag:
break
if i == '---':
flag = True
continue
if 'title:' in i:
title = i.split(':')[1].strip().replace('"', '')
elif 'date:' in i:
date = i.split(':')[1].strip()
elif 'tags' in i:
i = i.split(':')[1].strip()[1:-1] if '[' in i else i.split(':')[1] # noqa
tags = filter(None, map(lambda x: x.strip(), i.split(',')))
content = ''.join(f.readlines())
try:
await Post.create(title=title, content=content, tags=tags,
author_id=args.uid, slug='', summary='',
status=Post.STATUS_ONLINE, created_at=date)
except IntegrityError:
...
async def main():
await init_db()
for f in files:
await write_post(f)
if __name__ == '__main__':
run_async(main())