From 70ed765fc8bf39eefeb4095c699e409aa7eb38d7 Mon Sep 17 00:00:00 2001 From: Dnomd343 Date: Tue, 27 Dec 2022 17:46:36 +0800 Subject: [PATCH] feat: gitbook loader --- src/release/common.py | 12 ++++++--- src/release/gitbook.py | 56 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 3 deletions(-) create mode 100644 src/release/gitbook.py diff --git a/src/release/common.py b/src/release/common.py index 1312e3c..316879e 100644 --- a/src/release/common.py +++ b/src/release/common.py @@ -12,7 +12,7 @@ dataPath = os.path.join(rootPath, './release/') metadataFile = os.path.join(rootPath, './assets/metadata.json') -def loadData(jsonName: str) -> dict: +def loadData(jsonName: str) -> dict: # load book data from json file content = json.loads(open( os.path.join(dataPath, '%s.json' % jsonName) ).read()) @@ -23,5 +23,11 @@ def loadData(jsonName: str) -> dict: } -if __name__ == '__main__': - print(loadData(sys.argv[1])) +def saveFile(fileName: str, content: str) -> None: # save into file + with open(fileName, 'w') as fileObj: + fileObj.write(content) + + +def createFolder(folderName: str) -> None: # create folder + if not os.path.exists(folderName): + os.mkdir(folderName) diff --git a/src/release/gitbook.py b/src/release/gitbook.py new file mode 100644 index 0000000..f774d58 --- /dev/null +++ b/src/release/gitbook.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +import os +import re +from common import loadData +from common import saveFile +from common import createFolder + +workDir = './temp/' +contentDir = os.path.join(workDir, './content/') + + +def initFolder() -> None: + createFolder(workDir) + createFolder(contentDir) + + +def loadChapter(caption: str, content: list) -> str: + chapterNum = re.search(r'^第(\d+)章', caption)[1] + chapterNum = '0' * (3 - len(chapterNum)) + chapterNum # add `0` prefix + fileName = 'chapter-%s.md' % chapterNum + saveFile( + os.path.join(workDir, './content/', fileName), + '# %s\n\n%s\n' % (caption, '\n\n'.join(content)) + ) + return fileName + + +def loadChapters(chapters: dict) -> dict: + catalog = {} + for (title, chapter) in chapters.items(): + catalog[title] = loadChapter(title, chapter) + return catalog + + +def loadCover(metadata: dict) -> None: + cover = '---\ndescription: 作者:%s\n---\n\n# %s\n\n' % (metadata['author'], metadata['name']) + cover += '
\n\n' + cover += '\n>\n'.join(['> %s' % x for x in metadata['desc']]) + saveFile(os.path.join(workDir, 'README.md'), cover) + + +def loadSummary(catalog: dict) -> None: + summary = '# XXRS\n\n' + summary += '* [栩栩若生](README.md)\n\n' + summary += '## 内容 \n\n' + for (title, mdFile) in catalog.items(): + summary += '* [%s](content/%s)\n' % (title, mdFile) + saveFile(os.path.join(workDir, 'SUMMARY.md'), summary) + + +initFolder() +# c = loadChapters(loadData('rc-4')['content']) +# loadSummary(c) +loadCover(loadData('rc-4')['metadata'])