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 {shell} from 'electron';
import {cfgPath} from './paths'; import {cfgPath} from './paths';
import {Registry, loadRegistry} from '../utils/registry'; import {Registry, loadRegistry} from '../utils/registry';
import {exec} from 'child_process';
export default () => { const getUserChoiceKey = () => {
// 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 () => {
if (!loadRegistry()) return; if (!loadRegistry()) return;
try { try {
// Load FileExts keys for .js files // Load FileExts keys for .js files
@ -30,11 +24,11 @@ export default () => {
console.error(error); console.error(error);
return; return;
} }
}; };
const hasDefaultSet = async () => { const hasDefaultSet = () => {
if (!loadRegistry()) return false; if (!loadRegistry()) return false;
const userChoice = await getUserChoiceKey(); const userChoice = getUserChoiceKey();
if (!userChoice) return false; if (!userChoice) return false;
try { try {
@ -55,29 +49,29 @@ export default () => {
console.error(error); console.error(error);
return false; return false;
} }
}; };
// This mimics shell.openItem, true if it worked, false if not. // This mimics shell.openItem, true if it worked, false if not.
const openNotepad = (file: string) => const openNotepad = (file: string) =>
new Promise<boolean>((resolve) => { new Promise<boolean>((resolve) => {
exec(`start notepad.exe ${file}`, (error) => { exec(`start notepad.exe ${file}`, (error) => {
resolve(!error); resolve(!error);
}); });
}); });
return hasDefaultSet() export default () => {
.then((yes) => { // Windows opens .js files with WScript.exe by default
if (yes) { // 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 === ''); return shell.openPath(cfgPath).then((error) => error === '');
} }
console.warn('No default app set for .js files, using notepad.exe fallback'); 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); 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 === '');
}; };