-
Notifications
You must be signed in to change notification settings - Fork 0
/
oikaze_jinja.py
303 lines (233 loc) · 8.87 KB
/
oikaze_jinja.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
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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import socketserver
import http.server
from jinja2.runtime import StrictUndefined
from markdown2 import markdown
from os import listdir, path, getcwd
from pathlib import Path
from shutil import rmtree, copytree
#import configparser # TODO: the whole config parser
from jinja2 import Environment, PackageLoader, select_autoescape, Template
import htmlmin # html minifier
import config_app
import config_site
app_options = config_app.app_options
site_options = config_site.site_options
class OikazeJinja(object):
def __init__(self):
self.app_options = app_options
self.site_options = site_options
self.allFiles = self.getListOfFiles()
self.env = self.loadJinjaEnv()
# exec
self.clearOutputFolder()
self.parseContentFolder(self.allFiles)
self.copyAssets()
def getListOfFiles(self, dirName = False):
if not dirName:
dirName = self.app_options['content_folder']
# create a list of file and sub directories
# names in the given directory
if not path.isdir(dirName):
print("ERROR: content folder doesn't exists:", dirName)
exit()
listOfFile = listdir(dirName)
allFiles = list()
# Iterate over all the entries
for entry in listOfFile:
# Create full path
fullPath = path.join(dirName, entry)
# If entry is a directory then get the list of files in this directory
if path.isdir(fullPath):
allFiles = allFiles + self.getListOfFiles(fullPath)
else:
allFiles.append(fullPath)
self.allFiles = allFiles
return allFiles
def splitAll(self,pa):
allparts = []
while 1:
parts = path.split(pa)
if parts[0] == pa: # sentinel for absolute paths
allparts.insert(0, parts[0])
break
elif parts[1] == pa: # sentinel for relative paths
allparts.insert(0, parts[1])
break
else:
pa = parts[0]
allparts.insert(0, parts[1])
return allparts
def outputF(self, filePath, data):
global app_options
global site_options
if(data['slug'] != "/" and data['slug'] != "index" and data['slug'] != "home"):
slug = data['slug']
else:
slug = ""
if type(filePath) == str:
filePath = path.join(filePath)
filePath = self.splitAll(filePath)
#replace first folder (content/ by default) for output folder (output/ by default)
filePath[0] = app_options['output_folder']
# Add lang slug if needed
if "lang_slugs" in site_options:
if data['lang'] in site_options['lang_slugs']:
filePath.insert(1, site_options['lang_slugs'][data['lang']])
else:
print("site_options[lang_slug] is missing lang: " + data['lang'])
return False
else:
print("site_options is missing [lang_slug] key")
return False
# pop last item which is the original file name.
filePath.pop(-1)
#combine filePath + slug if slug not empty
if slug:
outputFile = path.join(*filePath, slug)
else:
outputFile = path.join(*filePath)
return outputFile
def parseFileMD(self,fileName):
with open(fileName, 'r', encoding="utf-8") as file:
parsed_md = markdown(file.read(), extras=['metadata'])
data = parsed_md.metadata
data['body'] = parsed_md
return data
def parseFileJSON(self,fileName):
import json
with open(fileName, 'r', encoding="utf-8") as file:
parsed_json = json.load(file)
return parsed_json
def parseContentFolder(self,allFiles):
global app_options
counter = 0
for fileName in allFiles:
fileName = path.join(fileName)
counter += 1
if fileName.endswith(".md"):
data = self.parseFileMD(fileName)
elif fileName.endswith(".json"):
data = self.parseFileJSON(fileName)
html = self.buildContent(data)
if html:
html = self.minifyHTML(html)
outputFile = self.outputF(fileName, data)
if outputFile:
if self.generateOutput(html, outputFile):
print(str(counter) + " " + fileName +
" processed to -> " + outputFile + "/index.html")
else:
print(str(counter) + " " + "ERROR generating" +
outputFile + "/index.html")
else:
print("Error getting output folder for %s", fileName)
# Generate listing pages
def loadJinjaEnv(self):
env = Environment(
loader=PackageLoader('oikaze_jinja', self.app_options['template_folder']),
#autoescape=select_autoescape([
# 'html',
# 'xml'
#]),
#undefined=StrictUndefined,
auto_reload=True,
cache_size=0 #disable cache so it rebuilts when watching for changes
)
env.trim_blocks = True
env.lstrip_blocks = True
env.strip_trailing_newlines = True
# TODO: Test in depth if this parser of jinja2 extra config works
if "jinja2_env" in app_options:
for k, v in self.app_options['jinja2_env']:
env[k] = v
return env
def buildContent(self, data):
"""
buildContent(data)
Will use the template in data.template (or default in app_options) to render with Jinja.
"""
if "template" in data:
template = data['template']
else:
# TODO: add app setting to change name of default template name?
template = self.app_options["template_default"]
try:
render = self.env.get_template(template)
except:
print("Error, can't find the template: templates/" + template)
return False
try:
r = render.render(content=data, globals=self.site_options)
except:
print("Error rendering")
print(render)
import sys
print(sys.exc_info())
return False
r = self.minifyHTML(r)
return r
def minifyHTML(self,html):
"""
minifyHTML(html):
parses the HTML to minifiy and strip empty spaces
"""
#minify HTML
html = htmlmin.minify(html,
remove_empty_space=True
, remove_all_empty_space=True
, remove_comments=True)
return html
def clearOutputFolder(self):
if self.app_options['clean_output']:
output_folder = self.app_options['output_folder']
if self.app_options['output_folder'][1] != "/":
output_folder = "/" + output_folder
try:
rmtree(path.join(getcwd(), self.app_options['output_folder']))
print("Output folder cleaned")
return True
except:
# TODO: false positive error?
print("Error cleaning up output folder:" +
getcwd() + self.app_options['output_folder'])
return False
def copyAssets(self,customFolder = False):
if customFolder:
orig = customFolder
else:
orig = self.app_options['assets_folder']
end = self.app_options['output_folder'] + "/" + orig.split("/")[-1]
try:
copytree(orig, end)
except:
print("Error copying the assets/static folder: " + orig + " -> " + end)
print("Assets cloned")
def generateOutput(self, html, file):
if str(file).startswith("/"):
file = file[1:]
#create folder(s) if doesn't exists
try:
Path(file).mkdir(parents=True, exist_ok=True)
except:
print("Wrong SLUG?" + file)
return False
with open(path.join(file + "/index.html"), 'w') as output:
output.write(html)
return True
###############
# RUN #
###############
if __name__ == "__main__":
import sys
args = [x.replace("--","") for x in sys.argv[1:] ]
print(args)
OikazeJinja()
if "http" in args:
PORT = 8000
DIRECTORY = "output"
class Handler(http.server.SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, directory=DIRECTORY, **kwargs)
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("serving at port", PORT)
httpd.serve_forever()