Merge pull request #2311 from resin-io/config-file

feat(gui): Add ability to read settings from a config file
Close #1356
This commit is contained in:
Jonas Hermsmeier 2018-05-09 17:00:36 +02:00 committed by GitHub
commit 262d06f035
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -17,6 +17,10 @@
'use strict'
const Bluebird = require('bluebird')
const _ = require('lodash')
const fs = require('fs')
const path = require('path')
const os = require('os')
/**
* @summary Local storage settings key
@ -25,6 +29,43 @@ const Bluebird = require('bluebird')
*/
const LOCAL_STORAGE_SETTINGS_KEY = 'etcher-settings'
/**
* @summary Local settings filename
* @constant
* @type {String}
*/
const RCFILE = '.etcher.json'
/**
* @summary Read a local .etcherrc file
* @function
* @public
*
* @param {String} filename - file path
* @fulfil {Object} - settings
* @returns {Promise}
*
* @example
* readConfigFile('.etcherrc').then((settings) => {
* console.log(settings)
* })
*/
const readConfigFile = (filename) => {
return new Bluebird((resolve, reject) => {
fs.readFile(filename, (error, buffer) => {
if (error) {
if (error.code === 'ENOENT') {
resolve({})
} else {
reject(error)
}
} else {
resolve(JSON.parse(buffer.toString()))
}
})
})
}
/**
* @summary Read all local settings
* @function
@ -39,9 +80,22 @@ const LOCAL_STORAGE_SETTINGS_KEY = 'etcher-settings'
* });
*/
exports.readAll = () => {
const homeConfigPath = process.platform === 'win32'
? path.join(os.userInfo().homedir, RCFILE)
: path.join(os.userInfo().homedir, '.config', 'etcher', 'config.json')
const workdirConfigPath = path.join(process.cwd(), RCFILE)
const settings = {}
return Bluebird.try(() => {
return JSON.parse(window.localStorage.getItem(LOCAL_STORAGE_SETTINGS_KEY)) || {}
})
_.merge(settings, JSON.parse(window.localStorage.getItem(LOCAL_STORAGE_SETTINGS_KEY)))
}).return(readConfigFile(homeConfigPath))
.then((homeConfig) => {
_.merge(settings, homeConfig)
})
.return(readConfigFile(workdirConfigPath))
.then((workdirConfig) => {
_.merge(settings, workdirConfig)
})
.return(settings)
}
/**