forked from posthtml/posthtml-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.js
More file actions
executable file
·91 lines (81 loc) · 2.23 KB
/
cli.js
File metadata and controls
executable file
·91 lines (81 loc) · 2.23 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#!/usr/bin/env node
var path = require('path')
var fs = require('fs')
var posthtml = require('posthtml')
var globby = require('globby')
var pathExists = require('path-exists')
var argv = require('yargs')
.usage('Usage: $0 [-o output-file/directory|-r] [-i input-file/directory] [--config|-c path/to/file/config]')
.example('posthtml -o output.html -i input.html', 'Default example')
.alias('i', 'input')
.array('input')
.demand(['i'])
.alias('o', 'output')
.alias('r', 'replace')
.alias('u', 'use')
.array('use')
.pkgConf('posthtml')
.config('c')
.alias('c', 'config')
.version(function () {
return require('./package.json').version
})
.alias('v', 'version')
.help('h')
.alias('h', 'help')
.check(function (argv) {
if (argv.output && argv.replace) {
throw new Error('Both `output file` and `replace` provided: please use either --output or --replace option.')
}
if (!argv.output && !argv.replace) {
throw new Error('Both `output file` and `replace` missing: please use either --output or --replace option.')
}
return true
})
.argv
function processing(file, output) {
// get htmls
var html = fs.readFileSync(file, 'utf8')
var ext = {}
// create config extends for posthtml-load-plugins
if (argv.use) {
argv.use.forEach(function (plugin) {
ext[plugin] = argv[plugin] || {}
})
}
// processing
posthtml(require('posthtml-load-plugins')(argv.config, ext))
.process(html)
.then(function (result) {
fs.writeFileSync(output, result.html)
})
}
function isFile(outputPath) {
if (outputPath === undefined) {
return false
}
return Boolean(path.extname(outputPath))
}
function getOutput(file) {
if (argv.output === undefined) {
return file
}
return argv.output + path.basename(file)
}
function createFolder(outputPath) {
if (isFile(outputPath) === true) {
outputPath = path.dirname(outputPath)
}
if (pathExists.sync(outputPath) === false) {
fs.mkdirSync(outputPath)
}
}
globby(argv.input).then(function (files) {
if (argv.output !== undefined) {
createFolder(argv.output)
}
files.forEach(function (file) {
var output = isFile(argv.output) ? argv.output : getOutput(file)
processing(file, output)
})
})