This repository has been archived by the owner on Jan 25, 2019. It is now read-only.
/
engine.py
executable file
·460 lines (388 loc) · 17 KB
/
engine.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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
#!/usr/bin/python2
import os
import sys
import shutil
from datetime import datetime
from optparse import OptionParser, OptionGroup
import logging
import yaml
import wok
from wok.page import Page, Author
from wok import renderers
from wok import util
from wok.dev_server import dev_server
import locale
class Engine(object):
"""
The main engine of wok. Upon initialization, it generates a site from the
source files.
"""
default_options = {
'content_dir': 'content',
'template_dir': 'templates',
'output_dir': 'output',
'media_dir': 'media',
'site_title': 'Some random Wok site',
'url_pattern': '/{category}/{slug}{page}.{ext}',
'url_include_index': True,
'slug_from_filename': False,
'relative_urls': False,
'locale': None,
'markdown_extra_plugins': [],
}
SITE_ROOT = os.getcwd()
def __init__(self, output_lvl=1):
"""
Set up CLI options, logging levels, and start everything off.
Afterwards, run a dev server if asked to.
"""
# CLI options
# -----------
parser = OptionParser(version='%prog v{0}'.format(wok.version))
# Add option to initialize an new project
init_grp = OptionGroup(parser, "Initialize project",
"Creates a config file and the required directories. ")
init_grp.add_option('--init', action='store_true',
dest='initproject',
help="create a confg file before generating the site")
init_grp.add_option('--site_title',
dest='site_title',
help="configures the site title to the given value")
parser.add_option_group(init_grp)
# Add option to to run the development server after generating pages
devserver_grp = OptionGroup(parser, "Development server",
"Runs a small development server after site generation. "
"--address and --port will be ignored if --server is absent.")
devserver_grp.add_option('--server', action='store_true',
dest='runserver',
help="run a development server after generating the site")
devserver_grp.add_option('--address', action='store', dest='address',
help="specify ADDRESS on which to run development server")
devserver_grp.add_option('--port', action='store', dest='port',
type='int',
help="specify PORT on which to run development server")
parser.add_option_group(devserver_grp)
# Options for noisiness level and logging
logging_grp = OptionGroup(parser, "Logging",
"By default, log messages will be sent to standard out, "
"and report only errors and warnings.")
parser.set_defaults(loglevel=logging.WARNING)
logging_grp.add_option('-q', '--quiet', action='store_const',
const=logging.ERROR, dest='loglevel',
help="be completely quiet, log nothing")
logging_grp.add_option('--warnings', action='store_const',
const=logging.WARNING, dest='loglevel',
help="log warnings in addition to errors")
logging_grp.add_option('-v', '--verbose', action='store_const',
const=logging.INFO, dest='loglevel',
help="log ALL the things!")
logging_grp.add_option('--debug', action='store_const',
const=logging.DEBUG, dest='loglevel',
help="log debugging info in addition to warnings and errors")
logging_grp.add_option('--log', '-l', dest='logfile',
help="log to the specified LOGFILE instead of standard out")
parser.add_option_group(logging_grp)
cli_options, args = parser.parse_args()
# Set up logging
# --------------
logging_options = {
'format': '%(levelname)s: %(message)s',
'level': cli_options.loglevel,
}
if cli_options.logfile:
logging_options['filename'] = cli_options.logfile
else:
logging_options['stream'] = sys.stdout
logging.basicConfig(**logging_options)
# Init project
# ------------
if cli_options.initproject:
''' Create the config file and the required directories if the user said to.
'''
orig_dir = os.getcwd()
os.chdir(self.SITE_ROOT)
# create config
options = Engine.default_options.copy()
# read old config if present
if os.path.isfile('config'):
with open('config') as f:
yaml_config = yaml.load(f)
if yaml_config:
options.update(yaml_config)
if cli_options.site_title:
options['site_title'] = cli_options.site_title
# save new config
with open('config', 'w') as f:
yaml.dump(options, f)
# create required dirs
required_dirs = [options['content_dir'], options['template_dir']]
for required_dir in required_dirs:
if not os.path.isdir(required_dir):
os.mkdir(required_dir)
os.chdir(orig_dir)
# Action!
# -------
self.generate_site()
# Dev server
# ----------
if cli_options.runserver:
''' Run the dev server if the user said to, and watch the specified
directories for changes. The server will regenerate the entire wok
site if changes are found after every request.
'''
output_dir = os.path.join(self.options['server_root'])
host = '' if cli_options.address is None else cli_options.address
port = 8000 if cli_options.port is None else cli_options.port
server = dev_server(serv_dir=output_dir, host=host, port=port,
dir_mon=True,
watch_dirs=[
self.options['media_dir'],
self.options['template_dir'],
self.options['content_dir']
],
change_handler=self.generate_site)
server.run()
def generate_site(self):
''' Generate the wok site '''
orig_dir = os.getcwd()
os.chdir(self.SITE_ROOT)
self.all_pages = []
self.read_options()
self.sanity_check()
self.load_hooks()
self.load_renderers()
self.renderer_options()
self.run_hook('site.start')
self.prepare_output()
self.load_pages()
self.make_tree()
self.render_site()
self.run_hook('site.done')
os.chdir(orig_dir)
def read_options(self):
"""Load options from the config file."""
self.options = Engine.default_options.copy()
if os.path.isfile('config'):
with open('config') as f:
yaml_config = yaml.load(f)
if yaml_config:
self.options.update(yaml_config)
# Make authors a list, even only a single author was specified.
authors = self.options.get('authors', self.options.get('author', None))
if isinstance(authors, list):
self.options['authors'] = [Author.parse(a) for a in authors]
elif isinstance(authors, str):
csv = authors.split(',')
self.options['authors'] = [Author.parse(a) for a in csv]
if len(self.options['authors']) > 1:
logging.warn('Deprecation Warning: Use YAML lists instead of '
'CSV for multiple authors. i.e. ["John Doe", "Jane '
'Smith"] instead of "John Doe, Jane Smith". In config '
'file.')
if '{type}' in self.options['url_pattern']:
logging.warn('Deprecation Warning: You should use {ext} instead '
'of {type} in the url pattern specified in the config '
'file.')
# Set locale if needed
wanted_locale = self.options.get('locale')
if wanted_locale is not None:
try:
locale.setlocale(locale.LC_TIME, wanted_locale)
except locale.Error as err:
logging.warn('Unable to set locale to `%s`: %s',
wanted_locale, err
)
# add a subdir prefix to the output_dir, if present in the config
self.options['server_root'] = self.options['output_dir']
self.options['output_dir'] = os.path.join(self.options['output_dir'], self.options.get('url_subdir', ''))
def renderer_options(self):
"""Monkeypatches renderer options as in `config` file."""
# Markdown extra plugins
markdown_extra_plugins = \
self.options.get('markdown_extra_plugins', [])
if hasattr(renderers, 'Markdown'):
renderers.Markdown.plugins.extend(markdown_extra_plugins)
if hasattr(renderers, 'Markdown2'):
renderers.Markdown2.extras.extend(markdown_extra_plugins)
def sanity_check(self):
"""Basic sanity checks."""
# Make sure that this is (probabably) a wok source directory.
if not (os.path.isdir('templates') or os.path.isdir('content')):
logging.critical("This doesn't look like a wok site. Aborting.")
sys.exit(1)
def load_hooks(self):
try:
sys.path.append('hooks')
import __hooks__
self.hooks = __hooks__.hooks
logging.info('Loaded {0} hooks: {0}'.format(self.hooks))
except ImportError as e:
if "__hooks__" in str(e):
logging.info('No hooks module found.')
else:
# don't catch import errors raised within a hook
logging.info('Import error within hooks.')
raise
def load_renderers(self):
self.renderers = {}
for renderer in renderers.all:
self.renderers.update((ext, renderer) for ext in renderer.extensions)
try:
sys.path.append('renderers')
import __renderers__
self.renderers.update(__renderers__.renderers)
logging.info('Loaded {0} renderers'.format(len(__renderers__.renderers)))
except ImportError as e:
if "__renderers__" in str(e):
logging.info('No renderers module found.')
else:
# don't catch import errors raised within a renderer
logging.info('Import error within renderers.')
raise
def run_hook(self, hook_name, *args):
""" Run specified hooks if they exist """
logging.debug('Running hook {0}'.format(hook_name))
returns = []
try:
for hook in self.hooks.get(hook_name, []):
returns.append(hook(self.options, *args))
except AttributeError:
logging.info('Hook {0} not defined'.format(hook_name))
return returns
def prepare_output(self):
"""
Prepare the output directory. Remove any contents there already, and
then copy over the media files, if they exist.
"""
if os.path.isdir(self.options['output_dir']):
for name in os.listdir(self.options['output_dir']):
# Don't remove dotfiles
if name[0] == ".":
continue
path = os.path.join(self.options['output_dir'], name)
if os.path.isfile(path):
os.unlink(path)
else:
shutil.rmtree(path)
else:
os.makedirs(self.options['output_dir'])
self.run_hook('site.output.pre', self.options['output_dir'])
# Copy the media directory to the output folder
if os.path.isdir(self.options['media_dir']):
try:
for name in os.listdir(self.options['media_dir']):
path = os.path.join(self.options['media_dir'], name)
if os.path.isdir(path):
shutil.copytree(
path,
os.path.join(self.options['output_dir'], name),
symlinks=True
)
else:
shutil.copy(path, self.options['output_dir'])
# Do nothing if the media directory doesn't exist
except OSError:
logging.warning('There was a problem copying the media files '
'to the output directory.')
self.run_hook('site.output.post', self.options['output_dir'])
def load_pages(self):
"""Load all the content files."""
# Load pages from hooks (pre)
for pages in self.run_hook('site.content.gather.pre'):
if pages:
self.all_pages.extend(pages)
# Load files
for root, dirs, files in os.walk(self.options['content_dir']):
# Grab all the parsable files
for f in files:
# Don't parse hidden files.
if f.startswith('.'):
continue
ext = f.split('.')[-1]
renderer = self.renderers.get(ext)
if renderer is None:
logging.warning('No parser found '
'for {0}. Using default renderer.'.format(f))
renderer = renderers.Renderer
p = Page.from_file(os.path.join(root, f), self.options, self, renderer)
if p and p.meta['published']:
self.all_pages.append(p)
# Load pages from hooks (post)
for pages in self.run_hook('site.content.gather.post', self.all_pages):
if pages:
self.all_pages.extend(pages)
def make_tree(self):
"""
Make the category pseudo-tree.
In this structure, each node is a page. Pages with sub pages are
interior nodes, and leaf nodes have no sub pages. It is not truly a
tree, because the root node doesn't exist.
"""
self.categories = {}
site_tree = []
# We want to parse these in a approximately breadth first order
self.all_pages.sort(key=lambda p: len(p.meta['category']))
# For every page
for p in self.all_pages:
# If it has a category (ie: is not at top level)
if len(p.meta['category']) > 0:
top_cat = p.meta['category'][0]
if not top_cat in self.categories:
self.categories[top_cat] = []
self.categories[top_cat].append(p.meta)
try:
# Put this page's meta in the right place in site_tree.
siblings = site_tree
for cat in p.meta['category']:
# This line will fail if the page is an orphan
parent = [subpage for subpage in siblings
if subpage['slug'] == cat][0]
siblings = parent['subpages']
siblings.append(p.meta)
except IndexError:
logging.error('It looks like the page "{0}" is an orphan! '
'This will probably cause problems.'.format(p.path))
def render_site(self):
"""Render every page and write the output files."""
# Gather tags
tag_set = set()
for p in self.all_pages:
tag_set = tag_set.union(p.meta['tags'])
tag_dict = dict()
for tag in tag_set:
# Add all pages with the current tag to the tag dict
tag_dict[tag] = [p.meta for p in self.all_pages
if tag in p.meta['tags']]
# Gather slugs
slug_dict = dict((p.meta['slug'], p.meta) for p in self.all_pages)
for p in self.all_pages:
# Construct this every time, to avoid sharing one instance
# between page objects.
templ_vars = {
'site': {
'title': self.options.get('site_title', 'Untitled'),
'datetime': datetime.now(),
'date': datetime.now().date(),
'time': datetime.now().time(),
'tags': tag_dict,
'pages': self.all_pages[:],
'categories': self.categories,
'slugs': slug_dict,
},
}
for k, v in self.options.iteritems():
if k not in ('site_title', 'output_dir', 'content_dir',
'templates_dir', 'media_dir', 'url_pattern'):
templ_vars['site'][k] = v
if 'author' in self.options:
templ_vars['site']['author'] = self.options['author']
# Rendering the page might give us back more pages to render.
new_pages = p.render(templ_vars)
if p.meta['make_file']:
p.write()
if new_pages:
logging.debug('found new_pages')
self.all_pages += new_pages
if __name__ == '__main__':
Engine()
exit(0)