-
Notifications
You must be signed in to change notification settings - Fork 39
/
mustache_lint.php
355 lines (305 loc) · 11.9 KB
/
mustache_lint.php
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
<?php
// This file is part of local_ci - https://github.com/moodlehq/moodle-local_ci
//
// local_ci is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// local_ci is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with local_ci. If not, see <http://www.gnu.org/licenses/>.
/**
* Lint mustache templates.
*
* @category ci
* @package local_ci
* @copyright 2016 Dan Poltawski
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once(__DIR__.'/../phplib/clilib.php');
// Let's use composer autoload, supporting both standalone and dependency modes.
// (borrowed from https://github.com/Behat/Behat/blob/a1f2809/bin/behat#L18-L30)
if (file_exists(__DIR__.'/../vendor/autoload.php')) {
// This must work when installed as direct dependency.
require_once(__DIR__.'/../vendor/autoload.php');
} else if (file_exists(__DIR__.'/../../../autoload.php')) {
// And also needs to work when installed as a dependency of others.
require_once(__DIR__.'/../../../autoload.php');
}
// Arrived here, something went wrong if we cannot locate the Mustache_Engine class.
if (!class_exists('Mustache_Engine')) {
// Something went wrong, this was not installed using composer,
// neither standalone installation or as a dependency.
fwrite(STDERR,
'You must set up the project dependencies, run the following commands:' . PHP_EOL.
'curl -s http://getcomposer.org/installer | php' . PHP_EOL.
'php composer.phar install' . PHP_EOL
);
exit(1);
}
list($options, $unrecognized) = cli_get_params(
['help' => false, 'filename' => '', 'validator' => '', 'basename' => ''],
['h' => 'help', 'f' => 'filename', 'v' => 'validator', 'b' => 'basename']);
if ($unrecognized) {
$unrecognized = implode("\n ", $unrecognized);
cli_error("Unrecognised options:\n{$unrecognized}\n Please use --help option.");
}
if ($options['help']) {
$help =
"Check a Moodle mustache template.
Options:
-h, --help Print out this help
-f, --filename Path to file
-v, --validator Validator URL (e.g. https://html5.validator.nu/ or http://localhost:8080/)
or path to validator JAR file (e.g. /path/to/vnu.jar)
-b, --basename Full path to the moodle base dir
";
echo $help;
exit(0);
}
if (empty($options['filename']) || empty($options['validator']) || empty($options['basename'])) {
cli_error('--filename or --validator or --basename missing. Use --help to get more info.');
}
$VALIDATOR = $options['validator'];
$FILENAME = $options['filename'];
$WARNINGS = false;
if (!file_exists($FILENAME)) {
echo "$FILENAME does not exist\n";
exit(1);
}
if (!load_core_component_from_moodle($options['basename'])) {
echo "Could not load core_component from dirroot: {$options['basename']}\n";
exit(1);
}
if (strpos($FILENAME, $CFG->dirroot) !== 0) {
echo "File path passed ($FILENAME) is not within basename ({$CFG->dirroot})\n";
exit(1);
}
// Ignore the .mustachelintignore file itself.
if (basename($FILENAME) === '.mustachelintignore') {
exit(0);
}
require_once(__DIR__.'/simple_core_component_mustache_loader.php');
require_once(__DIR__.'/js_helper.php');
$templatecontent = file_get_contents($FILENAME);
$theme = get_theme_from_template_path($FILENAME);
$jshelper = new js_helper($CFG->dirroot);
$mustache = new Mustache_Engine([
'pragmas' => [Mustache_Engine::PRAGMA_BLOCKS],
'helpers' => [ // Emulate some helpers for html validation purposes.
'str' => function($text) { return '((' . urlencode($text) . '))'; },
'pix' => function($text) { return "<img src='pix-placeholder.png' alt='$text'>"; },
'uniqid' => function() { return "would-be-a-uniqid"; },
'quote' => function($text, $helper) {
$content = $helper->render(trim($text));
$content = str_replace('"', '\\"', $content);
$content = preg_replace('([{}]{2,3})', '{{=<% %>=}}${0}<%={{ }}=%>', $content);
return '"' . $content . '"';
},
'js' => [$jshelper, 'add_js'],
],
'partials_loader' => new simple_core_component_mustache_loader($theme),
]);
$content = '';
try {
$example = extract_example_from_template($templatecontent);
$content = $mustache->render($templatecontent, $example);
} catch (exception $e) {
print_problem('ERROR', 'Mustache syntax exception: '.$e->getMessage());
exit(1);
}
$performhtmlvalidation = true;
$ignorefilepath = dirname($FILENAME) . '/.mustachelintignore';
if (file_exists($ignorefilepath)) {
foreach (file($ignorefilepath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $ignorepattern) {
if (strpos($ignorepattern, '#')) {
continue;
}
if (fnmatch(trim($ignorepattern), basename($FILENAME))) {
print_message('INFO', 'HTML validation skipped');
$performhtmlvalidation = false;
}
}
}
if (empty($content)) {
// This probably is related to a partial or so on. Best to avoid raising an error.
print_message('INFO', 'Template produced no content');
} else if ($performhtmlvalidation) {
check_html_validation($content);
}
$eslintproblems = $jshelper->run_eslint();
if ($eslintproblems === false) {
// Not an error situation for now, because we might run in situations
// where npm dependencies including eslint are not installed.
echo "INFO: ESLint did not run" . PHP_EOL;
print_message('INFO', 'ESLint did not run');
} else {
echo "INFO: ESLint did run" . PHP_EOL;
// When we have no example context, parse errors are common because
// there are missing variables in the js, thus we ignore them.
$ignoreparseerrors = empty($example) ? true : false;
print_eslint_problems($eslintproblems, $ignoreparseerrors);
}
if (!$WARNINGS) {
print_message('OK', 'Mustache rendered html succesfully');
exit(0);
} else {
exit(1);
}
/**
* Extracts the example context data from a template,
* mostly copies the approach from the js in tool_templatelibrary.
*
* @param string $content the raw template as string.
* @return mixed json_decoded data or false if no example found.
* @throws exception if json fails to parse
*/
function extract_example_from_template($content) {
$docs = '';
preg_match_all('/{{!([\s\S]*?)}}/', $content, $sections);
foreach ($sections[0] as $section) {
// Do a bit of similar stuff as template lib to strip {{! and }}.
$section = trim($section);
$pos = strpos($section, '@template');
if ($pos !== false) {
$docs = substr($section, $pos, -2);
break;
}
}
if (empty($docs)) {
print_problem('WARNING', 'Example context missing (@template section not found.)');
return [];
}
if (!preg_match('/Example context \(json\):([\s\S]*)/', $docs, $matches)) {
print_problem('WARNING', 'Example context missing.');
return [];
}
$json = trim($matches[1]);
$exampledata = json_decode($matches[1]);
if ($exampledata !== null) {
return $exampledata;
}
if (function_exists('json_last_error_msg')) {
$lasterror = json_last_error_msg();
} else {
// Fall back to numeric error for older PHP version.
$lasterror = json_last_error();
}
throw new Exception("Example context JSON is unparsable, fails with: $lasterror");
}
function print_problem($severity, $message) {
global $WARNINGS;
$WARNINGS = true;
print_message($severity, $message);
}
function print_message($severity, $mesage) {
global $FILENAME;
echo "$FILENAME - $severity: $mesage\n";
}
/**
* Wrap the template content in a html5 wrapper and validate it
*/
function check_html_validation($content) {
if (strpos($content, '<head>') === false) {
// Primative detection if we have full html body, if not, wrap it.
// (This isn't bulletproof, obviously).
$wrappedcontent = "<!DOCTYPE html><html lang=\"en\"><head><title>Validate</title></head><body>\n{$content}\n</body></html>";
} else {
$wrappedcontent = $content;
}
$response = validate_html($wrappedcontent);
if (!$response || !isset($response->messages)) {
print_problem('WARNING', 'Problem calling HTML validator - please report bug to integration team.');
return;
}
if (empty($response->messages)) {
// All good!
return;
}
foreach ($response->messages as $problem) {
//TODO: Sure would be nice if we could 'guess' a more accurate line number here..
$context = str_replace("\n", '', $problem->extract);
$message = "HTML Validation {$problem->type}, line {$problem->lastLine}: {$problem->message} ({$context})";
if ($problem->type == 'info') {
print_message('INFO', $message);
} else {
print_problem('WARNING', $message);
}
}
}
/**
* Print out problems from eslint.
* @param array $problems from eslint
* @param bool $ignoreparseerrors if true, we don't print parse errors
*/
function print_eslint_problems($problems, $ignoreparseerrors) {
foreach ($problems as $problem) {
// Remove the leading indentation..
$problem->source = trim($problem->source);
if ($ignoreparseerrors && preg_match('/Parsing error:/', $problem->message)) {
// We do this when no example context, so likely a false positive.
continue;
}
if ($problem->severity == 2) {
$severity = 'error';
} else {
$severity = 'warning';
}
$message = "ESLint {$severity} [{$problem->ruleId}]: {$problem->message} ( {$problem->source} ), Line: {$problem->line} Column: {$problem->column}";
print_problem('WARNING', $message);
}
}
/**
* Call the html validator with example content
* @return mixed false if a problem occured or the response from validator
*/
function validate_html($content) {
global $VALIDATOR;
if (strpos($VALIDATOR, 'http') !== 0) {
$file = tempnam(sys_get_temp_dir(), 'mustache_lint');
if ($file === false) {
return false;
}
file_put_contents($file, $content);
// The "2>&1" part redirects stderr to stdout because the JSON is sent to stderr and PHP does not capture that.
$output = shell_exec(sprintf('java -jar %s --format json --exit-zero-always %s 2>&1', $VALIDATOR, $file));
unlink($file);
if ($output === null) {
return false;
}
return json_decode($output);
}
$ch = curl_init("$VALIDATOR?out=json");
curl_setopt($ch, CURLOPT_USERAGENT, 'moodle/local_ci validator 0.1');
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-type: text/html; charset=utf-8']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] !== 200) {
return false; // Can't run html validator right now..
}
return json_decode($response);
}
/**
* If the template path passed is part of a theme, returns the theme name.
*
* @param string $templatepath The path to the template.
* @return string|null theme name or null if template not part of theme.
*/
function get_theme_from_template_path($templatepath) {
global $CFG;
$regexp = '#'.preg_quote($CFG->dirroot, '#').'/theme/([^/]+)/.*#';
if (preg_match($regexp, $templatepath, $matches)) {
return $matches[1];
}
return null;
}