Fix Flipper lints #18

Summary: Fixed several lint errors mainly related to Warning/node/no-sync.

Reviewed By: passy

Differential Revision: D31795894

fbshipit-source-id: 020597d93232a8e84b25ea11a87d9481a6d2616f
This commit is contained in:
Roman Karpenko
2021-10-21 03:43:32 -07:00
committed by Facebook GitHub Bot
parent 37498ad5a9
commit 2be631ea4d
3 changed files with 122 additions and 87 deletions

View File

@@ -10,7 +10,6 @@
import os from 'os'; import os from 'os';
import fs from 'fs'; import fs from 'fs';
import path from 'path'; import path from 'path';
import {promisify} from 'util';
import {spawn} from 'child_process'; import {spawn} from 'child_process';
import xdg from 'xdg-basedir'; import xdg from 'xdg-basedir';
import mkdirp from 'mkdirp'; import mkdirp from 'mkdirp';
@@ -18,14 +17,19 @@ import mkdirp from 'mkdirp';
const isProduction = () => const isProduction = () =>
!/node_modules[\\/]electron[\\/]/.test(process.execPath); !/node_modules[\\/]electron[\\/]/.test(process.execPath);
const isLauncherInstalled = () => { const isLauncherInstalled = async () => {
if (os.type() == 'Darwin') { if (os.type() == 'Darwin') {
const receipt = 'com.facebook.flipper.launcher'; const receipt = 'com.facebook.flipper.launcher';
const plistLocation = '/Applications/Flipper.app/Contents/Info.plist'; const plistLocation = '/Applications/Flipper.app/Contents/Info.plist';
try {
return ( return (
fs.existsSync(plistLocation) && (await fs.promises.stat(plistLocation)) &&
fs.readFileSync(plistLocation).indexOf(receipt) > 0 (await fs.promises.readFile(plistLocation)).indexOf(receipt) > 0
); );
} catch (e) {
console.error('Error while reading Info.plist', e);
return false;
}
} }
return false; return false;
@@ -54,17 +58,14 @@ const checkIsCycle = async () => {
let backThen; let backThen;
try { try {
backThen = parseInt( backThen = parseInt((await fs.promises.readFile(filePath)).toString(), 10);
(await promisify(fs.readFile)(filePath)).toString(),
10,
);
} catch (e) { } catch (e) {
backThen = 0; backThen = 0;
} }
const delta = rightNow - backThen; const delta = rightNow - backThen;
await mkdirp(dir); await mkdirp(dir);
await promisify(fs.writeFile)(filePath, '' + rightNow); await fs.promises.writeFile(filePath, '' + rightNow);
// If the last startup was less than 5s ago, something's not okay. // If the last startup was less than 5s ago, something's not okay.
return Math.abs(delta) < 5000; return Math.abs(delta) < 5000;
@@ -79,7 +80,7 @@ export default async function delegateToLauncher(argv: {
file?: string; file?: string;
url?: string; url?: string;
}) { }) {
if (argv.launcher && isProduction() && isLauncherInstalled()) { if (argv.launcher && isProduction() && (await isLauncherInstalled())) {
if (await checkIsCycle()) { if (await checkIsCycle()) {
console.error( console.error(
'Launcher cycle detected. Not delegating even though I usually would.', 'Launcher cycle detected. Not delegating even though I usually would.',

View File

@@ -26,7 +26,7 @@ import url from 'url';
import fs from 'fs'; import fs from 'fs';
import fixPath from 'fix-path'; import fixPath from 'fix-path';
import {exec} from 'child_process'; import {exec} from 'child_process';
import setup from './setup'; import setup, {Config, configPath} from './setup';
import isFB from './fb-stubs/isFB'; import isFB from './fb-stubs/isFB';
import delegateToLauncher from './launcher'; import delegateToLauncher from './launcher';
import yargs from 'yargs'; import yargs from 'yargs';
@@ -99,8 +99,6 @@ const argv = yargs
.help() .help()
.parse(process.argv.slice(1)); .parse(process.argv.slice(1));
const {config, configPath} = setup(argv);
if (isFB && process.env.FLIPPER_FB === undefined) { if (isFB && process.env.FLIPPER_FB === undefined) {
process.env.FLIPPER_FB = 'true'; process.env.FLIPPER_FB = 'true';
} }
@@ -110,11 +108,6 @@ if (argv['disable-gpu'] || process.env.FLIPPER_DISABLE_GPU === '1') {
app.disableHardwareAcceleration(); app.disableHardwareAcceleration();
} }
process.env.CONFIG = JSON.stringify(config);
nativeTheme.themeSource = validThemes.includes(config.darkMode)
? config.darkMode
: 'light';
// possible reference to main app window // possible reference to main app window
let win: BrowserWindow; let win: BrowserWindow;
let appReady = false; let appReady = false;
@@ -178,9 +171,13 @@ app.on('will-finish-launching', () => {
}); });
}); });
app.on('ready', () => { app.on('ready', async () => {
const config = await setup(argv);
processConfig(config);
// If we delegate to the launcher, shut down this instance of the app. // If we delegate to the launcher, shut down this instance of the app.
delegateToLauncher(argv).then(async (hasLauncherInvoked: boolean) => { delegateToLauncher(argv)
.then(async (hasLauncherInvoked: boolean) => {
if (hasLauncherInvoked) { if (hasLauncherInvoked) {
app.quit(); app.quit();
return; return;
@@ -188,7 +185,8 @@ app.on('ready', () => {
appReady = true; appReady = true;
app.commandLine.appendSwitch('scroll-bounce'); app.commandLine.appendSwitch('scroll-bounce');
configureSession(); configureSession();
createWindow(); createWindow(config);
// if in development install the react devtools extension // if in development install the react devtools extension
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
const { const {
@@ -202,11 +200,13 @@ app.on('ready', () => {
console.log('Force updating DevTools'); console.log('Force updating DevTools');
} }
// Redux // Redux
try {
await installExtension(REDUX_DEVTOOLS.id, { await installExtension(REDUX_DEVTOOLS.id, {
loadExtensionOptions: {allowFileAccess: true, forceDownload}, loadExtensionOptions: {allowFileAccess: true, forceDownload},
}).catch((e: any) => {
console.error('Failed to install Redux devtools extension', e);
}); });
} catch (e) {
console.error('Failed to install Redux devtools extension', e);
}
// React // React
// Fix for extension loading (see D27685981) // Fix for extension loading (see D27685981)
// Work around per https://github.com/electron/electron/issues/23662#issuecomment-787420799 // Work around per https://github.com/electron/electron/issues/23662#issuecomment-787420799
@@ -215,24 +215,27 @@ app.on('ready', () => {
}`; }`;
if (await promisify(fs.exists)(reactDevToolsPath)) { if (await promisify(fs.exists)(reactDevToolsPath)) {
console.log('Loading React devtools from disk ' + reactDevToolsPath); console.log('Loading React devtools from disk ' + reactDevToolsPath);
await session.defaultSession try {
.loadExtension( await session.defaultSession.loadExtension(
reactDevToolsPath, reactDevToolsPath,
// @ts-ignore only supported (and needed) in Electron 12 // @ts-ignore only supported (and needed) in Electron 12
{allowFileAccess: true}, {allowFileAccess: true},
) );
.catch((e) => { } catch (e) {
console.error('Failed to loa React devtools from disk: ', e); console.error('Failed to loa React devtools from disk: ', e);
}); }
} else { } else {
try {
await installExtension(REACT_DEVELOPER_TOOLS.id, { await installExtension(REACT_DEVELOPER_TOOLS.id, {
loadExtensionOptions: {allowFileAccess: true, forceDownload}, loadExtensionOptions: {allowFileAccess: true, forceDownload},
}).catch((e: any) => { });
} catch (e) {
console.error('Failed to install React devtools extension', e); console.error('Failed to install React devtools extension', e);
});
} }
} }
}); }
})
.catch((e: any) => console.error('Error while delegating app launch', e));
}); });
app.on('web-contents-created', (_event, contents) => { app.on('web-contents-created', (_event, contents) => {
@@ -340,7 +343,7 @@ app.setAsDefaultProtocolClient('flipper');
// is workaround suggested in the issue // is workaround suggested in the issue
app.commandLine.appendSwitch('disable-features', 'OutOfBlinkCors'); app.commandLine.appendSwitch('disable-features', 'OutOfBlinkCors');
function createWindow() { function createWindow(config: Config) {
win = new BrowserWindow({ win = new BrowserWindow({
show: false, show: false,
title: 'Flipper', title: 'Flipper',
@@ -384,7 +387,8 @@ function createWindow() {
const [x, y] = win.getPosition(); const [x, y] = win.getPosition();
const [width, height] = win.getSize(); const [width, height] = win.getSize();
// save window position and size // save window position and size
fs.writeFileSync(
fs.writeFile(
configPath, configPath,
JSON.stringify({ JSON.stringify({
...config, ...config,
@@ -396,6 +400,11 @@ function createWindow() {
height, height,
}, },
}), }),
(err) => {
if (err) {
console.error('Error while saving window position/size', err);
}
},
); );
}); });
if ( if (
@@ -414,3 +423,10 @@ function createWindow() {
}); });
win.loadURL(entryUrl); win.loadURL(entryUrl);
} }
function processConfig(config: Config) {
process.env.CONFIG = JSON.stringify(config);
nativeTheme.themeSource = validThemes.includes(config.darkMode)
? config.darkMode
: 'light';
}

View File

@@ -11,6 +11,14 @@ import path from 'path';
import os from 'os'; import os from 'os';
import fs from 'fs'; import fs from 'fs';
const flipperHomeDir = path.join(os.homedir(), '.flipper');
export const configPath = path.join(flipperHomeDir, 'config.json');
export const defaultConfig: Config = {
pluginPaths: [],
disabledPlugins: [],
darkMode: 'light',
};
export type Config = { export type Config = {
pluginPaths?: string[]; pluginPaths?: string[];
disabledPlugins?: string[]; disabledPlugins?: string[];
@@ -27,31 +35,41 @@ export type Config = {
darkMode: 'system' | 'light' | 'dark'; darkMode: 'system' | 'light' | 'dark';
}; };
export default function setup(argv: any) { const ensureConfigDirExists = async (path: fs.PathLike) => {
// ensure .flipper folder and config exist try {
const flipperDir = path.join(os.homedir(), '.flipper'); await fs.promises.access(path);
if (!fs.existsSync(flipperDir)) { } catch (e) {
fs.mkdirSync(flipperDir); console.warn('Config directory not found, creating config directory.');
try {
await fs.promises.mkdir(path);
} catch (e) {
console.error('Failed to create config directory', e);
} }
}
};
const configPath = path.join(flipperDir, 'config.json'); const readConfigFile = async (configPath: fs.PathLike) => {
let config: Config = { let config = defaultConfig;
pluginPaths: [],
disabledPlugins: [],
darkMode: 'light',
};
try { try {
config = { config = {
...config, ...config,
...JSON.parse(fs.readFileSync(configPath).toString()), ...JSON.parse((await fs.promises.readFile(configPath)).toString()),
}; };
} catch (e) { } catch (e) {
// file not readable or not parsable, overwrite it with the new config // file not readable or not parsable, overwrite it with the new config
console.warn(`Failed to read ${configPath}: ${e}`); console.warn(`Failed to read ${configPath}: ${e}`);
console.info('Writing new default config.'); console.info('Writing new default config.');
fs.writeFileSync(configPath, JSON.stringify(config)); await fs.promises.writeFile(configPath, JSON.stringify(config));
} }
return config;
};
export default async function setup(argv: any) {
// ensure .flipper folder and config exist
await ensureConfigDirExists(flipperHomeDir);
let config = await readConfigFile(configPath);
// Non-persistent CLI arguments. // Non-persistent CLI arguments.
config = { config = {
@@ -67,5 +85,5 @@ export default function setup(argv: any) {
launcherMsg: argv.launcherMsg, launcherMsg: argv.launcherMsg,
}; };
return {config, configPath}; return config;
} }