refactor config/open

This commit is contained in:
Labhansh Agrawal 2021-01-10 00:08:21 +05:30 committed by Benjamin Staneck
parent 7ae9a328a3
commit 0863a46889

View file

@ -1,15 +1,9 @@
import {shell} from 'electron';
import {cfgPath} from './paths';
import {Registry, loadRegistry} from '../utils/registry';
import {exec} from 'child_process';
export default () => {
// Windows opens .js files with WScript.exe by default
// If the user hasn't set up an editor for .js files, we fallback to notepad.
if (process.platform === 'win32') {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const {exec} = require('child_process') as typeof import('child_process');
const getUserChoiceKey = async () => {
const getUserChoiceKey = () => {
if (!loadRegistry()) return;
try {
// Load FileExts keys for .js files
@ -30,11 +24,11 @@ export default () => {
console.error(error);
return;
}
};
};
const hasDefaultSet = async () => {
const hasDefaultSet = () => {
if (!loadRegistry()) return false;
const userChoice = await getUserChoiceKey();
const userChoice = getUserChoiceKey();
if (!userChoice) return false;
try {
@ -55,29 +49,29 @@ export default () => {
console.error(error);
return false;
}
};
};
// This mimics shell.openItem, true if it worked, false if not.
const openNotepad = (file: string) =>
// This mimics shell.openItem, true if it worked, false if not.
const openNotepad = (file: string) =>
new Promise<boolean>((resolve) => {
exec(`start notepad.exe ${file}`, (error) => {
resolve(!error);
});
});
return hasDefaultSet()
.then((yes) => {
if (yes) {
export default () => {
// Windows opens .js files with WScript.exe by default
// If the user hasn't set up an editor for .js files, we fallback to notepad.
if (process.platform === 'win32') {
try {
if (hasDefaultSet()) {
return shell.openPath(cfgPath).then((error) => error === '');
}
console.warn('No default app set for .js files, using notepad.exe fallback');
return openNotepad(cfgPath);
})
.catch((err) => {
} catch (err) {
console.error('Open config with default app error:', err);
return openNotepad(cfgPath);
});
} else {
return Promise.resolve(shell.openPath(cfgPath).then((error) => error === ''));
}
return openNotepad(cfgPath);
}
return shell.openPath(cfgPath).then((error) => error === '');
};