/
init.py
479 lines (422 loc) · 19.1 KB
/
init.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
# -*- coding: utf-8 -*-
# Copyright © 2012-2015 Roberto Alsina and others.
# Permission is hereby granted, free of charge, to any
# person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the
# Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the
# Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice
# shall be included in all copies or substantial portions of
# the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
# OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
from __future__ import print_function, unicode_literals
import os
import shutil
import io
import json
import textwrap
import datetime
import unidecode
import dateutil.tz
import dateutil.zoneinfo
from mako.template import Template
from pkg_resources import resource_filename
import tarfile
import nikola
from nikola.nikola import DEFAULT_TRANSLATIONS_PATTERN, DEFAULT_INDEX_READ_MORE_LINK, DEFAULT_RSS_READ_MORE_LINK, LEGAL_VALUES, urlsplit, urlunsplit
from nikola.plugin_categories import Command
from nikola.utils import ask, ask_yesno, get_logger, makedirs, STDERR_HANDLER, load_messages
from nikola.packages.tzlocal import get_localzone
LOGGER = get_logger('init', STDERR_HANDLER)
SAMPLE_CONF = {
'BLOG_AUTHOR': "Your Name",
'BLOG_TITLE': "Demo Site",
'SITE_URL': "https://example.com/",
'BLOG_EMAIL': "joe@demo.site",
'BLOG_DESCRIPTION': "This is a demo site for Nikola.",
'DEFAULT_LANG': "en",
'TRANSLATIONS': """{
DEFAULT_LANG: "",
# Example for another language:
# "es": "./es",
}""",
'THEME': 'bootstrap3',
'TIMEZONE': 'UTC',
'COMMENT_SYSTEM': 'disqus',
'COMMENT_SYSTEM_ID': 'nikolademo',
'TRANSLATIONS_PATTERN': DEFAULT_TRANSLATIONS_PATTERN,
'INDEX_READ_MORE_LINK': DEFAULT_INDEX_READ_MORE_LINK,
'RSS_READ_MORE_LINK': DEFAULT_RSS_READ_MORE_LINK,
'POSTS': """(
("posts/*.rst", "posts", "post.tmpl"),
("posts/*.txt", "posts", "post.tmpl"),
)""",
'PAGES': """(
("stories/*.rst", "stories", "story.tmpl"),
("stories/*.txt", "stories", "story.tmpl"),
)""",
'COMPILERS': """{
"rest": ('.rst', '.txt'),
"markdown": ('.md', '.mdown', '.markdown'),
"textile": ('.textile',),
"txt2tags": ('.t2t',),
"bbcode": ('.bb',),
"wiki": ('.wiki',),
"ipynb": ('.ipynb',),
"html": ('.html', '.htm'),
# PHP files are rendered the usual way (i.e. with the full templates).
# The resulting files have .php extensions, making it possible to run
# them without reconfiguring your server to recognize them.
"php": ('.php',),
# Pandoc detects the input from the source filename
# but is disabled by default as it would conflict
# with many of the others.
# "pandoc": ('.rst', '.md', '.txt'),
}""",
'NAVIGATION_LINKS': """{
DEFAULT_LANG: (
("/archive.html", "Archives"),
("/categories/index.html", "Tags"),
("/rss.xml", "RSS feed"),
),
}""",
'REDIRECTIONS': [],
}
# Generate a list of supported languages here.
# Ugly code follows.
_suplang = {}
_sllength = 0
for k, v in LEGAL_VALUES['TRANSLATIONS'].items():
if not isinstance(k, tuple):
main = k
_suplang[main] = v
else:
main = k[0]
k = k[1:]
bad = []
good = []
for i in k:
if i.startswith('!'):
bad.append(i[1:])
else:
good.append(i)
different = ''
if good or bad:
different += ' ['
if good:
different += 'ALTERNATIVELY ' + ', '.join(good)
if bad:
if good:
different += '; '
different += 'NOT ' + ', '.join(bad)
if good or bad:
different += ']'
_suplang[main] = v + different
if len(main) > _sllength:
_sllength = len(main)
_sllength = str(_sllength)
suplang = (u'# {0:<' + _sllength + u'} {1}\n').format('en', 'English')
del _suplang['en']
for k, v in sorted(_suplang.items()):
suplang += (u'# {0:<' + _sllength + u'} {1}\n').format(k, v)
SAMPLE_CONF['_SUPPORTED_LANGUAGES'] = suplang.strip()
# Generate a list of supported comment systems here.
SAMPLE_CONF['_SUPPORTED_COMMENT_SYSTEMS'] = '\n'.join(textwrap.wrap(
u', '.join(LEGAL_VALUES['COMMENT_SYSTEM']),
initial_indent=u'# ', subsequent_indent=u'# ', width=79))
def format_default_translations_config(additional_languages):
"""Return the string to configure the TRANSLATIONS config variable to
make each additional language visible on the generated site."""
if not additional_languages:
return SAMPLE_CONF["TRANSLATIONS"]
lang_paths = [' DEFAULT_LANG: "",']
for lang in sorted(additional_languages):
lang_paths.append(' "{0}": "./{0}",'.format(lang))
return "{{\n{0}\n}}".format("\n".join(lang_paths))
def format_navigation_links(additional_languages, default_lang, messages):
"""Return the string to configure NAVIGATION_LINKS."""
f = u"""\
{0}: (
("{1}/archive.html", "{2[Archive]}"),
("{1}/categories/index.html", "{2[Tags]}"),
("{1}/rss.xml", "{2[RSS feed]}"),
),"""
pairs = []
def get_msg(lang):
"""Generate a smaller messages dict with fallback."""
fmsg = {}
for i in (u'Archive', u'Tags', u'RSS feed'):
if messages[lang][i]:
fmsg[i] = messages[lang][i]
else:
fmsg[i] = i
return fmsg
# handle the default language
pairs.append(f.format('DEFAULT_LANG', '', get_msg(default_lang)))
for l in additional_languages:
pairs.append(f.format(json.dumps(l, ensure_ascii=False), '/' + l, get_msg(l)))
return u'{{\n{0}\n}}'.format('\n\n'.join(pairs))
# In order to ensure proper escaping, all variables but the three
# pre-formatted ones are handled by json.dumps().
def prepare_config(config):
"""Parse sample config with JSON."""
p = config.copy()
p.update(dict((k, json.dumps(v, ensure_ascii=False)) for k, v in p.items()
if k not in ('POSTS', 'PAGES', 'COMPILERS', 'TRANSLATIONS', 'NAVIGATION_LINKS', '_SUPPORTED_LANGUAGES', '_SUPPORTED_COMMENT_SYSTEMS', 'INDEX_READ_MORE_LINK', 'RSS_READ_MORE_LINK')))
# READ_MORE_LINKs require some special treatment.
p['INDEX_READ_MORE_LINK'] = "'" + p['INDEX_READ_MORE_LINK'].replace("'", "\\'") + "'"
p['RSS_READ_MORE_LINK'] = "'" + p['RSS_READ_MORE_LINK'].replace("'", "\\'") + "'"
return p
class CommandInit(Command):
"""Create a new site."""
name = "init"
doc_usage = "[--demo] [--quiet] folder"
needs_config = False
doc_purpose = "create a Nikola site in the specified folder"
cmd_options = [
{
'name': 'quiet',
'long': 'quiet',
'short': 'q',
'default': False,
'type': bool,
'help': "Do not ask questions about config.",
},
{
'name': 'demo',
'long': 'demo',
'short': 'd',
'default': False,
'type': bool,
'help': "Create a site filled with example data.",
}
]
@classmethod
def copy_sample_site(cls, target):
src = resource_filename('nikola', os.path.join('data', 'samplesite'))
shutil.copytree(src, target)
@staticmethod
def create_configuration(target):
template_path = resource_filename('nikola', 'conf.py.in')
conf_template = Template(filename=template_path)
conf_path = os.path.join(target, 'conf.py')
with io.open(conf_path, 'w+', encoding='utf8') as fd:
fd.write(conf_template.render(**prepare_config(SAMPLE_CONF)))
@staticmethod
def create_configuration_to_string():
template_path = resource_filename('nikola', 'conf.py.in')
conf_template = Template(filename=template_path)
return conf_template.render(**prepare_config(SAMPLE_CONF))
@classmethod
def create_empty_site(cls, target):
for folder in ('files', 'galleries', 'listings', 'posts', 'stories'):
makedirs(os.path.join(target, folder))
@staticmethod
def ask_questions(target):
"""Ask some questions about Nikola."""
def urlhandler(default, toconf):
answer = ask('Site URL', 'https://example.com/')
try:
answer = answer.decode('utf-8')
except (AttributeError, UnicodeDecodeError):
pass
if not answer.startswith(u'http'):
print(" ERROR: You must specify a protocol (http or https).")
urlhandler(default, toconf)
return
if not answer.endswith('/'):
print(" The URL does not end in '/' -- adding it.")
answer += '/'
dst_url = urlsplit(answer)
try:
dst_url.netloc.encode('ascii')
except (UnicodeEncodeError, UnicodeDecodeError):
# The IDN contains characters beyond ASCII. We must convert it
# to Punycode. (Issue #1644)
nl = dst_url.netloc.encode('idna')
answer = urlunsplit((dst_url.scheme,
nl,
dst_url.path,
dst_url.query,
dst_url.fragment))
print(" Converting to Punycode:", answer)
SAMPLE_CONF['SITE_URL'] = answer
def lhandler(default, toconf, show_header=True):
if show_header:
print("We will now ask you to provide the list of languages you want to use.")
print("Please list all the desired languages, comma-separated, using ISO 639-1 codes. The first language will be used as the default.")
print("Type '?' (a question mark, sans quotes) to list available languages.")
answer = ask('Language(s) to use', 'en')
while answer.strip() == '?':
print('\n# Available languages:')
try:
print(SAMPLE_CONF['_SUPPORTED_LANGUAGES'] + '\n')
except UnicodeEncodeError:
# avoid Unicode characters in supported language names
print(unidecode.unidecode(SAMPLE_CONF['_SUPPORTED_LANGUAGES']) + '\n')
answer = ask('Language(s) to use', 'en')
langs = [i.strip().lower().replace('-', '_') for i in answer.split(',')]
for partial, full in LEGAL_VALUES['_TRANSLATIONS_WITH_COUNTRY_SPECIFIERS'].items():
if partial in langs:
langs[langs.index(partial)] = full
print("NOTICE: Assuming '{0}' instead of '{1}'.".format(full, partial))
default = langs.pop(0)
SAMPLE_CONF['DEFAULT_LANG'] = default
# format_default_translations_config() is intelligent enough to
# return the current value if there are no additional languages.
SAMPLE_CONF['TRANSLATIONS'] = format_default_translations_config(langs)
# Get messages for navigation_links. In order to do this, we need
# to generate a throwaway TRANSLATIONS dict.
tr = {default: ''}
for l in langs:
tr[l] = './' + l
# Assuming that base contains all the locales, and that base does
# not inherit from anywhere.
try:
messages = load_messages(['base'], tr, default)
SAMPLE_CONF['NAVIGATION_LINKS'] = format_navigation_links(langs, default, messages)
except nikola.utils.LanguageNotFoundError as e:
print(" ERROR: the language '{0}' is not supported.".format(e.lang))
print(" Are you sure you spelled the name correctly? Names are case-sensitive and need to be reproduced as-is (complete with the country specifier, if any).")
print("\nType '?' (a question mark, sans quotes) to list available languages.")
lhandler(default, toconf, show_header=False)
def tzhandler(default, toconf):
print("\nPlease choose the correct time zone for your blog. Nikola uses the tz database.")
print("You can find your time zone here:")
print("http://en.wikipedia.org/wiki/List_of_tz_database_time_zones")
print("")
answered = False
while not answered:
try:
lz = get_localzone()
except:
lz = None
answer = ask('Time zone', lz if lz else "UTC")
tz = dateutil.tz.gettz(answer)
if tz is None:
print(" WARNING: Time zone not found. Searching list of time zones for a match.")
zonesfile = tarfile.open(fileobj=dateutil.zoneinfo.getzoneinfofile_stream())
zonenames = [zone for zone in zonesfile.getnames() if answer.lower() in zone.lower()]
if len(zonenames) == 1:
tz = dateutil.tz.gettz(zonenames[0])
answer = zonenames[0]
print(" Picking '{0}'.".format(answer))
elif len(zonenames) > 1:
print(" The following time zones match your query:")
print(' ' + '\n '.join(zonenames))
continue
if tz is not None:
time = datetime.datetime.now(tz).strftime('%H:%M:%S')
print(" Current time in {0}: {1}".format(answer, time))
answered = ask_yesno("Use this time zone?", True)
else:
print(" ERROR: No matches found. Please try again.")
SAMPLE_CONF['TIMEZONE'] = answer
def chandler(default, toconf):
print("You can configure comments now. Type '?' (a question mark, sans quotes) to list available comment systems. If you do not want any comments, just leave the field blank.")
answer = ask('Comment system', '')
while answer.strip() == '?':
print('\n# Available comment systems:')
print(SAMPLE_CONF['_SUPPORTED_COMMENT_SYSTEMS'])
print('')
answer = ask('Comment system', '')
while answer and answer not in LEGAL_VALUES['COMMENT_SYSTEM']:
if answer != '?':
print(' ERROR: Nikola does not know this comment system.')
print('\n# Available comment systems:')
print(SAMPLE_CONF['_SUPPORTED_COMMENT_SYSTEMS'])
print('')
answer = ask('Comment system', '')
SAMPLE_CONF['COMMENT_SYSTEM'] = answer
SAMPLE_CONF['COMMENT_SYSTEM_ID'] = ''
if answer:
print("You need to provide the site identifier for your comment system. Consult the Nikola manual for details on what the value should be. (you can leave it empty and come back later)")
answer = ask('Comment system site identifier', '')
SAMPLE_CONF['COMMENT_SYSTEM_ID'] = answer
STORAGE = {'target': target}
questions = [
('Questions about the site', None, None, None),
# query, default, toconf, destination
('Destination', None, False, '!target'),
('Site title', 'My Nikola Site', True, 'BLOG_TITLE'),
('Site author', 'Nikola Tesla', True, 'BLOG_AUTHOR'),
('Site author\'s e-mail', 'n.tesla@example.com', True, 'BLOG_EMAIL'),
('Site description', 'This is a demo site for Nikola.', True, 'BLOG_DESCRIPTION'),
(urlhandler, None, True, True),
('Questions about languages and locales', None, None, None),
(lhandler, None, True, True),
(tzhandler, None, True, True),
('Questions about comments', None, None, None),
(chandler, None, True, True),
]
print("Creating Nikola Site")
print("====================\n")
print("This is Nikola v{0}. We will now ask you a few easy questions about your new site.".format(nikola.__version__))
print("If you do not want to answer and want to go with the defaults instead, simply restart with the `-q` parameter.")
for query, default, toconf, destination in questions:
if target and destination == '!target':
# Skip the destination question if we know it already
pass
else:
if default is toconf is destination is None:
print('--- {0} ---'.format(query))
elif destination is True:
query(default, toconf)
else:
answer = ask(query, default)
try:
answer = answer.decode('utf-8')
except (AttributeError, UnicodeDecodeError):
pass
if toconf:
SAMPLE_CONF[destination] = answer
if destination == '!target':
while not answer:
print(' ERROR: you need to specify a target directory.\n')
answer = ask(query, default)
STORAGE['target'] = answer
print("\nThat's it, Nikola is now configured. Make sure to edit conf.py to your liking.")
print("If you are looking for themes and addons, check out https://themes.getnikola.com/ and https://plugins.getnikola.com/.")
print("Have fun!")
return STORAGE
def _execute(self, options={}, args=None):
"""Create a new site."""
try:
target = args[0]
except IndexError:
target = None
if not options.get('quiet'):
st = self.ask_questions(target=target)
try:
if not target:
target = st['target']
except KeyError:
pass
if not target:
print("Usage: nikola init [--demo] [--quiet] folder")
print("""
Options:
-q, --quiet Do not ask questions about config.
-d, --demo Create a site filled with example data.""")
return False
if not options.get('demo'):
self.create_empty_site(target)
LOGGER.info('Created empty site at {0}.'.format(target))
else:
self.copy_sample_site(target)
LOGGER.info("A new site with example data has been created at "
"{0}.".format(target))
LOGGER.info("See README.txt in that folder for more information.")
self.create_configuration(target)