hyper/config.js

85 lines
2 KiB
JavaScript
Raw Normal View History

const { dialog } = require('electron');
2016-07-07 06:46:58 -08:00
const { homedir } = require('os');
const { resolve } = require('path');
const { readFileSync, writeFileSync } = require('fs');
const gaze = require('gaze');
const vm = require('vm');
const path = resolve(homedir(), '.hyperterm.js');
const watchers = [];
2016-07-07 06:46:58 -08:00
let cfg = {};
function watch () {
gaze(path, function (err) {
if (err) throw err;
this.on('changed', () => {
try {
if (exec(readFileSync(path, 'utf8'))) {
watchers.forEach((fn) => fn());
}
} catch (err) {
dialog.showMessageBox({
message: `An error occurred loading your configuration (${path}): ${err.message}`,
buttons: ['Ok']
});
}
});
2016-07-07 06:46:58 -08:00
});
}
let _str; // last script
2016-07-07 06:46:58 -08:00
function exec (str) {
if (str === _str) return false;
_str = str;
2016-07-07 06:46:58 -08:00
const script = new vm.Script(str);
2016-07-07 06:50:18 -08:00
const module = {};
script.runInNewContext({ module });
if (!module.exports) {
throw new Error('Error reading configuration: `module.exports` not set');
}
2016-07-07 12:49:10 -08:00
const _cfg = module.exports;
if (!_cfg.config) {
2016-07-07 06:49:11 -08:00
throw new Error('Error reading configuration: `config` key is missing');
}
2016-07-07 12:49:10 -08:00
_cfg.plugins = _cfg.plugins || [];
_cfg.localPlugins = _cfg.localPlugins || [];
cfg = _cfg;
return true;
2016-07-07 06:46:58 -08:00
}
exports.subscribe = function (fn) {
watchers.push(fn);
return () => {
watchers.splice(watchers.indexOf(fn), 1);
};
};
2016-07-07 06:46:58 -08:00
exports.init = function () {
try {
exec(readFileSync(path, 'utf8'));
} catch (err) {
console.log('read error', path, err.message);
const defaultConfig = readFileSync(resolve(__dirname, 'config-default.js'));
try {
console.log('attempting to write default config to', path);
exec(defaultConfig);
2016-07-07 06:46:58 -08:00
writeFileSync(path, defaultConfig);
} catch (err) {
throw new Error(`Failed to write config to ${path}`);
}
}
watch();
};
2016-07-07 12:49:10 -08:00
exports.getConfig = function () {
return cfg.config;
};
exports.getPlugins = function () {
return {
plugins: cfg.plugins,
localPlugins: cfg.localPlugins
};
2016-07-07 06:46:58 -08:00
};