-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtask.py
More file actions
250 lines (222 loc) · 11.8 KB
/
Copy pathtask.py
File metadata and controls
250 lines (222 loc) · 11.8 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
#!/usr/bin/env python3
# coding=utf-8
import os
import re
import subprocess
import json
import shutil
import requests
from pathlib import Path
from loguru import logger
from lake2md import lake_to_md, get_pic
from dotenv import dotenv_values
user_config = dotenv_values(".env")
class Config:
def __init__(self, prefix):
try:
pwd = Path(__file__).absolute()
file_path = Path(pwd).parent / 'config.json'
with open(file_path, 'r') as f:
config = json.load(f)
self.config = config
if prefix in config.keys():
self.basedir = config[prefix].get('basedir', user_config.get('BASEDIR', Path.home()))
self.desdir = config[prefix].get('desdir', user_config.get('DESDIR', Path.home()))
self.workdir = config[prefix].get('workdir', user_config.get('WORKDIR', Path.home()))
self.cmd = config[prefix]['cmd']
self.conf = config[prefix]['conf']
else:
logger.debug("配置不正确")
except OSError as e:
logger.exception(e)
def deploy(self):
if self.cmd != '':
os.chdir(self.workdir)
return subprocess.Popen(self.cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,encoding="utf-8")
else:
logger.debug("命令为空")
def run(cmd_list=["hugo"]):
ret = subprocess.run(cmd_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8")
return ret
def init_theme(gen, prefix, workdir, desdir):
if gen == 'hugo':
if Path(workdir).exists():
os.chdir(Path(workdir))
else:
workdir.mkdir(parents=True, exist_ok=True)
os.chdir(Path(workdir))
# subprocess.call("hugo new site .",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,encoding="utf-8")
ret_new = run(["hugo", "new", "site", '.'])
if ret_new.returncode == 0:
logger.info("为{}初始化网站成功", prefix)
else:
logger.info("为{}初始化网站失败{}", prefix, ret_new)
Path(desdir).mkdir(parents=True, exist_ok=True)
logger.info("下载主题")
theme_url = 'https://github.com/AmazingRise/hugo-theme-diary.git'
command = ["git", "clone", theme_url, Path(workdir, 'themes', 'diary')]
# subprocess.call(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8")
ret_clone = run(command)
if ret_clone.returncode == 0:
logger.info("为{}下载了diary主题", prefix)
else:
logger.info("为{}下载主题失败{}", prefix, ret_clone)
config_list = Path(workdir, 'themes', 'diary', 'exampleSite', 'config.toml').read_text().split('\n')
domain = user_config.get('DOMAIN', '')
config_list[0] = f'baseURL = "https://{prefix}.{domain}"'
logger.info("初始化网站地址为https://{}.{}.xyz", prefix, domain)
Path(workdir, 'config.toml').write_text('\n'.join(config_list), encoding='utf-8')
os.chdir(Path(workdir))
ret_deploy = run(["hugo"])
if ret_deploy.returncode == 0:
logger.info("为{}部署成功", prefix)
else:
logger.info("为{}部署失败{}", prefix, ret_deploy)
# subprocess.call(["hugo"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="utf-8")
else:
logger.info("没有初始化命令")
pass
def create_namespace(prefix, code):
# 创建配置文件
gen = user_config.get('GEN', '')
basedir = user_config.get('BASEDIR', Path.home())
workdir = user_config.get('WORKDIR', Path(basedir, prefix))
desdir = user_config.get('DESDIR', Path(basedir, prefix, 'content', 'posts'))
pwd = Path(__file__).absolute()
file_path = Path(pwd).parent / 'config.json'
config = Path(file_path).read_text(encoding='utf-8')
config_dict = json.loads(config)
conf = {
prefix: {
"code": code,
"basedir": str(basedir),
"desdir": str(desdir),
"workdir": str(workdir),
"cmd": gen,
"conf": {
"html": True,
"shortcode": True
}
}
}
config_dict.update(conf)
json.dump(config_dict, file_path.open('w+'), indent = 6)
logger.info("为{}初始化一个配置文件", prefix)
# 下载主题和部署
init_theme(gen, prefix, workdir, desdir)
def init_web(doc, prefix):
doc_list = doc.split('---')
config = Config(prefix)
# # 处理主题
var_list = list(filter(None, doc_list[0].split('\n')))[1:-1]
# logger.debug(var_list)
var_dict = {}
for line in var_list:
v = line.split('=')
var_dict.update({v[0]: v[1]})
theme_dir = Path(config.workdir, 'themes', var_dict['theme'])
if Path(theme_dir).exists():
logger.info("主题文件存在,不处理")
else:
shutil.rmtree(Path(config.workdir, 'themes'))
Path(config.workdir, 'themes').mkdir(parents=True, exist_ok=True)
logger.info("下载主题{}", var_dict['theme'])
command = ["git", "clone", var_dict['theme_url'], Path(config.workdir, 'themes', var_dict['theme'])]
#
ret_clone = run(command)
if ret_clone.returncode == 0:
logger.info("为{}下载{}主题成功", prefix, var_dict['theme'])
else:
logger.info("为{}下载主题失败{}", prefix, ret_clone)
# 处理配置文件
conf_list = list(filter(None, doc_list[1].split('\n')))
if conf_list[0] == '```yaml':
Path(config.workdir, 'config.yaml').write_text('\n'.join(conf_list[1:-1]), encoding='utf-8')
else:
Path(config.workdir, 'config.toml').write_text('\n'.join(conf_list[1:-1]), encoding='utf-8')
# 处理静态文件
logger.info("静态文件夹为{}", var_dict['staticdir'])
static_path = Path(config.workdir, var_dict['staticdir'])
static_list = list(filter(None, doc_list[2].split('\n')))
logger.debug(static_list)
if len(static_list) == 0:
pass
else:
for line in static_list:
cap, url = get_pic(line)
resp = requests.get(url)
Path(static_path, cap).write_bytes(resp.content)
config.deploy()
logger.info("部署网站配置完成!")
def delete_namespace(namespace):
pwd = Path(__file__).absolute()
file_path = Path(pwd).parent / 'config.json'
with open(file_path, 'r') as f:
config = json.load(f)
if namespace in config:
try:
shutil.rmtree(Path(config[namespace]['workdir']))
del config[namespace]
json.dump(config, Path(file_path).open('w+'), indent = 6)
logger.info("{}已经删除了", namespace)
except IOError as e:
logger.exception(e)
else:
pass
logger.info("{}不存在", namespace)
def publish_doc(slug, doc, title, prefix):
config = Config(prefix)
try:
md_doc, file_path = lake_to_md(doc, title)
if file_path == '':
logger.info("PATH为{}", file_path)
path = str(Path(config.desdir))
Path(config.desdir, title + '.md').write_text(md_doc, encoding='utf-8')
else:
path = str(Path(config.workdir, 'content', file_path))
Path(config.workdir, 'content', file_path).mkdir(parents=True, exist_ok=True)
Path(config.workdir, 'content', file_path, title + '.md').write_text(md_doc, encoding='utf-8')
logger.debug(path)
logger.info("写入了一篇新的文章:{}", title)
except IOError as e:
logger.exception(e)
if Path(config.workdir, prefix + '.json').exists():
conf = Path(config.workdir, prefix + '.json').read_text(encoding='utf-8')
conf_dict = json.loads(conf)
logger.debug("配置文件为:{}", conf_dict)
if slug not in conf_dict:
conf_dict.update({slug: {"title": title, "path": path }})
logger.debug("config为{}", conf_dict)
json.dump(conf_dict, Path(config.workdir, prefix + '.json').open('w+', encoding='utf-8'), indent = 6)
logger.info("知识库{}发布了一遍名为<<{}>>的文章并已部署!", prefix, title)
else:
pass
logger.info("知识库{}更新了一遍名为<<{}>>的文章并已部署!", prefix, title)
else:
conf_dict = {slug: {"title": title, "path": path }}
json.dump(conf_dict, Path(config.workdir, prefix + '.json').open('w+', encoding='utf-8'), indent = 6)
logger.info("配置文件为空,设置为新的文件")
config.deploy()
def delete_doc(slug, title, prefix):
config = Config(prefix)
try:
conf = Path(config.workdir, prefix + '.json').read_text(encoding='utf-8')
conf_dict = json.loads(conf)
logger.debug("配置文件为:{}", conf_dict)
except IOError as e:
logger.exception(e)
conf_dict = {}
logger.info("配置文件为空,设置为新的文件")
if slug in conf_dict:
file_path = Path(conf_dict[slug]['path'], conf_dict[slug]['title'] + '.md')
Path(file_path).unlink()
del conf_dict[slug]
json.dump(conf_dict, Path(config.workdir, prefix + '.json').open('w+'), indent = 6)
logger.info("知识库{}删除了一篇名为<<{}>>的文章!", prefix, title)
else:
logger.info("文档可能已经移动,无法获取位置")
config.deploy()
if __name__ == '__main__':
create_namespace(os.environ['NAMESPACE'], os.environ['CODE'])
# init_conf('cccc')
# init_web("```bash\ngen=hugo\ntheme=LoveIt\ntheme_url=https://github.com/dillonzq/LoveIt.git\nstaticdir=themes\n```\n\n---\n\n```toml\nbaseURL = \"http://example.org/\"\n# [en, zh-cn, fr, ...] 设置默认的语言\ndefaultContentLanguage = \"zh-cn\"\n# 网站语言, 仅在这里 CN 大写\nlanguageCode = \"zh-CN\"\n# 是否包括中日韩文字\nhasCJKLanguage = true\n# 网站标题\ntitle = \"我的全新 Hugo 网站\"\n\n# 更改使用 Hugo 构建网站时使用的默认主题\ntheme = \"LoveIt\"\n\n[params]\n# LoveIt 主题版本\nversion = \"0.2.X\"\n\n[menu]\n[[menu.main]]\nidentifier = \"posts\"\n# 你可以在名称 (允许 HTML 格式) 之前添加其他信息, 例如图标\npre = \"\"\n# 你可以在名称 (允许 HTML 格式) 之后添加其他信息, 例如图标\npost = \"\"\nname = \"文章\"\nurl = \"/posts/\"\n# 当你将鼠标悬停在此菜单链接上时, 将显示的标题\ntitle = \"\"\nweight = 1\n[[menu.main]]\nidentifier = \"tags\"\npre = \"\"\npost = \"\"\nname = \"标签\"\nurl = \"/tags/\"\ntitle = \"\"\nweight = 2\n[[menu.main]]\nidentifier = \"categories\"\npre = \"\"\npost = \"\"\nname = \"分类\"\nurl = \"/categories/\"\ntitle = \"\"\nweight = 3\n\n# Hugo 解析文档的配置\n[markup]\n# 语法高亮设置 (https://gohugo.io/content-management/syntax-highlighting)\n[markup.highlight]\n# false 是必要的设置 (https://github.com/dillonzq/LoveIt/issues/158)\nnoClasses = false\n\n```\n\n---\n\n\n\n\n","zjan-bwcmnq")