/
plugin_categories.py
384 lines (288 loc) · 10.9 KB
/
plugin_categories.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
# -*- 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 absolute_import
import sys
import os
import re
from yapsy.IPlugin import IPlugin
from doit.cmd_base import Command as DoitCommand
from .utils import LOGGER, first_line
__all__ = [
'Command',
'LateTask',
'PageCompiler',
'RestExtension',
'MarkdownExtension',
'Task',
'TaskMultiplier',
'TemplateSystem',
'SignalHandler',
'ConfigPlugin',
'PostScanner',
]
class BasePlugin(IPlugin):
"""Base plugin class."""
def set_site(self, site):
"""Sets site, which is a Nikola instance."""
self.site = site
self.inject_templates()
def inject_templates(self):
"""If this plugin contains a 'templates' folder,
then templates/mako or templates/jinja will be inserted very early in
the theme chain."""
try:
# Sorry, found no other way to get this
mod_path = sys.modules[self.__class__.__module__].__file__
mod_dir = os.path.dirname(mod_path)
tmpl_dir = os.path.join(
mod_dir, 'templates', self.site.template_system.name
)
if os.path.isdir(tmpl_dir):
# Inject tmpl_dir low in the theme chain
self.site.template_system.inject_directory(tmpl_dir)
except AttributeError:
# In some cases, __builtin__ becomes the module of a plugin.
# We couldn’t reproduce that, and really find the reason for this,
# so let’s just ignore it and be done with it.
pass
def inject_dependency(self, target, dependency):
"""Add 'dependency' to the target task's task_deps"""
self.site.injected_deps[target].append(dependency)
class PostScanner(BasePlugin):
"""The scan method of these plugins is called by Nikola.scan_posts."""
def scan(self):
"""Creates a list of posts from some source. Returns a list of Post objects."""
raise NotImplementedError()
class Command(BasePlugin, DoitCommand):
"""These plugins are exposed via the command line.
They implement the doit Command interface."""
name = "dummy_command"
doc_purpose = "A short explanation."
doc_usage = ""
doc_description = None # None value will completely omit line from doc
# see http://python-doit.sourceforge.net/cmd_run.html#parameters
cmd_options = ()
needs_config = True
def __init__(self, *args, **kwargs):
BasePlugin.__init__(self, *args, **kwargs)
DoitCommand.__init__(self)
def __call__(self, config=None, **kwargs):
self._doitargs = kwargs
DoitCommand.__init__(self, config, **kwargs)
return self
def execute(self, options=None, args=None):
"""Check if the command can run in the current environment,
fail if needed, or call _execute."""
options = options or {}
args = args or []
if self.needs_config and not self.site.configured:
LOGGER.error("This command needs to run inside an existing Nikola site.")
return False
return self._execute(options, args)
def _execute(self, options, args):
"""Do whatever this command does.
@param options (dict) with values from cmd_options
@param args (list) list of positional arguments
"""
raise NotImplementedError()
def help(self):
"""return help text"""
text = []
text.append("Purpose: %s" % self.doc_purpose)
text.append("Usage: nikola %s %s" % (self.name, self.doc_usage))
text.append('')
text.append("Options:")
for opt in self.cmdparser.options:
text.extend(opt.help_doc())
if self.doc_description is not None:
text.append("")
text.append("Description:")
text.append(self.doc_description)
return "\n".join(text)
DoitCommand.help = help
class BaseTask(BasePlugin):
"""Plugins of this type are task generators."""
name = "dummy_task"
# default tasks are executed by default.
# the others have to be specifie in the command line.
is_default = True
def gen_tasks(self):
"""Task generator."""
raise NotImplementedError()
def group_task(self):
"""dict for group task"""
return {
'basename': self.name,
'name': None,
'doc': first_line(self.__doc__),
}
class Task(BaseTask):
"""Plugins of this type are task generators."""
name = "dummy_task"
class LateTask(BaseTask):
"""Plugins of this type are executed after all plugins of type Task."""
name = "dummy_latetask"
class TemplateSystem(BasePlugin):
"""Plugins of this type wrap templating systems."""
name = "dummy_templates"
def set_directories(self, directories, cache_folder):
"""Sets the list of folders where templates are located and cache."""
raise NotImplementedError()
def template_deps(self, template_name):
"""Returns filenames which are dependencies for a template."""
raise NotImplementedError()
def render_template(self, template_name, output_name, context):
"""Renders template to a file using context.
This must save the data to output_name *and* return it
so that the caller may do additional processing.
"""
raise NotImplementedError()
def render_template_to_string(self, template, context):
"""Renders template to a string using context. """
raise NotImplementedError()
def inject_directory(self, directory):
"""Injects the directory with the lowest priority in the
template search mechanism."""
raise NotImplementedError()
class TaskMultiplier(BasePlugin):
"""Plugins that take a task and return *more* tasks."""
name = "dummy multiplier"
def process(self, task):
"""Examine task and create more tasks.
Returns extra tasks only."""
return []
class PageCompiler(BasePlugin):
"""Plugins that compile text files into HTML."""
name = "dummy_compiler"
friendly_name = ''
demote_headers = False
supports_onefile = True
default_metadata = {
'title': '',
'slug': '',
'date': '',
'tags': '',
'category': '',
'link': '',
'description': '',
'type': 'text',
}
config_dependencies = []
def register_extra_dependencies(self, post):
"""Add additional dependencies to the post object.
Current main use is the ReST page compiler, which puts extra
dependencies into a .deb file."""
pass
def compile_html(self, source, dest, is_two_file=False):
"""Compile the source, save it on dest."""
raise NotImplementedError()
def create_post(self, path, content=None, onefile=False, is_page=False, **kw):
"""Create post file with optional metadata."""
raise NotImplementedError()
def extension(self):
"""The preferred extension for the output of this compiler."""
return ".html"
def read_metadata(self, post, file_metadata_regexp=None, unslugify_titles=False, lang=None):
"""
Read the metadata from a post, and return a metadata dict
"""
return {}
def split_metadata(self, data):
"""Split data from metadata in the raw post content.
This splits in the first empty line that is NOT at the beginning
of the document."""
split_result = re.split('(\n\n|\r\n\r\n)', data.lstrip(), maxsplit=1)
if len(split_result) == 1:
return '', split_result[0]
# ['metadata', '\n\n', 'post content']
return split_result[0], split_result[-1]
class RestExtension(BasePlugin):
name = "dummy_rest_extension"
class MarkdownExtension(BasePlugin):
name = "dummy_markdown_extension"
class SignalHandler(BasePlugin):
name = "dummy_signal_handler"
class ConfigPlugin(BasePlugin):
"""A plugin that can edit config (or modify the site) on-the-fly."""
name = "dummy_config_plugin"
class Importer(Command):
"""Basic structure for importing data into Nikola.
The flow is:
read_data
preprocess_data
parse_data
generate_base_site
populate_context
create_config
filter_data
process_data
process_data can branch into:
import_story (may use import_file and save_post)
import_post (may use import_file and save_post)
import_attachment (may use import_file)
Finally:
write_urlmap
"""
name = "dummy_importer"
def _execute(self, options={}, args=[]):
"""Import the data into Nikola."""
raise NotImplementedError()
def generate_base_site(self, path):
"""Create the base site."""
raise NotImplementedError()
def populate_context(self):
"""Use data to fill context for configuration."""
raise NotImplementedError()
def create_config(self):
"""Use the context to create configuration."""
raise NotImplementedError()
def read_data(self, source):
"""Fetch data into self.data"""
raise NotImplementedError()
def preprocess_data(self):
"""Modify data if needed."""
pass
def parse_data(self):
"""Convert self.data into self.items"""
raise NotImplementedError()
def filter_data(self):
"""Remove data that's not to be imported."""
pass
def process_data(self):
"""Go through self.items and save them."""
def import_story(self):
"""Create a story."""
raise NotImplementedError()
def import_post(self):
"""Create a post."""
raise NotImplementedError()
def import_attachment(self):
"""Create an attachment."""
raise NotImplementedError()
def import_file(self):
"""Import a file."""
raise NotImplementedError()
def save_post(self):
"""Save a post to disk."""
raise NotImplementedError()