1
1
#!/usr/bin/env node
2
2
3
3
var posthtml = require ( 'posthtml' ) ;
4
+ var globby = require ( 'globby' ) ;
5
+ var path = require ( 'path' ) ;
6
+ const pathExists = require ( 'path-exists' ) ;
4
7
var fs = require ( 'fs' ) ;
5
8
var argv = require ( 'yargs' )
6
- . usage ( 'Usage: $0 --output|-o output.html --input|-i input.html [--config|-c config.(js|json)]' )
9
+ . usage ( 'Usage: $0 --output|-o output.html/outputFolder --input|-i input.html/inputFolder [--config|-c config.(js|json)] [--replace|-r ]' )
7
10
. example ( 'posthtml -o output.html -i input.html' , 'Default example' )
8
- . demand ( [ 'o' , 'i' ] )
9
11
. alias ( 'i' , 'input' )
10
12
. alias ( 'o' , 'output' )
13
+ . alias ( 'r' , 'replace' )
14
+ . demand ( [ 'i' ] )
15
+ . array ( 'input' )
11
16
. pkgConf ( 'posthtml' )
12
17
. config ( 'c' )
13
18
. alias ( 'c' , 'config' )
@@ -17,14 +22,57 @@ var argv = require('yargs')
17
22
. alias ( 'v' , 'version' )
18
23
. help ( 'h' )
19
24
. alias ( 'h' , 'help' )
25
+ . check ( function ( argv ) {
26
+ if ( argv . output && argv . replace ) {
27
+ throw new Error ( 'Both `output file` and `replace` provided: please use either --output or --replace option.' ) ;
28
+ }
29
+ if ( ! argv . output && ! argv . replace ) {
30
+ throw new Error ( 'Both `output file` and `replace` missing: please use either --output or --replace option.' ) ;
31
+ }
32
+ return true ;
33
+ } )
20
34
. argv ;
21
35
22
- // get htmls
23
- var html = fs . readFileSync ( argv . input , 'utf8' ) ;
36
+ function processing ( file , output ) {
37
+ // get htmls
38
+ var html = fs . readFileSync ( file , 'utf8' ) ;
39
+
40
+ // processing
41
+ posthtml ( require ( 'posthtml-load-plugins' ) ( argv . config ) )
42
+ . process ( html )
43
+ . then ( function ( result ) {
44
+ fs . writeFileSync ( output , result . html ) ;
45
+ } ) ;
46
+ }
47
+
48
+ function isFile ( outputPath ) {
49
+ return Boolean ( path . extname ( outputPath ) ) ;
50
+ }
51
+
52
+ function getOutput ( file ) {
53
+ if ( argv . output === undefined ) {
54
+ return file ;
55
+ }
56
+ return argv . output + path . basename ( file ) ;
57
+ }
58
+
59
+ function createFolder ( outputPath ) {
60
+ if ( isFile ( outputPath ) === true ) {
61
+ outputPath = path . dirname ( outputPath ) ;
62
+ }
63
+
64
+ if ( pathExists . sync ( outputPath ) === false ) {
65
+ fs . mkdirSync ( outputPath ) ;
66
+ }
67
+ }
68
+
69
+ globby ( argv . input ) . then ( function ( files ) {
70
+ if ( argv . output !== undefined ) {
71
+ createFolder ( argv . output ) ;
72
+ }
24
73
25
- // processing
26
- posthtml ( require ( 'posthtml-load-plugins' ) ( argv . config ) )
27
- . process ( html )
28
- . then ( function ( result ) {
29
- fs . writeFileSync ( argv . output , result . html ) ;
74
+ files . forEach ( function ( file ) {
75
+ var output = isFile ( argv . output ) ? argv . output : getOutput ( file ) ;
76
+ processing ( file , output ) ;
30
77
} ) ;
78
+ } ) ;
0 commit comments