-
Notifications
You must be signed in to change notification settings - Fork 0
/
manageConfig.js
63 lines (60 loc) · 1.86 KB
/
manageConfig.js
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
const fs = require( 'fs' );
const { resolve } = require( 'path' );
const path = require( 'path' );
const configSample = fs.readFileSync(
path.join( __dirname, 'config.json.sample' )
);
const configSampleJSON = JSON.parse( configSample );
const configPath = path.join( __dirname, 'config.json' );
function confirmOptionsAvail( config, sample ) {
// Loop through each element of the sample and add it if it's missing
for ( element in sample ) {
if ( ! config.hasOwnProperty( element ) ) {
config[ element ] = sample[ element ];
}
// If we encounter a nested object, loop through each of its elements as well
if ( typeof sample[ element ] === 'object' ) {
config[ element ] = confirmOptionsAvail(
config[ element ],
sample[ element ]
);
}
}
return config;
}
function getUserConfig() {
return new Promise( ( resolve ) => {
// Generate a config file if one does not already exist
fs.writeFile( configPath, configSample, { flag: 'wx' }, ( error ) => {
if ( error ) {
// An error code of -17 means the file already exists, and we should confirm all values are present.
// All other errors should throw.
if ( error.errno === -17 ) {
// Confirm that all configSample elements are present, and add any that are missing
updatedConfig = confirmOptionsAvail(
JSON.parse( fs.readFileSync( configPath ) ),
configSampleJSON
);
// If any values needed updating, write the new config to the file
if (
updatedConfig !==
JSON.parse( fs.readFileSync( configPath ) )
) {
fs.writeFileSync(
configPath,
JSON.stringify( updatedConfig, null, 4 ),
{ flag: 'w' },
function ( err ) {
if ( err ) throw err;
}
);
}
resolve( JSON.parse( fs.readFileSync( configPath ) ) );
} else {
throw error;
}
}
} );
} );
}
module.exports = { getUserConfig };