/
__main__.py
429 lines (359 loc) · 14.3 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
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
# -*- coding: utf-8 -*-
# Copyright © 2012-2017 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.
"""The main function of Nikola."""
from __future__ import print_function, unicode_literals
import os
import shutil
import sys
import traceback
from collections import defaultdict
from blinker import signal
from doit.cmd_auto import Auto as DoitAuto
from doit.cmd_base import TaskLoader
from doit.cmd_clean import Clean as DoitClean
from doit.cmd_completion import TabCompletion
from doit.cmd_help import Help as DoitHelp
from doit.cmd_run import Run as DoitRun
from doit.doit_cmd import DoitMain
from doit.loader import generate_tasks
from doit.reporter import ExecutedOnlyReporter
from logbook import NullHandler
from . import __version__
from .nikola import Nikola
from .plugin_categories import Command
from .utils import (LOGGER, STDERR_HANDLER, STRICT_HANDLER,
ColorfulStderrHandler, get_root_dir, req_missing,
sys_decode, sys_encode)
try:
import readline # NOQA
except ImportError:
pass # This is only so raw_input/input does nicer things if it's available
if sys.version_info[0] == 3:
import importlib.machinery
else:
import imp
config = {}
# DO NOT USE unless you know what you are doing!
_RETURN_DOITNIKOLA = False
def main(args=None):
"""Run Nikola."""
colorful = False
if sys.stderr.isatty() and os.name != 'nt' and os.getenv('NIKOLA_MONO') is None and os.getenv('TERM') != 'dumb':
colorful = True
ColorfulStderrHandler._colorful = colorful
if args is None:
args = sys.argv[1:]
oargs = args
args = [sys_decode(arg) for arg in args]
conf_filename = 'conf.py'
conf_filename_bytes = b'conf.py'
conf_filename_changed = False
for index, arg in enumerate(args):
if arg[:7] == '--conf=':
del args[index]
del oargs[index]
conf_filename = arg[7:]
conf_filename_bytes = sys_encode(arg[7:])
conf_filename_changed = True
break
quiet = False
strict = False
if len(args) > 0 and args[0] == 'build' and '--strict' in args:
LOGGER.notice('Running in strict mode')
STRICT_HANDLER.push_application()
strict = True
if len(args) > 0 and args[0] == 'build' and '-q' in args or '--quiet' in args:
NullHandler().push_application()
quiet = True
if not quiet and not strict:
NullHandler().push_application()
STDERR_HANDLER[0].push_application()
global config
original_cwd = os.getcwd()
# Those commands do not require a `conf.py`. (Issue #1132)
# Moreover, actually having one somewhere in the tree can be bad, putting
# the output of that command (the new site) in an unknown directory that is
# not the current working directory. (does not apply to `version`)
argname = args[0] if len(args) > 0 else None
if argname and argname not in ['init', 'version'] and not argname.startswith('import_'):
root = get_root_dir()
if root:
os.chdir(root)
# Help and imports don't require config, but can use one if it exists
needs_config_file = (argname != 'help') and not argname.startswith('import_')
else:
needs_config_file = False
sys.path.append('')
try:
if sys.version_info[0] == 3:
loader = importlib.machinery.SourceFileLoader("conf", conf_filename)
conf = loader.load_module()
else:
conf = imp.load_source("conf", conf_filename_bytes)
config = conf.__dict__
except Exception:
if os.path.exists(conf_filename):
msg = traceback.format_exc(0)
LOGGER.error('"{0}" cannot be parsed.\n{1}'.format(conf_filename, msg))
return 1
elif needs_config_file and conf_filename_changed:
LOGGER.error('Cannot find configuration file "{0}".'.format(conf_filename))
return 1
config = {}
if conf_filename_changed:
LOGGER.info("Using config file '{0}'".format(conf_filename))
invariant = False
if len(args) > 0 and args[0] == 'build' and '--invariant' in args:
try:
import freezegun
freeze = freezegun.freeze_time("2038-01-01")
freeze.start()
invariant = True
except ImportError:
req_missing(['freezegun'], 'perform invariant builds')
if config:
if os.path.isdir('plugins') and not os.path.exists('plugins/__init__.py'):
with open('plugins/__init__.py', 'w') as fh:
fh.write('# Plugin modules go here.')
config['__colorful__'] = colorful
config['__invariant__'] = invariant
config['__quiet__'] = quiet
config['__configuration_filename__'] = conf_filename
config['__cwd__'] = original_cwd
site = Nikola(**config)
DN = DoitNikola(site, quiet)
if _RETURN_DOITNIKOLA:
return DN
_ = DN.run(oargs)
if site.invariant:
freeze.stop()
return _
class Help(DoitHelp):
"""Show Nikola usage."""
@staticmethod
def print_usage(cmds):
"""Print nikola "usage" (basic help) instructions."""
# Remove 'run'. Nikola uses 'build', though we support 'run' for
# people used to it (eg. doit users).
# WARNING: 'run' is the vanilla doit command, without support for
# --strict, --invariant and --quiet.
del cmds['run']
print("Nikola is a tool to create static websites and blogs. For full documentation and more information, please visit https://getnikola.com/\n\n")
print("Available commands:")
for cmd_name in sorted(cmds.keys()):
cmd = cmds[cmd_name]
print(" nikola {:20s} {}".format(cmd_name, cmd.doc_purpose))
print("")
print(" nikola help show help / reference")
print(" nikola help <command> show command usage")
print(" nikola help <task-name> show task usage")
class Build(DoitRun):
"""Expose "run" command as "build" for backwards compatibility."""
def __init__(self, *args, **kw):
"""Initialize Build."""
opts = list(self.cmd_options)
opts.append(
{
'name': 'strict',
'long': 'strict',
'default': False,
'type': bool,
'help': "Fail on things that would normally be warnings.",
}
)
opts.append(
{
'name': 'invariant',
'long': 'invariant',
'default': False,
'type': bool,
'help': "Generate invariant output (for testing only!).",
}
)
opts.append(
{
'name': 'quiet',
'long': 'quiet',
'short': 'q',
'default': False,
'type': bool,
'help': "Run quietly.",
}
)
self.cmd_options = tuple(opts)
super(Build, self).__init__(*args, **kw)
class Clean(DoitClean):
"""Clean site, including the cache directory."""
def clean_tasks(self, tasks, dryrun):
"""Clean tasks."""
if not dryrun and config:
cache_folder = config.get('CACHE_FOLDER', 'cache')
if os.path.exists(cache_folder):
shutil.rmtree(cache_folder)
return super(Clean, self).clean_tasks(tasks, dryrun)
# Nikola has its own "auto" commands that uses livereload.
# Expose original doit "auto" command as "doit_auto".
DoitAuto.name = 'doit_auto'
class NikolaTaskLoader(TaskLoader):
"""Nikola-specific task loader."""
def __init__(self, nikola, quiet=False):
"""Initialize the loader."""
self.nikola = nikola
self.quiet = quiet
def load_tasks(self, cmd, opt_values, pos_args):
"""Load Nikola tasks."""
if self.quiet:
DOIT_CONFIG = {
'verbosity': 0,
'reporter': 'zero',
}
else:
DOIT_CONFIG = {
'reporter': ExecutedOnlyReporter,
'outfile': sys.stderr,
}
DOIT_CONFIG['default_tasks'] = ['render_site', 'post_render']
DOIT_CONFIG.update(self.nikola._doit_config)
try:
tasks = generate_tasks(
'render_site',
self.nikola.gen_tasks('render_site', "Task", 'Group of tasks to render the site.'))
latetasks = generate_tasks(
'post_render',
self.nikola.gen_tasks('post_render', "LateTask", 'Group of tasks to be executed after site is rendered.'))
signal('initialized').send(self.nikola)
except Exception:
LOGGER.error('Error loading tasks. An unhandled exception occurred.')
if self.nikola.debug:
raise
_print_exception()
sys.exit(3)
return tasks + latetasks, DOIT_CONFIG
class DoitNikola(DoitMain):
"""Nikola-specific implementation of DoitMain."""
# overwite help command
DOIT_CMDS = list(DoitMain.DOIT_CMDS) + [Help, Build, Clean, DoitAuto]
TASK_LOADER = NikolaTaskLoader
def __init__(self, nikola, quiet=False):
"""Initialzie DoitNikola."""
super(DoitNikola, self).__init__()
self.nikola = nikola
nikola.doit = self
self.task_loader = self.TASK_LOADER(nikola, quiet)
def get_cmds(self):
"""Get commands."""
# core doit commands
cmds = DoitMain.get_cmds(self)
# load nikola commands
for name, cmd in self.nikola._commands.items():
cmds[name] = cmd
return cmds
def run(self, cmd_args):
"""Run Nikola."""
args = self.process_args(cmd_args)
args = [sys_decode(arg) for arg in args]
if len(args) == 0:
cmd_args = ['help']
args = ['help']
if '--help' in args or '-h' in args:
new_cmd_args = ['help'] + cmd_args
new_args = ['help'] + args
cmd_args = []
args = []
for arg in new_cmd_args:
if arg not in ('--help', '-h'):
cmd_args.append(arg)
for arg in new_args:
if arg not in ('--help', '-h'):
args.append(arg)
if args[0] == 'help':
self.nikola.init_plugins(commands_only=True)
elif args[0] == 'plugin':
self.nikola.init_plugins(load_all=True)
else:
self.nikola.init_plugins()
sub_cmds = self.get_cmds()
if any(arg in ("--version", '-V') for arg in args):
cmd_args = ['version']
args = ['version']
if args[0] not in sub_cmds.keys():
LOGGER.error("Unknown command {0}".format(args[0]))
sugg = defaultdict(list)
sub_filtered = (i for i in sub_cmds.keys() if i != 'run')
for c in sub_filtered:
d = levenshtein(c, args[0])
sugg[d].append(c)
if sugg.keys():
best_sugg = sugg[min(sugg.keys())]
if len(best_sugg) == 1:
LOGGER.info('Did you mean "{}"?'.format(best_sugg[0]))
else:
LOGGER.info('Did you mean "{}" or "{}"?'.format('", "'.join(best_sugg[:-1]), best_sugg[-1]))
return 3
if not sub_cmds[args[0]] in (Help, TabCompletion) and not isinstance(sub_cmds[args[0]], Command):
if not self.nikola.configured:
LOGGER.error("This command needs to run inside an "
"existing Nikola site.")
return 3
try:
return super(DoitNikola, self).run(cmd_args)
except Exception:
LOGGER.error('An unhandled exception occurred.')
if self.nikola.debug:
raise
_print_exception()
return 1
@staticmethod
def print_version():
"""Print Nikola version."""
print("Nikola v" + __version__)
def levenshtein(s1, s2):
u"""Calculate the Levenshtein distance of two strings.
Implementation from Wikibooks:
https://en.wikibooks.org/w/index.php?title=Algorithm_Implementation/Strings/Levenshtein_distance&oldid=2974448#Python
Copyright © The Wikibooks contributors (CC BY-SA/fair use citation); edited to match coding style and add an exception.
"""
if len(s1) < len(s2):
return levenshtein(s2, s1)
# len(s1) >= len(s2)
if len(s2) == 0:
return len(s1)
previous_row = range(len(s2) + 1)
for i, c1 in enumerate(s1):
current_row = [i + 1]
for j, c2 in enumerate(s2):
# j+1 instead of j since previous_row and current_row are one character longer than s2
insertions = previous_row[j + 1] + 1
deletions = current_row[j] + 1
substitutions = previous_row[j] + (c1 != c2)
current_row.append(min(insertions, deletions, substitutions))
previous_row = current_row
return previous_row[-1]
def _print_exception():
"""Print an exception in a friendlier, shorter style."""
etype, evalue, _ = sys.exc_info()
LOGGER.error(''.join(traceback.format_exception(etype, evalue, None, limit=0, chain=False)).strip())
LOGGER.notice("To see more details, run Nikola in debug mode (set environment variable NIKOLA_DEBUG=1)")
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))