const {moveSync, copySync, existsSync, writeFileSync, readFileSync, lstatSync} = require('fs-extra');
const {sync: mkdirpSync} = require('mkdirp');
const {defaultCfg, cfgPath, legacyCfgPath, plugs, defaultPlatformKeyPath} = require('./paths');
const {_init, _extractDefault} = require('./init');
const notify = require('../notify');
let defaultConfig;
const _write = function(path, data) {
const crlfify = function(str) {
return str.replace(/\r?\n/g, '\r\n');
};
const format = process.platform === 'win32' ? crlfify(data.toString()) : data;
writeFileSync(path, format, 'utf8');
};
const saveAsBackup = src => {
let attempt = 1;
while (attempt < 100) {
try {
const backupPath = src + '.backup' + (attempt === 1 ? '' : attempt);
moveSync(src, backupPath);
return backupPath;
} catch (e) {
if (e.code === 'EEXIST') {
attempt++;
} else {
throw e;
}
}
}
throw new Error('Failed to create backup for config file. Too many backups');
};
const migrateHyper2Config = () => {
if (cfgPath === legacyCfgPath) {
return;
}
if (!existsSync(legacyCfgPath)) {
return;
}
const existsNew = existsSync(cfgPath);
if (lstatSync(legacyCfgPath).isSymbolicLink() || (existsNew && lstatSync(cfgPath).isSymbolicLink())) {
return;
}
if (existsNew) {
const cfg1 = readFileSync(defaultCfg, 'utf8').replace(/\r|\n/g, '');
const cfg2 = readFileSync(cfgPath, 'utf8').replace(/\r|\n/g, '');
const hasNewConfigBeenTouched = cfg1 !== cfg2;
if (hasNewConfigBeenTouched) {
const backupPath = saveAsBackup(legacyCfgPath);
notify(
'Hyper 3',
`Settings location has changed to ${cfgPath}.\nWe've backed up your old Hyper config to ${backupPath}`
);
return;
}
}
copySync(legacyCfgPath, cfgPath);
saveAsBackup(legacyCfgPath);
notify(
'Hyper 3',
`Settings location has changed to ${cfgPath}.\nWe've automatically migrated your existing config!\nPlease restart Hyper now`
);
};
const _importConf = function() {
mkdirpSync(plugs.base);
mkdirpSync(plugs.local);
try {
migrateHyper2Config();
} catch (err) {
console.error(err);
}
try {
const defaultCfgRaw = readFileSync(defaultCfg, 'utf8');
const _defaultCfg = _extractDefault(defaultCfgRaw);
try {
const content = readFileSync(defaultPlatformKeyPath(), 'utf8');
const mapping = JSON.parse(content);
_defaultCfg.keymaps = mapping;
} catch (err) {
console.error(err);
}
try {
const userCfg = readFileSync(cfgPath, 'utf8');
return {userCfg, defaultCfg: _defaultCfg};
} catch (err) {
_write(cfgPath, defaultCfgRaw);
return {userCfg: defaultCfgRaw, defaultCfg: _defaultCfg};
}
} catch (err) {
console.log(err);
}
};
exports._import = () => {
const imported = _importConf();
defaultConfig = imported.defaultCfg;
const result = _init(imported);
return result;
};
exports.getDefaultConfig = () => {
if (!defaultConfig) {
defaultConfig = _extractDefault(_importConf().defaultCfg);
}
return defaultConfig;
};