1+ /* @flow */
2+ import path from 'path' ;
3+
4+ import requireUncached from 'require-uncached' ;
5+
6+ import { createLogger } from './util/logger' ;
7+ import { UsageError } from './errors' ;
8+
9+ const log = createLogger ( __filename ) ;
10+
11+ type ApplyConfigToArgvParams = { |
12+ argv : Object ,
13+ configObject : Object ,
14+ defaultValues : Object ,
15+ | } ;
16+
17+ export function applyConfigToArgv ( {
18+ argv,
19+ configObject,
20+ defaultValues = { } ,
21+ } : ApplyConfigToArgvParams ) : Object {
22+ const newArgv = { ...argv } ;
23+ for ( const option in configObject ) {
24+ // we assume the value was set on the CLI if the default value is
25+ // not the same as that on the argv object as there is a very rare chance
26+ // this happening
27+ const wasValueSetOnCLI = typeof ( argv [ option ] ) !== 'undefined' &&
28+ ( argv [ option ] !== defaultValues [ option ] ) ;
29+ if ( wasValueSetOnCLI ) {
30+ log . debug ( `Favoring CLI: ${ option } =${ argv [ option ] } over ` +
31+ `configuration: ${ option } =${ configObject [ option ] } ` ) ;
32+ continue ;
33+ }
34+ if ( ! argv . hasOwnProperty ( option ) ) {
35+ log . debug ( `Ignoring configuration: ${ option } =${ configObject [ option ] } ` +
36+ 'because this is an unknown option' ) ;
37+ continue ;
38+ }
39+ newArgv [ option ] = configObject [ option ] ;
40+ }
41+ return newArgv ;
42+ }
43+
44+ export function loadJSConfigFile ( filePath : string ) : Object {
45+ const resolvedFilePath = path . resolve ( filePath ) ;
46+ log . debug (
47+ `Loading JS config file: "${ filePath } " ` +
48+ `(resolved to "${ resolvedFilePath } ")` ) ;
49+ let configObject ;
50+ try {
51+ configObject = requireUncached ( resolvedFilePath ) ;
52+ } catch ( error ) {
53+ log . debug ( 'Handling error:' , error ) ;
54+ throw new UsageError (
55+ `Cannot read config file: ${ resolvedFilePath } \n` +
56+ `Error: ${ error . message } ` ) ;
57+ }
58+ if ( Object . keys ( configObject ) . length === 0 ) {
59+ log . debug ( `Config file ${ resolvedFilePath } did not define any options. ` +
60+ 'Did you set module.exports = {...}?' ) ;
61+ }
62+ return configObject ;
63+ }
0 commit comments