-
Notifications
You must be signed in to change notification settings - Fork 14
/
main.py
362 lines (293 loc) · 11.4 KB
/
main.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
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from datetime import datetime
import mimetypes
import os
from os.path import (isfile, isdir, dirname, join, splitext, basename, exists,
relpath, sep)
import re
import socket
from flask import (Flask, request, has_request_context, render_template,
make_response, abort, send_file)
from jinja2 import ChoiceLoader, FileSystemLoader, PackageLoader
from jinja2.exceptions import TemplateNotFound
import yaml
from .helpers import (read_content, make_dirs, create_file,
copy_if_updated, get_updated_datetime)
from .jinja_includewith import IncludeWith
from .tglobals import link_to, active, to_unicode
SOURCE_DIRNAME = 'source'
BUILD_DIRNAME = 'build'
TMPL_EXTS = ('.html', '.tmpl')
RX_TMPL = re.compile(r'\.tmpl$')
HTTP_NOT_FOUND = 404
DEFAULT_HOST = '0.0.0.0'
DEFAULT_PORT = 8080
WELCOME = u" # Clay (by Lucuma labs)"
ADDRINUSE = u" ---- Address already in use. Trying another port..."
SOURCE_NOT_FOUND = u"""We couldn't found a "%s" dir.
Are you sure you're in the correct folder? """ % SOURCE_DIRNAME
rx_abs_url = re.compile(r'\s(src|href|data-[a-z0-9_-]+)\s*=\s*[\'"](\/(?:[a-z0-9_-][^\'"]*)?)[\'"]',
re.UNICODE | re.IGNORECASE)
class Clay(object):
def __init__(self, root, settings=None):
if isfile(root):
root = dirname(root)
settings = settings or {}
self.settings = settings
self.settings_path = join(root, 'settings.yml')
self.load_settings_from_file()
self.source_dir = join(root, SOURCE_DIRNAME)
self.build_dir = join(root, BUILD_DIRNAME)
self.app = self.make_app()
def make_app(self):
app = Flask('clay', static_folder=None, template_folder=self.source_dir)
app.jinja_loader = self.get_jinja_loader()
app.jinja_options = self.get_jinja_options()
app.debug = True
self.set_template_context_processors(app)
self.set_urls(app)
return app
def get_jinja_loader(self):
return ChoiceLoader([
FileSystemLoader(self.source_dir),
PackageLoader('clay', SOURCE_DIRNAME),
])
def get_jinja_options(self):
return {
'autoescape': True,
'extensions': ['jinja2.ext.with_', IncludeWith]
}
def set_template_context_processors(self, app):
@app.context_processor
def inject_globals():
return {
'CLAY_URL': 'http://lucuma.github.com/Clay',
'now': datetime.utcnow(),
'enumerate': enumerate,
'active': active,
'link_to': link_to,
}
def set_urls(self, app):
app.add_url_rule('/', 'page', self.render_page)
app.add_url_rule('/<path:path>', 'page', self.render_page)
app.add_url_rule('/_index.html', 'index', self.show__index)
app.add_url_rule('/_index.txt', 'index_txt', self.show__index_txt)
def load_settings_from_file(self):
if isfile(self.settings_path):
source = read_content(self.settings_path)
st = yaml.load(source)
self.settings.update(st)
def _get_base_url(self):
host = self.settings.get('host', DEFAULT_HOST)
port = self.settings.get('port', DEFAULT_PORT)
return 'http://%s:%s' % (host, port)
def render(self, path, context):
if has_request_context():
return render_template(path, **context)
base_url = self._get_base_url()
with self.app.test_request_context('/' + path, base_url=base_url, method='GET'):
return render_template(path, **context)
def get_full_source_path(self, path):
return join(self.source_dir, path)
def get_full_build_path(self, path):
return join(self.build_dir, path)
def get_real_fn(self, path):
filename = basename(path)
fn, ext = splitext(filename)
fn2, ext2 = splitext(fn)
if ext2:
return fn
return filename
def guess_mimetype(self, fn):
return mimetypes.guess_type(fn)[0] or 'text/plain'
def normalize_path(self, path):
path = path or 'index.html'
if isdir(self.get_full_source_path(path)):
path = '/'.join([path, 'index.html'])
return path
def get_relpath(self, folder):
rel = relpath(folder, self.source_dir)
return rel.lstrip('.').lstrip(sep)
def _get_run_config(self, host, port):
port = port or self.settings.get('port', DEFAULT_PORT)
return {
'host': host or self.settings.get('host', DEFAULT_HOST),
'port': int(port),
'use_debugger': True,
'use_reloader': False,
}
def remove_template_ext(self, path):
return RX_TMPL.sub('', path)
def get_relative_url(self, relpath, currurl):
depth = relpath.count('/')
url = (ur'../' * depth) + currurl.lstrip('/')
if not url:
return 'index.html'
path = self.get_full_source_path(url)
if isdir(path) or url.endswith('/'):
return url.rstrip('/') + '/index.html'
return url
def make_absolute_urls_relative(self, content, relpath):
for attr, url in rx_abs_url.findall(content):
newurl = self.get_relative_url(relpath, url)
repl = ur' %s="%s"' % (attr, newurl)
content = re.sub(rx_abs_url, repl, content, count=1)
return content
def is_html_fragment(self, content):
head = content[:500].strip().lower()
return not (head.startswith('<!doctype ') or head.startswith('<html'))
def must_be_included(self, path):
return path in self.settings.get('INCLUDE', [])
def must_be_filtered(self, path):
filename = basename(path)
return filename.startswith('.') or path in self.settings.get('FILTER', [])
def must_filter_fragment(self, content):
return self.settings.get('FILTER_PARTIALS') and self.is_html_fragment(content)
def get_pages_list(self):
pages = []
for folder, subs, files in os.walk(self.source_dir):
rel = self.get_relpath(folder)
for filename in files:
pages.append(join(rel, filename))
return pages
def get_pages_index(self):
index = []
pages = self.get_pages_list()
for path in pages:
if not path.endswith(TMPL_EXTS):
continue
if not self.must_be_included(path):
if self.must_be_filtered(path):
continue
content = self.render(path, self.settings)
if self.must_filter_fragment(content):
continue
fullpath = self.get_full_source_path(path)
updated_at = get_updated_datetime(fullpath)
index.append((path, updated_at))
return index
def send_file(self, path):
fp = self.get_full_source_path(path)
try:
return send_file(fp)
except IOError:
return self.show_notfound(path)
def render_page(self, path=None):
path = self.normalize_path(path)
if not path.endswith(TMPL_EXTS):
return self.send_file(path)
try:
res = self.render(path, self.settings)
except TemplateNotFound, e:
return self.show_notfound(e)
response = make_response(res)
response.mimetype = self.guess_mimetype(self.get_real_fn(path))
return response
def _make__index(self, path):
index = self.get_pages_index()
context = self.settings.copy()
context['index'] = index
return self.render(path, context)
def show__index_txt(self):
path = '_index.txt'
content = self._make__index(path)
resp = make_response(content)
resp.mimetype = 'text/plain'
return resp
def build__index_txt(self):
path = '_index.txt'
self.print_build_message(path)
content = self._make__index(path)
bp = self.get_full_build_path(path)
create_file(bp, content)
def show__index(self):
path = '_index.html'
content = self._make__index(path)
resp = make_response(content)
resp.mimetype = 'text/html'
return resp
def build__index(self):
path = '_index.html'
self.print_build_message(path)
content = self._make__index(path)
bp = self.get_full_build_path(path)
create_file(bp, content)
def print_build_message(self, path):
print ' ', to_unicode(self.remove_template_ext(path))
def build_page(self, path):
sp = self.get_full_source_path(path)
bp = self.get_full_build_path(path)
make_dirs(dirname(bp))
if not path.endswith(TMPL_EXTS):
if self.must_be_filtered(path):
return
self.print_build_message(path)
return copy_if_updated(sp, bp)
content = u''
if not self.must_be_included(path):
if self.must_be_filtered(path):
return
content = self.render(path, self.settings)
if self.must_filter_fragment(content):
return
self.print_build_message(path)
bp = self.remove_template_ext(bp)
if bp.endswith('.html'):
content = self.make_absolute_urls_relative(content, path)
create_file(bp, content)
def print_welcome_msg(self):
print WELCOME
def print_help_msg(self, host, port):
print ' - Quit the server with Ctrl+C -'
if host == '0.0.0.0':
ips = [ip
for ip in socket.gethostbyname_ex(socket.gethostname())[2]
if not ip.startswith("127.")
][:1]
if ips:
print ' * Running on http://%s:%s' % (ips[0], port)
def run_in_next_free_port(self, config):
current_port = config['port']
max_port = current_port + 10
def run(current_port, config):
try:
self.print_help_msg(config['host'], current_port)
config['port'] = current_port
return self.app.run(**config)
except socket.error, e:
if e.errno != socket.errno.EADDRINUSE:
print e
return
print ADDRINUSE
current_port += 1
if current_port > max_port:
return
return run(current_port, config)
return run(current_port, config)
def run(self, host=DEFAULT_HOST, port=DEFAULT_PORT):
if not exists(self.source_dir):
print SOURCE_NOT_FOUND
return
config = self._get_run_config(host, port)
self.print_welcome_msg()
return self.run_in_next_free_port(config)
def build(self):
pages = self.get_pages_list()
print u'Building...\n'
for path in pages:
self.build_page(path)
self.build__index()
self.build__index_txt()
print u'\nDone.'
def show_notfound(self, path):
context = self.settings.copy()
context['path'] = path
res = self.render('_notfound.html', context)
return make_response(res, HTTP_NOT_FOUND)
def get_test_client(self):
self.app.testing = True
host = self.settings.get('host', DEFAULT_HOST)
port = self.settings.get('port', DEFAULT_PORT)
self.app.config['SERVER_NAME'] = '%s:%s' % (host, port)
return self.app.test_client()