1- #!/usr/bin/env node
2-
3- import meow from 'meow' ;
1+ import { promises as fs } from 'fs' ;
42import path from 'path' ;
53import { renderToFolder } from '.' ;
64
7- async function main ( ) {
8- const cli = meow (
9- `
5+ /** Trims the leading and trailing whitespace from the help text. */
6+ function trimUsageString ( string : string ) : string {
7+ // Remove newlines from beginning and end
8+ const usage = string . replace ( / ^ ( \s * \n ) * | ( \s * \n ) * $ / g, '' ) ;
9+ // Remove leading indentation
10+ const indentationLength = usage . match ( / ^ \s * / ) [ 0 ] . length ;
11+ return usage . replace ( new RegExp ( `^ {${ indentationLength } }` , 'gm' ) , '' ) ;
12+ }
13+
14+ function showUsage ( ) {
15+ const usageString = trimUsageString ( `
1016 Usage
1117 $ template-file <dataFile> <sourceGlob> <destination>
1218
1319 Arguments
14- data Data file in JSON; used to replace variables in source files
20+ dataFile Data file in JSON; used to replace variables in source files
1521 sourceGlob Files to process; see [glob](https://npmjs.com/glob) for syntax
1622 destination Destination directory where processed files go
1723
@@ -21,15 +27,39 @@ async function main() {
2127
2228 Compile all .abc files in src/ to build/
2329 $ template-file stuff.json 'src/**/*.abc' build/
24- `
25- // { importMeta: import.meta }
30+ ` ) ;
31+
32+ console . log ( usageString ) ;
33+ }
34+
35+ async function getVersion ( ) : Promise < string > {
36+ const packageJson = await fs
37+ . readFile ( path . resolve ( __dirname , '../package.json' ) , 'utf-8' )
38+ . then ( JSON . parse ) ;
39+
40+ return packageJson . version ;
41+ }
42+
43+ async function main ( ) {
44+ const args = process . argv . slice ( 2 ) ;
45+
46+ const hasHelpArg = args . some ( arg => [ '-h' , '--help' , 'help' ] . includes ( arg ) ) ;
47+ const hasVersionArg = args . some ( arg =>
48+ [ '-v' , '--version' , 'version' ] . includes ( arg )
2649 ) ;
50+ const hasCorrectNumberOfArgs = args . length === 3 ;
51+
52+ if ( hasVersionArg ) {
53+ console . log ( await getVersion ( ) ) ;
54+ return ;
55+ }
2756
28- if ( cli . input . length !== 3 ) {
29- cli . showHelp ( 2 ) ;
57+ if ( hasHelpArg || ! hasCorrectNumberOfArgs ) {
58+ showUsage ( ) ;
59+ process . exit ( hasHelpArg ? 0 : 1 ) ;
3060 }
3161
32- const [ dataFile , sourceGlob , destination ] = cli . input ;
62+ const [ dataFile , sourceGlob , destination ] = args ;
3363 const data = await import ( path . resolve ( dataFile ) ) ;
3464
3565 renderToFolder ( sourceGlob , destination , data ) ;
0 commit comments