1 | 'use strict'
|
2 |
|
3 | const
|
4 | helpers = require('./helpers'),
|
5 | path = require('path'),
|
6 | sh = require('shelljs'),
|
7 | compiler = global.compiler || require('riot-compiler'),
|
8 | constants = require('./const'),
|
9 | NO_FILE_FOUND = constants.NO_FILE_FOUND,
|
10 | PREPROCESSOR_NOT_REGISTERED = constants.PREPROCESSOR_NOT_REGISTERED
|
11 |
|
12 |
|
13 |
|
14 |
|
15 | class Task {
|
16 | constructor(opt) {
|
17 |
|
18 |
|
19 |
|
20 | if (this.called) return
|
21 | this.called = true
|
22 |
|
23 |
|
24 | opt.parsers = helpers.extend(
|
25 | compiler.parsers,
|
26 | opt.parsers || {}
|
27 | )
|
28 |
|
29 |
|
30 | this.error = opt.compiler ? this.validate(opt.compiler, opt.parsers) : null
|
31 |
|
32 |
|
33 |
|
34 | this.extRegex = new RegExp(`\\.${opt.ext || 'tag' }$`)
|
35 |
|
36 |
|
37 |
|
38 | if (!opt.to)
|
39 | opt.to = this.extRegex.test(opt.from) ? path.dirname(opt.from) : opt.from
|
40 |
|
41 |
|
42 |
|
43 | opt.from = path.resolve(opt.from)
|
44 | opt.to = path.resolve(opt.to)
|
45 |
|
46 |
|
47 | if (!sh.test('-e', opt.from)) this.error = NO_FILE_FOUND
|
48 |
|
49 |
|
50 | if (this.error) {
|
51 |
|
52 | if (opt.isCli)
|
53 | helpers.err(this.error)
|
54 | else return this.error
|
55 | }
|
56 |
|
57 |
|
58 |
|
59 |
|
60 |
|
61 |
|
62 |
|
63 | opt.flow = (this.extRegex.test(opt.from) ? 'f' : 'd') +
|
64 | (/\.(js|html|css)$/.test(opt.to) ? 'f' : 'd')
|
65 |
|
66 |
|
67 | if (!opt.compiler) opt.compiler = {}
|
68 |
|
69 |
|
70 | return this.run(opt)
|
71 |
|
72 | }
|
73 |
|
74 | |
75 |
|
76 |
|
77 |
|
78 |
|
79 |
|
80 |
|
81 | findParser(type, id, parsers) {
|
82 | var error
|
83 |
|
84 |
|
85 | if (!compiler.parsers[type][id] && !parsers[type][id])
|
86 | error = PREPROCESSOR_NOT_REGISTERED(type, id)
|
87 | else
|
88 | try {
|
89 | compiler.parsers._req(id, true)
|
90 | } catch (e) {
|
91 | error = e.toString()
|
92 | }
|
93 |
|
94 | return typeof error == 'string' ? error : null
|
95 | }
|
96 |
|
97 | |
98 |
|
99 |
|
100 |
|
101 |
|
102 |
|
103 |
|
104 | validate(opt, parsers) {
|
105 | var template = opt.template,
|
106 | type = opt.type,
|
107 | style = opt.style,
|
108 | error = null
|
109 |
|
110 | if (template)
|
111 | error = this.findParser('html', template, parsers)
|
112 | if (type && !error)
|
113 | error = this.findParser('js', type, parsers)
|
114 | if (style && !error)
|
115 | error = this.findParser('css', style, parsers)
|
116 |
|
117 | return error
|
118 | }
|
119 | }
|
120 |
|
121 | module.exports = Task
|