-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathscript.html-beautify.js
More file actions
73 lines (57 loc) · 2.27 KB
/
script.html-beautify.js
File metadata and controls
73 lines (57 loc) · 2.27 KB
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
const fs = require('node:fs');
const path = require('node:path');
const weblog = require('webpack-log');
const frontMatter = require('front-matter');
const beautify = require('js-beautify');
const ENV = require('./app.env');
const UTILS = require('./webpack.utils');
const logger = weblog({ name: 'html-beautify' });
const beautifyfIgnore = UTILS.readIgnoreFile('./.jsbeautifyignore');
const statMessages = { fixed: 0, skipped: 0, ignored: 0 };
const patterns = [...UTILS.processArgs._];
const config = UTILS.readJsonFile('./.jsbeautifyrc');
const stripWhitespaces = (string) => {
let result = string;
if (result.charCodeAt(0) === 0xfeff) {
result = result.slice(1);
}
result = result
.replace(/\r\n/g, '\n')
.replace(/\t/g, ' ')
.replace(/[ \t]+\n/g, '\n');
return result;
};
const beautifyHtml = (html) => {
let result = beautify.html(html, config);
result = stripWhitespaces(result);
result = result.replace(/{{\s*/g, '{{ ').replace(/\s*}}/g, ' }}');
result = result.replace(/{%(-?)\s*/g, '{%$1 ').replace(/\s*(-?)%}/g, ' $1%}');
result = result.replace(/{#\s*/g, '{# ').replace(/\s*#}/g, ' #}');
return result;
};
const files = UTILS.globArraySync(patterns.length > 0 ? patterns : [`${ENV.SOURCE_PATH}/**/*.html`], {
ignore: [`${ENV.OUTPUT_PATH}/**/*.html`, `${ENV.SOURCE_PATH}/partials/macros/**/*.html`],
nodir: true,
});
logger.info(`${files.length} files\n`);
files.forEach((resourcePath) => {
const relativePath = UTILS.slash(path.relative(__dirname, resourcePath));
if (beautifyfIgnore.ignores(relativePath)) {
statMessages.ignored += 1;
logger.info(`ignored ${relativePath}`);
return;
}
const html = fs.readFileSync(resourcePath).toString('utf-8');
const templateData = frontMatter(html);
const output = (templateData.frontmatter ? ['---', templateData.frontmatter, '---', ''].join('\n') : '') + beautifyHtml(templateData.body.normalize('NFC'));
if (html !== output) {
fs.writeFileSync(resourcePath, output);
statMessages.fixed += 1;
logger.info(`fixed ${relativePath}`);
} else {
statMessages.skipped += 1;
logger.info(`skipped ${relativePath}`);
}
});
console.log('');
logger.info('stats:', statMessages);