-
Notifications
You must be signed in to change notification settings - Fork 0
/
makeme.py
executable file
·210 lines (154 loc) · 5.05 KB
/
makeme.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
#!/usr/bin/env python3
import argparse
import logging
import re
import markdown2 as m
from jinja2 import Environment, FileSystemLoader
from os import makedirs, mkdir, walk
from os.path import basename, exists, getmtime, split
from shutil import copy2
from sys import exit
l = logging.getLogger('Flourish! Makeme')
###
# Tasks
###
def generate(args):
if not exists(args['dest']):
l.info('Creating destination (' + args['dest'] + ") directory.")
mkdir(args['dest'])
generate_site(args)
###
# Generate stuffs
###
def generate_site(args):
l.debug('Generating site.')
env = Environment(loader=FileSystemLoader(args['src'] + '/templates'))
site = {}
parse_pages(args, site)
make_site(args, site, env)
# parse out a file
def parse_file(filename):
l.debug('Parsing file: ' + filename)
parsed = {}
f = open(filename)
contents = ''
for line in f:
contents += line
f.close()
try:
html = genHTML(contents)
parsed['content'] = html
parsed['config'] = html.metadata
parsed['filename'] = basename(filename)
parsed['changed'] = getmtime(filename)
return parsed
except Exception as e:
l.critical("Couldn't parse yaml in " + filename)
raise
# turn markdown into HTML
def genHTML(markdown):
return m.markdown(markdown, extras=['fenced-code-blocks', 'metadata', 'smarty-pants'])
# find all files in directory `directory` and all subdirectories therein.
# using those files, parse them using `parse_fn`, and add the parsed contents
# to list `container`
def parse_dir(container, directory, parse_fn):
for root, dirs, files in walk(directory):
for f in files:
if f[0] == ".":
continue
container.append(parse_fn(root + '/' + f))
for d in dirs:
parse_dir(container, d, parse_fn)
###
# Page things
###
# parse all pages in a site
def parse_pages(args, site):
pages = []
page_directory = args['src'] + '/pages'
parse_dir(pages, page_directory, parse_page)
site['pages'] = pages
# parse an individual page
def parse_page(filename):
l.debug('Parsing page: ' + filename)
print('Parsing page: ' + filename)
page = parse_file(filename)
page['title'] = page['config']['title']
if 'layout' not in page['config']:
page['layout'] = 'page.html'
else:
page['layout'] = page['config']['layout']
if 'slug' in page['config']:
page['slug'] = page['config']['slug']
else:
page['slug'] = splitext(page['filename'])[0]
return page
###
# The Magic
###
# start putting things together
def make_site(args, site, env):
expand_pages(args, site, env)
copy_assets(args, site)
# expand pages
def expand_pages(args, site, env):
for page in site['pages']:
#out_path = args['dest'] + page['slug']
out_dir, out_file = split(args['dest'] + '/' + page['slug'])
if out_file == '':
out_file = 'index.html'
else:
# make sure this is really a file, and not a directory...
# MUST HAVE `.` somewhere in name
fname = 'index.html'
for i in range(len(out_file) - 1, 0, -1):
if out_file[i] == '.':
fname = out_file
break
out_file = fname
l.debug(str(exists(out_dir)) + "\t: " + out_dir)
if not exists(out_dir):
makedirs(out_dir)
writer = open(out_dir + '/' + out_file, 'w')
template = env.get_template(page['layout'])
writer.write(template.render(site=site, page=page))
writer.close()
# copy static assets
def copy_assets(args, site):
if not exists(args['src'] + '/assets'):
l.debug('no assets')
return
newPath = args['dest']
for root, dirs, files in walk(args['src'] + '/assets'):
for d in dirs:
ndir = root + '/' + d
ndir = ndir.replace(args['src'], newPath)
if not exists(ndir):
makedirs(ndir)
for f in files:
fPath = root + '/' + f
nfPath = fPath.replace(args['src'], newPath)
if exists(nfPath):
if getmtime(nfPath) > getmtime(fPath):
continue
copy2(fPath, nfPath)
if __name__ == '__main__':
###
# Argument parsing things
###
parser = argparse.ArgumentParser(description='Flourish! Makeme is a simple static site generator.', prog="makeme.py")
sub = parser.add_subparsers()
# logging level parser.
level = parser.add_mutually_exclusive_group()
level.add_argument('-l', '--level', default='INFO', type=str.upper, choices=['DEBUG', 'INFO', 'WARNING', 'ERROR'], help="Sets %(prog)s\'s log level.")
level.add_argument('-q', '--quiet', action='store_const', const='ERROR', dest='level', help='Sets %(prog)s\'s log level to ERROR.')
level.add_argument('-v', '--verbose', action='store_const', const='DEBUG', dest='level', help='Sets %(prog)\'s log level to DEBUG.')
# generate parser
gen = sub.add_parser('generate')
gen.add_argument('src', nargs='?', default='./', metavar='source', help='The directory %(prog)s looks in for source files.')
gen.add_argument('dest', nargs='?', default='./_site', metavar='destination', help='The directory %(prog)s outputs to.')
gen.set_defaults(func=generate)
args = vars(parser.parse_args())
#print(args)
l.setLevel(logging.DEBUG)
args['func'](args)