-
Notifications
You must be signed in to change notification settings - Fork 0
/
wmk.py
executable file
·2031 lines (1896 loc) · 81.3 KB
/
wmk.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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import os
import sys
import datetime
import re
import ast
import json
import subprocess
import hashlib
import shutil
import locale
import gettext
import sass
import yaml
import frontmatter
import markdown
import pypandoc
import lunr
from mako.lookup import TemplateLookup
from mako.exceptions import text_error_template, TemplateLookupException
from wmk_utils import (
slugify, attrdict, MDContentList, RenderCache, Nav, Toc, hookable)
import wmk_mako_filters as wmf
# To be imported from wmk_autoload and/or wmk_theme_autoload, if applicable
autoload = {}
VERSION = '1.18'
# Template variables with these names will be converted to date or datetime
# objects (depending on length) - if they conform to ISO 8601.
KNOWN_DATE_KEYS = (
'date', 'pubdate', 'modified_date', 'expire_date', 'created_date')
# Note that only markdown/html extensions will be active unless explicitly
# set in wmk_config (or pandoc is globally true).
DEFAULT_CONTENT_EXTENSIONS = {
'.md': {}, # just markdown...
'.mdwn': {},
'.mdown': {},
'.markdown': {},
'.mmd': {'pandoc_input_format': 'markdown_mmd'},
'.gfm': {'pandoc_input_format': 'gfm'},
'.html': {'raw': True},
'.htm': {'raw': True},
# pandoc-only formats below
'.org': {'pandoc': True, 'pandoc_input_format': 'org'},
'.rst': {'pandoc': True, 'pandoc_input_format': 'rst'},
'.dj': {'pandoc': True, 'pandoc_input_format': 'djot'},
'.textile': {'pandoc': True, 'pandoc_input_format': 'textile'},
'.tex': {'pandoc': True, 'pandoc_input_format': 'latex'},
'.typ': {'pandoc': True, 'pandoc_input_format': 'typst'},
'.man': {'pandoc': True, 'pandoc_input_format': 'man'},
'.rtf': {'pandoc': True, 'pandoc_input_format': 'rtf'},
'.xml': {'pandoc': True, 'pandoc_input_format': 'jats'},
'.jats': {'pandoc': True, 'pandoc_input_format': 'jats'},
'.tei': {'pandoc': True, 'pandoc_input_format': 'tei'},
'.docbook': {'pandoc': True, 'pandoc_input_format': 'docbook'},
# binary formats supported via pandoc (converted to markdown as an intermediary step)
'.docx': {'is_binary': True, 'pandoc': True, 'pandoc_binary_format': 'docx',
'pandoc_input_format': 'markdown'},
'.odt': {'is_binary': True, 'pandoc': True, 'pandoc_binary_format': 'odt',
'pandoc_input_format': 'markdown'},
'.epub': {'is_binary': True, 'pandoc': True, 'pandoc_binary_format': 'epub',
'pandoc_input_format': 'markdown'},
}
def main(basedir=None, quick=False):
"""
Builds/copies everything into the output dir (normally htdocs).
"""
# `force` mode is now the default and is turned off by setting --quick
force = not quick
if basedir is None:
basedir = os.path.dirname(os.path.realpath(__file__)) or '.'
basedir = os.path.realpath(basedir)
if not os.path.isdir(basedir):
raise Exception('{} is not a directory'.format(basedir))
conf_file = re.sub(
r'.*/', '', os.environ.get('WMK_CONFIG', '')) or 'wmk_config.yaml'
if not os.path.exists(os.path.join(basedir, conf_file)):
print('ERROR: {} does not contain a {}'.format(
basedir, conf_file))
sys.exit(1)
conf = get_config(basedir, conf_file)
dirs = get_dirs(basedir, conf)
ensure_dirs(dirs)
if not dirs['python'] in sys.path:
sys.path.insert(0, dirs['python'])
global autoload
try:
from wmk_autoload import autoload
except:
pass
# 1) get theme settings, copy static files
# css_dir_from_start is workaround for process_assets timestamp check
css_dir_from_start = os.path.exists(os.path.join(dirs['output'], 'css'))
# a) preparation, loading plugins, setting sys.path etc
themedir = os.path.join(
dirs['themes'], conf.get('theme')) if conf.get('theme') else None
if themedir and not os.path.exists(themedir):
themedir = None
if themedir and not conf.get('ignore_theme_config', False):
# Partial merge of theme config with main config file.
# NOTE that WMK_CONFIG does not affect theme settings.
theme_conf = get_config(themedir, 'wmk_config.yaml')
conf_merge(conf, theme_conf)
if themedir and os.path.exists(os.path.join(themedir, 'py')):
theme_py = os.path.join(themedir, 'py')
if not theme_py in sys.path:
sys.path.insert(1, os.path.join(themedir, 'py'))
try:
from wmk_theme_autoload import autoload as theme_autoload
for k in theme_autoload:
if k in autoload:
continue
autoload[k] = theme_autoload[k]
except:
pass
# b) Run init commands, if any
run_init_commands(basedir, conf)
# (NOTE: hookable works at this point, since sys.path is ready).
# c) Doing the actual copying.
copy_static_files(dirs, themedir, conf, quick)
# 2) compile assets (only scss for now):
theme_assets = os.path.join(themedir, 'assets') if themedir else None
process_assets(
dirs['assets'], theme_assets, dirs['output'],
conf, css_dir_from_start, force)
assets_map = fingerprint_assets(conf, dirs['output'], dirs['data'])
# 3) Preparation for remaining phases
# a) Global data for template rendering, used by both process_templates
# and process_markdown_content.
template_vars = get_template_vars(dirs, themedir, conf, assets_map)
lookup = get_template_lookup(dirs, themedir, conf, template_vars)
conf['_lookup'] = lookup
# 4) write redirect files
if not quick:
handle_redirects(
conf.get('redirects'), template_vars['DATADIR'], template_vars['WEBROOT'])
# 5a) templates
templates = get_templates(
dirs['templates'], themedir, dirs['output'], template_vars)
# 5b) inherited yaml metadata
index_yaml = get_index_yaml_data(dirs['content'], dirs['data'])
conf['_index_yaml_data'] = index_yaml or {}
# 5c) markdown (etc.) content
content = get_content(
dirs['content'], dirs['data'], dirs['output'],
template_vars, conf, force=force)
# 6) render templates
process_templates(templates, lookup, template_vars, force)
# 7) render Markdown/HTML/other content
process_markdown_content(content, lookup, conf, force)
# 8) Cleanup/external post-processing stage
if not quick:
post_build_actions(conf, dirs, templates, content)
run_cleanup_commands(conf, basedir)
def get_content_info(basedir='.', content_only=True):
"""
Gets the content (i.e. MDContent) data like it is at the stage where
`process_markdown_content()` is called during normal processing. Intended
for development and debugging, i.e. usage in an interactive shell, but may
also be used by an external script. If `content_only` is False, returns
a tuple of (content, conf, templates).
"""
force = True
basedir = os.path.realpath(basedir)
if not os.path.isdir(basedir):
raise Exception('{} is not a directory'.format(basedir))
conf_file = re.sub(
r'.*/', '', os.environ.get('WMK_CONFIG', '')) or 'wmk_config.yaml'
if not os.path.exists(os.path.join(basedir, conf_file)):
print('ERROR: {} does not contain a {}'.format(
basedir, conf_file))
sys.exit(1)
conf = get_config(basedir, conf_file)
dirs = get_dirs(basedir, conf)
ensure_dirs(dirs)
if not dirs['python'] in sys.path:
sys.path.insert(0, dirs['python'])
global autoload
try:
from wmk_autoload import autoload
except:
pass
themedir = os.path.join(
dirs['themes'], conf.get('theme')) if conf.get('theme') else None
if themedir and not os.path.exists(themedir):
themedir = None
if themedir and not conf.get('ignore_theme_config', False):
theme_conf = get_config(themedir, 'wmk_config.yaml')
conf_merge(conf, theme_conf)
if themedir and os.path.exists(os.path.join(themedir, 'py')):
theme_py = os.path.join(themedir, 'py')
if not theme_py in sys.path:
sys.path.insert(1, os.path.join(themedir, 'py'))
try:
from wmk_theme_autoload import autoload as theme_autoload
for k in theme_autoload:
if k in autoload:
continue
autoload[k] = theme_autoload[k]
except:
pass
assets_map = fingerprint_assets(conf, dirs['output'], dirs['data'])
template_vars = get_template_vars(dirs, themedir, conf, assets_map)
lookup = get_template_lookup(dirs, themedir, conf, template_vars)
conf['_lookup'] = lookup
templates = get_templates(
dirs['templates'], themedir, dirs['output'], template_vars)
index_yaml = get_index_yaml_data(dirs['content'], dirs['data'])
conf['_index_yaml_data'] = index_yaml or {}
content = get_content(
dirs['content'], dirs['data'], dirs['output'],
template_vars, conf, force=force)
if content_only:
return content
else:
return (content, conf, templates)
@hookable
def get_template_vars(dirs, themedir, conf, assets_map=None):
template_vars = {
'DATADIR': os.path.realpath(dirs['data']),
'CONTENTDIR': os.path.realpath(dirs['content']),
'WEBROOT': os.path.realpath(dirs['output']),
'TEMPLATES': [],
'MDCONTENT': MDContentList([]),
'CACHE': {}, # in-memory hash for caching in templates
}
template_vars.update(conf.get('template_context', {}))
template_vars['site'] = attrdict(conf.get('site', {}))
template_vars['nav'] = get_nav(conf, dirs, themedir)
# b) Locale/translation related
# site.locale affects collation; site.lang affects translations
locale_and_translation(template_vars, themedir)
# c) Assets fingerprinting
# If assets_fingerprinting is off fallback to the 'assets_map' setting
template_vars['ASSETS_MAP'] = get_assets_map(
conf, template_vars['DATADIR']) if assets_map is None else assets_map
# Used as a filter in Mako templates
template_vars['fingerprint'] = wmf.fingerprint_gen(
template_vars['WEBROOT'], template_vars['ASSETS_MAP'])
# d) Settings-dependent Mako filters
# Used as a filter in Mako templates
template_vars['url'] = wmf.url_filter_gen(
template_vars['site'].leading_path or template_vars['site'].base_url or '/')
template_vars['site'].build_time = datetime.datetime.now()
template_vars['site'].lunr_search = conf.get('lunr_index', False)
return template_vars
@hookable
def get_nav(conf, dirs=None, themedir=None):
conf_nav = conf.get('nav', [])
if isinstance(conf_nav, str) and conf_nav == 'auto':
return Nav([]) # will be generated from content later
else:
return Nav(conf_nav)
@hookable
def auto_nav_from_content(content):
"""
Automatically generate a simple nav from frontmatter. Called if `conf.nav` is
set to 'auto'.
Each added page MUST have `nav_section` and MAY have `nav_title` (which
fallbacks to `title`) and `nav_order` (which fallbacks to `weight` or
defaults to 2**32-1 if that fails). They MAY also have `nav_parent`/`parent`
(for which see below). The attribute `nav_exclude` will prevent a page from
appearing in the nav, even if it has a `nav_section`.
Sections are ordered by the smallest weight assigned to them, with the Root
section always being placed at the start. Non-Root sections with the same
weight are ordered alphabetically. Page links within each seaction are
ordered by `nav_order`/`weight`, or, if that is equal, by
`nav_title`/`title`.
If any of the pages in the nav have the attribute `nav_parent` (or `parent`),
and the value of that is the `nav_title`/`title` (case-insensitive), `id`, or
`slug` of another page in the same `nav_section`, then they will be treated
as children of those pages. Normally, using the title of the parent is
sufficient to identify it. However, if there is more than one page with the
same `nav_title`, then it may be necessary to disambiguate by using the
`slug` or even (in exceptional cases) the `id` of the parent page instead.
Note that if the `parent` attribute does not match any of the other pages in
the same section, then it will be ignored.
"""
autonav = []
fallback_weight = 2**32 - 1
sortkey = lambda x: (x['order'], x['title'])
sections = {'root': {'has_nesting': False, 'weight': 0, 'items': []}}
for it in content:
pg = it['data']['page']
if not pg.nav_section or pg.nav_exclude:
continue
# NOTE: Only Root section is case-insensitive
seckey = 'root' if pg.nav_section.lower() == 'root' else pg.nav_section
item_weight = pg.nav_order or pg.weight or fallback_weight
parent = pg.nav_parent if 'nav_parent' in pg else (pg.parent or None)
rec = {
'title': pg.nav_title or pg.title,
'url': it['url'],
'order': item_weight,
'slug': pg.slug,
'id': pg['id'],
'children': [],
'parent': parent,
'subitem': False,
}
if seckey not in sections:
sections[seckey] = {
'has_nesting': True if rec['parent'] else False,
'weight': item_weight,
'items': [rec],
}
else:
sections[seckey]['items'].append(rec)
if sections[seckey]['weight'] > item_weight:
sections[seckey]['weight'] = item_weight
if rec['parent']:
sections[seckey]['has_nesting'] = True
# Handle nesting
for seckey in sections:
if not sections[seckey]['has_nesting']:
continue
items = sections[seckey]['items']
# pass 1: assign children
for it in items:
par = it['parent']
if par:
parlow = par.lower()
for it2 in items:
if it2['id'] == par or it2['slug'] == par or it2['title'].lower() == parlow:
# TODO: detect duplicate titles and pick the one nearest
# (by weight or wrt directory structure), thus reducing
# the need for using slug/id. Maybe support 'nav_id' attr?
it2['children'].append(it)
it['subitem'] = True
break
# pass 2: sort children by weight
for it in items:
if it['children']:
it['children'].sort(key=sortkey)
# pass 3: remove subitems (items that are children) from top level
for i in reversed(range(len(items))):
if items[i]['subitem']:
items.pop(i)
root_section = sections.pop('root')
root_section['items'].sort(key=sortkey)
for it in root_section['items']:
autonav.append(it)
for section in sorted(list(sections.keys()), key=lambda x: (sections[x]['weight'], x)):
items = sections[section]['items']
items.sort(key=sortkey)
autonav.append({section: items})
return Nav(autonav)
@hookable
def get_template_lookup(dirs, themedir, conf, template_vars=None):
lookup_dirs = [dirs['templates']]
if themedir and os.path.exists(os.path.join(themedir, 'templates')):
lookup_dirs.append(os.path.join(themedir, 'templates'))
if conf.get('extra_template_dirs', None):
lookup_dirs += conf['extra_template_dirs']
# Add wmk_home templates for "built-in" shortcodes
wmk_home = os.path.dirname(os.path.realpath(__file__))
lookup_dirs.append(os.path.join(wmk_home, 'templates'))
mako_imports = ['from wmk_mako_filters import ' + ', '.join(wmf.__all__)]
if conf.get('mako_imports', None):
mako_imports += conf.get('mako_imports')
is_jinja = conf.get('jinja2_templates') or False
if is_jinja:
from jinja2 import (
Environment, FileSystemLoader, select_autoescape, pass_context)
import wmk_jinja2_extras as wje
# TODO: Handle potential Jinja2 settings in conf
loader = FileSystemLoader(
searchpath=lookup_dirs, encoding='utf-8', followlinks=True)
env = Environment(
loader=loader,
autoescape=select_autoescape())
env.globals = wje.get_globals()
env.globals['mako_lookup'] = TemplateLookup(
directories=lookup_dirs, imports=mako_imports)
@pass_context
def get_context(c):
_c = c.get_all()
reserved = ('context', 'UNDEFINED', 'loop')
ret = {}
for k in _c:
if k in reserved:
continue
ret[k] = _c[k]
return ret
env.globals['get_context'] = get_context
env.filters.update(wje.get_filters())
if template_vars and 'fingerprint' in template_vars:
env.filters.update({
'fingerprint': template_vars['fingerprint'],
'url': template_vars.get('url')})
# TODO: Add potential user-defined custom filters
return env
else:
return TemplateLookup(
directories=lookup_dirs, imports=mako_imports)
@hookable
def locale_and_translation(template_vars, themedir):
if template_vars['site'].locale:
print("NOTE: Setting collation locale to", template_vars['site'].locale)
locale.setlocale(locale.LC_COLLATE, template_vars['site'].locale)
# A directory which contains $LANG/LC_MESSAGES/wmk.mo
localedir = os.path.join(template_vars['DATADIR'], 'locales')
if themedir and not os.path.exists(localedir):
theme_locales = os.path.join(themedir, 'data', 'locales')
if os.path.exists(theme_locales):
localedir = theme_locales
if not os.path.exists(localedir):
localedir = None
if localedir and template_vars['site'].lang:
langs = template_vars['site'].lang
if isinstance(langs, str):
langs = [langs]
try:
lang = gettext.translation('wmk', localedir=localedir, languages=langs)
# Make traditional 'translate message' _ shortcut available globally,
# including in templates:
lang.install()
except FileNotFoundError:
# Rather than fall back to system locale, don't use translations at all
# in this case. But we still need the _ shortcut...
print("WARNING: Translations for locale (site.lang) '{}' not found".format(
template_vars['site'].lang))
gettext.install('wmk')
else:
# No localization available; nevertheless install the _ shortcut into
# the global environment for compatibility with templates that use it.
gettext.install('wmk')
def preview_single(basedir, preview_file,
preview_content=None, with_metadata=False, render_draft=True):
"""
Returns the bare HTML (i.e. not including HTML from Mako templates other
than shortcodes) for a single named file inside the content directory.
This is more complicated than it sounds since all settings must be
respected and all processing except for the actual output must be
done. If `preview_content` is provided, then the file named does not
actually need to exist (although a filename does need to be provided).
Note that the POSTPROCESS will not be performed. This includes shortcodes
relying on that, such as `linkto` and `pagelist`; only placeholders for them
will be visible in the output. The `resize_image` will actually output
resized images to the htdocs directory, unless they already are present.
"""
# `force` mode is now the default and is turned off by setting --quick
force = True
basedir = os.path.realpath(basedir)
if not os.path.isdir(basedir):
raise Exception('{} is not a directory'.format(basedir))
conf_file = re.sub(
r'.*/', '', os.environ.get('WMK_CONFIG', '')) or 'wmk_config.yaml'
if not os.path.exists(os.path.join(basedir, conf_file)):
print('ERROR: {} does not contain a {}'.format(
basedir, conf_file))
sys.exit(1)
conf = get_config(basedir, conf_file)
if render_draft:
conf['render_drafts'] = True
dirs = get_dirs(basedir, conf)
if not dirs['python'] in sys.path:
sys.path.insert(0, dirs['python'])
global autoload
try:
from wmk_autoload import autoload
except:
pass
# The content may use shortcodes, so we do need this
themedir = os.path.join(
dirs['themes'], conf.get('theme')) if conf.get('theme') else None
if themedir and not os.path.exists(themedir):
themedir = None
if themedir and not conf.get('ignore_theme_config', False):
# Partial merge of theme config with main config file.
# NOTE that WMK_CONFIG does not affect theme settings.
theme_conf = get_config(themedir, 'wmk_config.yaml')
conf_merge(conf, theme_conf)
if themedir and os.path.exists(os.path.join(themedir, 'py')):
theme_py = os.path.join(themedir, 'py')
if not theme_py in sys.path:
sys.path.insert(1, theme_py)
try:
from wmk_theme_autoload import autoload as theme_autoload
for k in theme_autoload:
if k in autoload:
continue
autoload[k] = theme_autoload[k]
except:
pass
# Global data for template rendering, used by both process_templates
# and process_markdown_content.
template_vars = get_template_vars(dirs, themedir, conf, assets_map=None)
lookup = get_template_lookup(dirs, themedir, conf, template_vars)
conf['_lookup'] = lookup
# 4) get info about stand-alone templates and Markdown content
index_yaml = get_index_yaml_data(dirs['content'], dirs['data'])
conf['_index_yaml_data'] = index_yaml or {}
content = get_content(
dirs['content'], dirs['data'], dirs['output'],
template_vars, conf, force=force,
previewing=preview_file, preview_content=preview_content)
return content if with_metadata else content['rendered']
def conf_merge(primary, secondary):
"""
Merge theme_conf (= secondary) with conf (= primary), which is changed.
Values from secondary (and from dicts inside it) are only added to primary
if their key is not present beforehand at the same level.
"""
if not secondary:
return
dictkeys = set([k for k in secondary if isinstance(secondary[k], dict)])
for k in secondary:
if not k in primary:
primary[k] = secondary[k]
elif k in dictkeys and isinstance(primary[k], dict):
for k2 in secondary[k]:
if not k2 in primary[k]:
primary[k][k2] = secondary[k][k2]
@hookable
def run_init_commands(basedir, conf):
init_commands = conf.get('init_commands', [])
for cmd in init_commands:
print("[%s] - init command: %s" % (datetime.datetime.now(), cmd))
ret = subprocess.run(
cmd, cwd=basedir, shell=True, capture_output=True, encoding='utf-8')
if ret.returncode == 0 and ret.stdout:
print(" **OK**:", ret.stdout)
elif ret.returncode != 0:
print(' **WARNING: init command error [exitcode={}]:'.format(
ret.returncode), ret.stderr)
@hookable
def copy_static_files(dirs, themedir, conf, quick=False):
if themedir and os.path.exists(os.path.join(themedir, 'static')):
os.system('rsync -a "%s/" "%s/"' % (
os.path.join(themedir, 'static'), dirs['output']))
if quick:
os.system('rsync -a --update "%s/" "%s/"' % (dirs['static'], dirs['output']))
else:
os.system('rsync -a "%s/" "%s/"' % (dirs['static'], dirs['output']))
# support content bundles (mainly images inside content dir)
content_extensions = get_content_extensions(conf)
ext_excludes = ' '.join(['--exclude "*{}"'.format(_) for _ in content_extensions.keys()])
if quick:
ext_excludes = '--update ' + ext_excludes
os.system(
'rsync -a ' + ext_excludes + ' --exclude "*.yaml" --exclude "_*" --exclude ".*" --prune-empty-dirs "%s/" "%s/"'
% (dirs['content'], dirs['output']))
@hookable
def post_build_actions(conf, dirs, templates, content):
"""
This is the hookable you would override for updating a search index
(e.g. if you are not using lunr and want to have the option of indexing the
output of stand-alone templates). By default, it just calls index_content().
"""
index_content(content, conf, dirs['content'])
@hookable
def get_content_extensions(conf):
ce = conf.get('content_extensions', None)
if ce is None and not conf.get('pandoc'):
# If pandoc is True in the global config, we support all known content
# extensions by default. Otherwise, we only support markdown and html.
ce = ['.md', '.mdwn', '.mdown', '.markdown', '.gfm', '.mmd' '.htm', '.html']
if isinstance(ce, dict):
return ce
elif isinstance(ce, list):
ret = {}
for it in ce:
k = it if it.startswith('.') else '.' + it
ret[k] = DEFAULT_CONTENT_EXTENSIONS.get(k, None)
if ret[k] is None:
ret[k] = {'pandoc': True, 'pandoc_input_format': k[1:]}
return ret
# Should only get here if pandoc is globally true
return DEFAULT_CONTENT_EXTENSIONS
@hookable
def get_assets_map(conf, datadir):
if not 'assets_map' in conf:
return {}
am = conf['assets_map']
if isinstance(am, dict):
return conf['assets_map']
elif isinstance(am, str):
if not am.endswith(('.json', '.yaml')):
return {}
path = os.path.join(datadir, am.strip('/'))
if not os.path.exists(path):
return {}
with open(path) as f:
if am.endswith('.json'):
return json.loads(f.read())
elif am.endswith('yaml'):
return yaml.safe_load(f)
return {}
def get_dirs(basedir, conf):
"""
Configuration of subdirectory names relative to the basedir.
"""
# For those who prefer 'site' or 'public' to 'htdocs' -- or perhaps
# in order to distinguish production and development setups.
output_dir = conf.get('output_directory', 'htdocs')
output_dir = re.sub(r'^[\.\/]+', '', output_dir)
return {
'base': basedir,
'templates': basedir + '/templates', # Mako/Jinja2 templates
'content': basedir + '/content', # Markdown files
'output': basedir + '/' + output_dir, # normally htdocs/
'static': basedir + '/static',
'assets': basedir + '/assets', # only scss for now
'data': basedir + '/data', # YAML, potentially sqlite
'themes': basedir + '/themes', # extra static/assets/templates
'python': basedir + '/py', # python modules for hooks/templates
}
def get_config(basedir, conf_file):
filename = os.path.join(basedir, conf_file)
conf_dir = os.path.join(basedir, conf_file.replace('.yaml', '.d'))
conf = {}
# Note that unsafe loading is only allowed for the top-level config, i.e.
# wmk_config.yaml (either prject or theme). This allows python-specific
# expressions, such as '!!python/name:my_package.containing.my_def'
if os.path.exists(filename):
with open(filename) as f:
conf = yaml.load(f, yaml.UnsafeLoader) or {}
# Look for yaml files inside data/wmk_config.d. Each file contains the
# value for the key specified by the path name to it, e.g. ./site/info.yaml
# contains the value of site.data. (The contents of ./site.yaml, if present,
# is merged with the contents of the files inside the ./site/ directory).
if os.path.isdir(conf_dir):
dirconf = {}
for root, dirs, fils in os.walk(conf_dir):
nesting = root[len(conf_dir)+1:]
pathkeys = [_ for _ in nesting.split('/') if _]
for fn in fils:
if not fn.endswith('.yaml'):
continue
filkey = fn.replace('.yaml', '')
with open(os.path.join(root, fn)) as f:
partial = yaml.safe_load(f) or {}
_ensure_nested_dict(dirconf, pathkeys, filkey, partial)
for k in dirconf:
if k in conf and isinstance(conf[k], dict):
conf[k].update(dirconf[k])
else:
conf[k] = dirconf[k]
return conf
def _ensure_nested_dict(dic, keylist, key, val=None):
# Helper function for get_config.
for k in keylist:
dic = dic.setdefault(k, {})
if key in dic and isinstance(dic[key], dict) and isinstance(val, dict):
dic[key].update(val)
else:
dic[key] = val
@hookable
def process_templates(templates, lookup, template_vars, force):
"""
Renders the specified templates into the outputdir.
"""
for tpl in templates:
# NOTE: very crude, not affected by template dependencies
if not force and is_older_than(tpl['src_path'], tpl['target']):
continue
template = lookup.get_template(tpl['src'])
#data = get_data(tpl['data'], datadir=datadir)
#kannski byggt á tpl.module.DATA attribute?
data = template_vars
maybe_mkdir(tpl['target'])
self_url = tpl['target'].replace(data['WEBROOT'], '', 1)
self_url = re.sub(r'/index.html$', '/', self_url)
data['SELF_URL'] = self_url
data['SELF_FULL_PATH'] = None
data['SELF_TEMPLATE'] = tpl['src']
data['LOOKUP'] = lookup
data['page'] = attrdict({}) # empty but present...
try:
tpl_output = template.render(**data)
except:
print("WARNING: Error when rendering {}: {}".format(
tpl['src_path'], text_error_template().render()))
tpl_output = None
# empty output => nothing is written
if tpl_output:
with open(tpl['target'], 'w') as f:
f.write(tpl_output)
print('[%s] - template: %s' % (
str(datetime.datetime.now()), tpl['src']))
elif tpl_output is not None:
# (probably) deliberately empty output
print("NOTICE: template {} had no output, nothing written".format(
tpl['src']))
@hookable
def process_markdown_content(content, lookup, conf, force):
"""
Renders the specified markdown content into the outputdir.
"""
for ct in content:
if not force and is_older_than(ct['source_file'], ct['target']):
continue
try:
template = None if ct['template'].lower() == '__empty__' \
else lookup.get_template(ct['template'])
except TemplateLookupException:
if not '/' in ct['template']:
template = lookup.get_template('base/' + ct['template'])
ct['template'] = 'base/' + ct['template']
else:
raise
maybe_mkdir(ct['target'])
data = ct['data']
# Since 'pre_render' was dropped, this condition should always be true.
html = ct['rendered'] if 'rendered' in ct else render_markdown(ct, conf)
data['CONTENT'] = html
data['RAW_CONTENT'] = ct['doc']
page = data['page']
global autoload
if page.POSTPROCESS and page._CACHER:
# NOTE: Because of the way we handle caching in the presence of
# postprocessing, the postprocess chain is potentially run twice
# for each applicable page: once before the Mako template is called,
# and once after. To prevent this, we use the `was_called`
# attribute which when present prevents the postprocessing from
# taking place after the template has been applied.
# AS A CONSEQUENCE, the range of application for a cached and a
# non-cached page will be slightly different in that a cached page
# will not apply the postprocessing code to the parts of the HTML
# supplied by the Mako template, only to the HTML directly converted
# from Markdown. For most purposes this will not matter. If it does
# for some specific page you will need to set `no_cache` to True
# in its frontmatter.
for pp in page.POSTPROCESS:
if isinstance(pp, str):
if autoload and pp in autoload:
html = autoload[pp](html, **data)
autoload[pp].was_called = data['SELF_FULL_PATH']
else:
print("WARNING: postprocess action '%s' missing for %s"
% (pp, ct['url']))
else:
try:
html = pp(html, **data)
pp.was_called = data['SELF_FULL_PATH']
except Exception as e:
print("WARNING: postprocess failed for {}: {}".format(
ct['source_file_short'], e))
page._CACHER(html)
ct['rendered'] = html
data['CONTENT'] = html
try:
data['TOC'] = Toc(html)
except Exception as e:
print("TOC ERROR for %s: %s" % (ct['url'], str(e)))
data['TOC'] = Toc('')
html_output = ''
handle_taxonomy(data)
try:
if template is None:
html_output = data['CONTENT'] or ''
else:
html_output = template.render(**data)
except:
# TODO: Does not really make sense for Jinja template errors
print("WARNING: Error when rendering {}: {}".format(
ct['source_file_short'], text_error_template().render()))
# If present, POSTPROCESS will have been added by a shortcode call
if html_output and page.get('POSTPROCESS'):
html_output = postprocess_html(page.POSTPROCESS, data, html_output)
if html_output and not page.get('do_not_render', False):
with open(ct['target'], 'w') as f:
f.write(html_output)
print('[%s] - content: %s' % (
str(datetime.datetime.now()), ct['source_file_short']))
elif html_output:
# This output is non-draft but marked as not to be rendered.
# ("headless" in Hugo parlance)
print('[%s] - non-rendered: %s' % (
str(datetime.datetime.now()), ct['source_file_short']))
@hookable
def handle_taxonomy(data):
"""
- Adds TAXONS to context (i.e. data) for the base template that will be
called immediately after this in the flow.
- Writes a page (using the MDContentList write_to() method) for each taxon
with TAXON (== CHUNK) and TAXON_INDEX (indicating its ordering in TAXONS)
in the context.
- No return value.
"""
txy = data['page'].TAXONOMY
if txy and 'taxon' in txy:
detail_template = txy.get('detail_template', data['page'].template)
txy.valid = True
maybe_order = {'order': txy['order']} if txy['order'] else {}
taxons = data['MDCONTENT'].taxonomy_info(txy['taxon'], **maybe_order)
data['TAXONS'] = taxons
base_url = data['SELF_URL']
for i, tx in enumerate(taxons):
# NOTE: Assumes normal pretty_path setting!
dest = re.sub(r'/index.html$',
'/{}/index.html'.format(tx['slug']),
base_url)
if dest == data['SELF_URL']:
raise Exception(
'handle_taxonomy() requires pretty_path to be active or auto')
ctx = dict(**data)
ctx['SELF_TEMPLATE'] = detail_template
tx['url'] = dest
tx['items'].write_to(
dest=dest,
context=ctx,
extra_kwargs={'TAXON': tx, 'TAXON_INDEX': i},
template=detail_template)
elif txy:
print("WARNING: BAD TAXONOMY for", data['SELF_URL'])
txy.valid = False
data['TAXONS'] = []
@hookable
def postprocess_html(ppr, data, html):
"""
- ppr is a postprocessing callable or a list of such.
- data is the entire context previously passed to the mako renderer.
- html is the entire HTML page previously returned from the mako renderer.
Each postprocessing callable MUST return the html (changed or unchanged).
Returning None or an empty string results in the file not being rendered.
"""
# data contains page, CONTENT, RAW_CONTENT, etc.
if callable(ppr):
ppr = [ppr]
fullpath = data['SELF_FULL_PATH']
if isinstance(ppr, (list, tuple)):
for pp in ppr:
ppc = pp if callable(pp) else (autoload or {}).get(pp, None)
if not ppc:
print("WARNING: postprocess action '%s' missing for %s"
% (pp, fullpath))
continue
was_called = getattr(ppc, 'was_called', False)
if was_called and was_called == fullpath:
continue
elif was_called:
# The attribute was set by a different (cached) page using the same
# callable for postprocessing; let's reset it.
ppc.was_called = False
html = ppc(html, **data)
return html
@hookable
def render_markdown(ct, conf):
"""
Convert markdown document to HTML (including shortcodes).
If possible, retrieve the converted version from cache.
"""
if 'CONTENT' in ct:
return ct['CONTENT']
data = ct['data']
pg = data.get('page', {})
doc = ct['doc']
target = ct.get('target', '')
# The following settings affect cache validity:
extensions, extension_configs = markdown_extensions_settings(pg, conf)
is_html = pg.get('_is_html', ct.get('source_file', '').endswith('.html'))
is_pandoc = pg.get('pandoc', conf.get('pandoc', False))
pandoc_filters = pg.get('pandoc_filters', conf.get('pandoc_filters')) or []
pandoc_options = pg.get('pandoc_options', conf.get('pandoc_options')) or []
# This should be a markdown/commonmark subformat or gfm, unless the
# extension dictates otherwise (e.g. rst, org, textile, man)
pandoc_input = pg.get('pandoc_input_format',
conf.get('pandoc_input_format')) or 'markdown'
# This should be an html subformat
pandoc_output = pg.get('pandoc_output_format',
conf.get('pandoc_output_format')) or 'html'
use_cache = conf.get('use_cache', True) and not pg.get('no_cache', False)
if use_cache:
mtime_matters = pg.get('cache_mtime_matters',
conf.get('cache_mtime_matters', False))
maybe_mtime = ct['data']['MTIME'] if mtime_matters else None
optstr = str([target, extensions, extension_configs,
is_pandoc, pandoc_filters, pandoc_options,
pandoc_input, pandoc_output, maybe_mtime])
projectdir = ct['data']['DATADIR'][:-5] # remove /data from the end
cache = RenderCache(doc, optstr, projectdir)
ret = cache.get_cache()
if ret:
return ret
else:
ret = None
cache = None
nth = {}
## Note that PREPROCESS is now run before shortcodes are interpreted, so
## such actions cannot be added by them. PREPROCESS actions may for instance
## handle syntactic sugar that transforms into shortcodes behind the scenes.
if pg.PREPROCESS:
global autoload
pg.is_pandoc = is_pandoc
for pp in pg.PREPROCESS:
if isinstance(pp, str):
if autoload and pp in autoload:
doc = autoload[pp](doc, pg)
else:
print("WARNING: Preprocessor '%s' not present for %s"
% (pp, ct['source_file_short']))
else:
doc = pp(doc, pg)
# POSTPROCESS, on the other hand may be added by shortcodes (and often is)
if '{{<' in doc:
# SHORTCODES:
# We need to handle include() first.
incpat = r'{{<[ \n\r\t]*(include)\(\s*(.*?)\s*\)\s*>}}'
incfound = re.search(incpat, doc, re.DOTALL)
while incfound:
doc = re.sub(incpat, handle_shortcode(conf, data, nth), doc, flags=re.DOTALL)
incfound = re.search(incpat, doc, re.DOTALL)
# Now other shortcodes.
# funcname, argstring
pat = r'{{<[ \n\r\t]*(\w+)\(\s*(.*?)\s*\)\s*>}}'
found = re.search(pat, doc, re.DOTALL)
while found:
doc = re.sub(pat, handle_shortcode(conf, data, nth), doc, flags=re.DOTALL)
found = re.search(pat, doc, re.DOTALL)
if is_html:
ret = doc
elif is_pandoc:
# For TOC to be added inline, page.toc must be True and the
# markdown content must have a '[TOC]' line.
# Note that this is different from the Toc object available
# in the template context as the TOC variable.
need_toc = (
pg.get('toc', False)
and re.search(r'^\[TOC\]$', doc, flags=re.M))
if need_toc:
if not pandoc_options:
pandoc_options = []
pandoc_options.append('--toc')
pandoc_options.append('--standalone')
toc_depth = ct['data']['page'].get('toc_depth')
if toc_depth:
pandoc_options.append('--toc-depth=%s' % toc_depth)
toc_tpl = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
'aux',
'pandoc-toc-only.html')
pandoc_options.append('--template=%s' % toc_tpl)
popt = {}
if pandoc_filters:
popt['filters'] = pandoc_filters