Prefer const wherever possible

Summary:
Non-final identifiers make code harder to understand.
This is particularly true for JavaScript where even the *type*
can change as a value gets reassigned later.

This enforces to use `const` whereever possible, but doesn't
"outlaw" `let`. Mixed destructuring is also still allowed.

Used `eslint --fix` to change all existing cases.

Reviewed By: jknoxville

Differential Revision: D16131329

fbshipit-source-id: 2eceaca7c603b71b36e005be5d135e1849f2518d
This commit is contained in:
Pascal Hartig
2019-07-09 04:15:32 -07:00
committed by Facebook Github Bot
parent 662db20948
commit c588b650ae
34 changed files with 141 additions and 140 deletions

View File

@@ -22,8 +22,9 @@ module.exports = {
'no-bitwise': 0, // bitwise operations needed in some places
'consistent-return': 0,
'no-var': 2,
'max-len': 0, // let's take prettier take care of this
indent: 0, // let's take prettier take care of this
'prefer-const': [2, {destructuring: 'all'}],
'max-len': 0, // lets prettier take care of this
indent: 0, // lets prettier take care of this
'no-console': 0, // we're setting window.console in App.js
'prefer-promise-reject-errors': 1,

View File

@@ -146,7 +146,7 @@ async function exitActions(
store: Store,
): Promise<void> {
const {metrics, exit} = userArguments;
for (let exitAction of exitClosures) {
for (const exitAction of exitClosures) {
try {
const action = await exitAction(userArguments, store);
if (action.exit) {

View File

@@ -355,7 +355,7 @@ const shadow = (props, hover) => {
if (props.inactive) {
return `inset 0 0 0 1px ${colors.light10}`;
}
let shadow = ['1px 1px 5px rgba(0,0,0,0.1)'];
const shadow = ['1px 1px 5px rgba(0,0,0,0.1)'];
if (props.isSelected) {
shadow.push(`inset 0 0 0 2px ${colors.macOSTitleBarIconSelected}`);
}

View File

@@ -29,7 +29,7 @@ class LocationsButton extends Component<Props> {
goToLocation = (location: string) => {
const {selectedDevice} = this.props;
if (selectedDevice instanceof AndroidDevice) {
let shellCommand = `am start ${location}`;
const shellCommand = `am start ${location}`;
selectedDevice.adb.shell(selectedDevice.serial, shellCommand);
}
};

View File

@@ -161,7 +161,7 @@ class PluginDebugger extends Component<Props> {
}
getRows(): Array<TableBodyRow> {
let rows: Array<TableBodyRow> = [];
const rows: Array<TableBodyRow> = [];
// bundled plugins are loaded from the defaultPlugins directory within
// Flipper's package.

View File

@@ -9,24 +9,24 @@ import {uriComponents} from '../application.js';
test('test parsing of deeplink URL', () => {
const url = 'flipper://app/plugin/meta/data';
let components = uriComponents(url);
const components = uriComponents(url);
expect(components).toEqual(['app', 'plugin', 'meta/data']);
});
test('test parsing of deeplink URL when arguments are less', () => {
const url = 'flipper://app/';
let components = uriComponents(url);
const components = uriComponents(url);
expect(components).toEqual(['app']);
});
test('test parsing of deeplink URL when url is null', () => {
// $FlowFixMe
let components = uriComponents(null);
const components = uriComponents(null);
expect(components).toEqual([]);
});
test('test parsing of deeplink URL when pattern does not match', () => {
const url = 'Some random string';
let components = uriComponents(url);
const components = uriComponents(url);
expect(components).toEqual([]);
});

View File

@@ -160,7 +160,7 @@ async function checkXcodeVersionMismatch() {
let {stdout: xcodeCLIVersion} = await exec('xcode-select -p');
xcodeCLIVersion = xcodeCLIVersion.trim();
const {stdout} = await exec('ps aux | grep CoreSimulator');
for (let line of stdout.split('\n')) {
for (const line of stdout.split('\n')) {
const match = line.match(
/\/Applications\/Xcode[^/]*\.app\/Contents\/Developer/,
);

View File

@@ -49,7 +49,7 @@ export default class TemperatureTable extends Component<TemperatureTableProps> {
};
buildRows = () => {
let rows = [];
const rows = [];
for (const tz of Object.keys(this.props.temperatureMap).sort()) {
rows.push(this.buildRow(tz, this.props.temperatureMap[tz]));
}

View File

@@ -6,7 +6,7 @@
*/
import {FlipperDevicePlugin, Device} from 'flipper';
let adb = require('adbkit-fb');
const adb = require('adbkit-fb');
import TemperatureTable from './TemperatureTable.js';
import {
@@ -107,7 +107,7 @@ const Heading = styled('div')({
// check if str is a number
function isNormalInteger(str) {
let n = Math.floor(Number(str));
const n = Math.floor(Number(str));
return String(n) === str && n >= 0;
}
@@ -145,7 +145,7 @@ export default class CPUFrequencyTable extends FlipperDevicePlugin<CPUState> {
}
init() {
let device = ((this.device: any): AndroidDevice);
const device = ((this.device: any): AndroidDevice);
this.adbClient = device.adb;
this.updateHardwareInfo();
@@ -153,9 +153,9 @@ export default class CPUFrequencyTable extends FlipperDevicePlugin<CPUState> {
// check how many cores we have on this device
this.executeShell((output: string) => {
let idx = output.indexOf('-');
let cpuFreq = [];
let count = parseInt(output.substring(idx + 1), 10) + 1;
const idx = output.indexOf('-');
const cpuFreq = [];
const count = parseInt(output.substring(idx + 1), 10) + 1;
for (let i = 0; i < count; ++i) {
cpuFreq[i] = {
cpu_id: i,
@@ -187,8 +187,8 @@ export default class CPUFrequencyTable extends FlipperDevicePlugin<CPUState> {
updateCoreFrequency = (core: number, type: string) => {
this.executeShell((output: string) => {
let cpuFreq = this.state.cpuFreq;
let newFreq = isNormalInteger(output) ? parseInt(output, 10) : -1;
const cpuFreq = this.state.cpuFreq;
const newFreq = isNormalInteger(output) ? parseInt(output, 10) : -1;
// update table only if frequency changed
if (cpuFreq[core][type] != newFreq) {
@@ -207,12 +207,12 @@ export default class CPUFrequencyTable extends FlipperDevicePlugin<CPUState> {
updateAvailableFrequencies = (core: number) => {
this.executeShell((output: string) => {
let cpuFreq = this.state.cpuFreq;
let freqs = output.split(' ').map((num: string) => {
const cpuFreq = this.state.cpuFreq;
const freqs = output.split(' ').map((num: string) => {
return parseInt(num, 10);
});
cpuFreq[core].scaling_available_freqs = freqs;
let maxFreq = cpuFreq[core].scaling_max_freq;
const maxFreq = cpuFreq[core].scaling_max_freq;
if (maxFreq > 0 && freqs.indexOf(maxFreq) == -1) {
freqs.push(maxFreq); // always add scaling max to available frequencies
}
@@ -224,7 +224,7 @@ export default class CPUFrequencyTable extends FlipperDevicePlugin<CPUState> {
updateCoreGovernor = (core: number) => {
this.executeShell((output: string) => {
let cpuFreq = this.state.cpuFreq;
const cpuFreq = this.state.cpuFreq;
if (output.toLowerCase().includes('no such file')) {
cpuFreq[core].scaling_governor = 'N/A';
} else {
@@ -238,7 +238,7 @@ export default class CPUFrequencyTable extends FlipperDevicePlugin<CPUState> {
readAvailableGovernors = (core: number) => {
this.executeShell((output: string) => {
let cpuFreq = this.state.cpuFreq;
const cpuFreq = this.state.cpuFreq;
cpuFreq[core].scaling_available_governors = output.split(' ');
this.setState({
@@ -248,7 +248,7 @@ export default class CPUFrequencyTable extends FlipperDevicePlugin<CPUState> {
};
readCoreFrequency = (core: number) => {
let freq = this.state.cpuFreq[core];
const freq = this.state.cpuFreq[core];
if (freq.cpuinfo_max_freq < 0) {
this.updateCoreFrequency(core, 'cpuinfo_max_freq');
}
@@ -296,21 +296,21 @@ export default class CPUFrequencyTable extends FlipperDevicePlugin<CPUState> {
};
readThermalZones = () => {
let thermal_dir = '/sys/class/thermal/';
let map = {};
const thermal_dir = '/sys/class/thermal/';
const map = {};
this.executeShell(async (output: string) => {
if (output.toLowerCase().includes('permission denied')) {
this.setState({thermalAccessible: false});
return;
}
let dirs = output.split(/\s/);
let promises = [];
const dirs = output.split(/\s/);
const promises = [];
for (let d of dirs) {
d = d.trim();
if (d.length == 0) {
continue;
}
let path = thermal_dir + d;
const path = thermal_dir + d;
promises.push(this.readThermalZone(path, d, map));
}
await Promise.all(promises);
@@ -374,7 +374,7 @@ export default class CPUFrequencyTable extends FlipperDevicePlugin<CPUState> {
};
cleanup = () => {
let cpuFreq = this.state.cpuFreq;
const cpuFreq = this.state.cpuFreq;
for (let i = 0; i < this.state.cpuCount; ++i) {
cpuFreq[i].scaling_cur_freq = -1;
cpuFreq[i].scaling_min_freq = -1;
@@ -394,7 +394,7 @@ export default class CPUFrequencyTable extends FlipperDevicePlugin<CPUState> {
};
buildRow = (freq: CPUFrequency, idx: number) => {
let selected = this.state.selectedIds.indexOf(idx) >= 0;
const selected = this.state.selectedIds.indexOf(idx) >= 0;
let style = {};
if (freq.scaling_cur_freq == -2) {
style = {
@@ -466,11 +466,11 @@ export default class CPUFrequencyTable extends FlipperDevicePlugin<CPUState> {
if (freq.scaling_available_freqs.length == 0) {
return <Text>N/A</Text>;
}
let info = freq;
const info = freq;
return (
<Text>
{freq.scaling_available_freqs.map((freq, idx) => {
let style = {};
const style = {};
if (
freq == info.scaling_cur_freq ||
freq == info.scaling_min_freq ||
@@ -519,15 +519,15 @@ export default class CPUFrequencyTable extends FlipperDevicePlugin<CPUState> {
sidebarRows = (id: number) => {
let availableFreqTitle = 'Scaling Available Frequencies';
let selected = this.state.cpuFreq[id];
const selected = this.state.cpuFreq[id];
if (selected.scaling_available_freqs.length > 0) {
availableFreqTitle +=
' (' + selected.scaling_available_freqs.length.toString() + ')';
}
let keys = [availableFreqTitle, 'Scaling Available Governors'];
const keys = [availableFreqTitle, 'Scaling Available Governors'];
let vals = [
const vals = [
this.buildAvailableFreqList(selected),
this.buildAvailableGovList(selected),
];
@@ -540,8 +540,8 @@ export default class CPUFrequencyTable extends FlipperDevicePlugin<CPUState> {
if (!this.state.displayCPUDetail || this.state.selectedIds.length == 0) {
return null;
}
let id = this.state.selectedIds[0];
let cols = {
const id = this.state.selectedIds[0];
const cols = {
key: {
value: 'key',
resizable: true,
@@ -551,7 +551,7 @@ export default class CPUFrequencyTable extends FlipperDevicePlugin<CPUState> {
resizable: true,
},
};
let colSizes = {
const colSizes = {
key: '35%',
value: 'flex',
};

View File

@@ -346,20 +346,20 @@ test('test parsing of path when a regex is not present', () => {
});
test('test shouldShowCrashNotification function for all correct inputs', () => {
const device = new BaseDevice('TH1S-15DEV1CE-1D', 'emulator', 'test device');
let content =
const content =
'Blaa Blaaa \n Blaa Blaaa \n Path: path/to/simulator/TH1S-15DEV1CE-1D/App Name.app/App Name \n Blaa Blaa \n Blaa Blaa';
const shouldShowNotification = shouldShowCrashNotification(device, content);
expect(shouldShowNotification).toEqual(true);
});
test('test shouldShowCrashNotification function for all correct inputs but incorrect id', () => {
const device = new BaseDevice('TH1S-15DEV1CE-1D', 'emulator', 'test device');
let content =
const content =
'Blaa Blaaa \n Blaa Blaaa \n Path: path/to/simulator/TH1S-1598DEV1CE-2D/App Name.app/App Name \n Blaa Blaa \n Blaa Blaa';
const shouldShowNotification = shouldShowCrashNotification(device, content);
expect(shouldShowNotification).toEqual(false);
});
test('test shouldShowCrashNotification function for undefined device', () => {
let content =
const content =
'Blaa Blaaa \n Blaa Blaaa \n Path: path/to/simulator/TH1S-1598DEV1CE-2D/App Name.app/App Name \n Blaa Blaa \n Blaa Blaa';
const shouldShowNotification = shouldShowCrashNotification(null, content);
expect(shouldShowNotification).toEqual(false);

View File

@@ -544,7 +544,7 @@ export default class CrashReporterPlugin extends FlipperDevicePlugin<
};
static trimCallStackIfPossible = (callstack: string): string => {
let regex = /Application Specific Information:/;
const regex = /Application Specific Information:/;
const query = regex.exec(callstack);
return query ? callstack.substring(0, query.index) : callstack;
};
@@ -555,7 +555,7 @@ export default class CrashReporterPlugin extends FlipperDevicePlugin<
persistedState: PersistedState,
): Array<Notification> => {
const filteredCrashes = persistedState.crashes.filter(crash => {
let ignore = !crash.name && !crash.reason;
const ignore = !crash.name && !crash.reason;
if (ignore) {
console.error('Ignored the notification for the crash', crash);
}
@@ -563,7 +563,7 @@ export default class CrashReporterPlugin extends FlipperDevicePlugin<
});
return filteredCrashes.map((crash: Crash) => {
const id = crash.notificationID;
let name: string = crash.name || crash.reason;
const name: string = crash.name || crash.reason;
let title: string = 'CRASH: ' + truncate(name, 50);
title = `${
name == crash.reason

View File

@@ -302,7 +302,7 @@ export default class extends FlipperPlugin<PluginState, *, PersistedState> {
this.props.setPersistedState({imagesMap: images}),
);
let images = this.filterImages(
const images = this.filterImages(
this.props.persistedState.images,
this.props.persistedState.events,
this.state.selectedSurface,

View File

@@ -28,7 +28,7 @@ function constructSearchResultTree(
AXMode: boolean,
AXNode: ?Element,
): SearchResultTree {
let searchResult = {
const searchResult = {
id: node.id,
isMatch,
hasChildren: children.length > 0,
@@ -118,7 +118,7 @@ class ProxyArchiveClient {
}
const {ids} = paramaters;
const arr: Array<Element> = [];
for (let id: ElementID of ids) {
for (const id: ElementID of ids) {
arr.push(this.persistedState.elements[id]);
}
return Promise.resolve({elements: arr});
@@ -129,7 +129,7 @@ class ProxyArchiveClient {
}
const {ids} = paramaters;
const arr: Array<Element> = [];
for (let id: ElementID of ids) {
for (const id: ElementID of ids) {
arr.push(this.persistedState.AXelements[id]);
}
return Promise.resolve({elements: arr});

View File

@@ -49,7 +49,7 @@ function constructPersistedState(axMode: boolean): PersistedState {
let state = constructPersistedState(false);
function populateChildren(state: PersistedState, axMode: boolean) {
let elements = {};
const elements = {};
elements['root'] = constructElement('root', 'root view', [
'child0',
'child1',
@@ -95,7 +95,7 @@ beforeEach(() => {
});
test('test the searchNode for root in axMode false', async () => {
let searchResult: ?SearchResultTree = await searchNodes(
const searchResult: ?SearchResultTree = await searchNodes(
state.elements['root'],
'root',
false,
@@ -115,7 +115,7 @@ test('test the searchNode for root in axMode false', async () => {
test('test the searchNode for root in axMode true', async () => {
state = constructPersistedState(true);
populateChildren(state, true);
let searchResult: ?SearchResultTree = await searchNodes(
const searchResult: ?SearchResultTree = await searchNodes(
state.AXelements['root'],
'RoOT',
true,
@@ -133,7 +133,7 @@ test('test the searchNode for root in axMode true', async () => {
});
test('test the searchNode which matches just one child', async () => {
let searchResult: ?SearchResultTree = await searchNodes(
const searchResult: ?SearchResultTree = await searchNodes(
state.elements['root'],
'child0_child0',
false,
@@ -169,14 +169,14 @@ test('test the searchNode which matches just one child', async () => {
});
test('test the searchNode for which matches multiple child', async () => {
let searchResult: ?SearchResultTree = await searchNodes(
const searchResult: ?SearchResultTree = await searchNodes(
state.elements['root'],
'child0',
false,
state,
);
expect(searchResult).toBeDefined();
let expectedSearchResult = {
const expectedSearchResult = {
id: 'root',
isMatch: false,
hasChildren: true,
@@ -231,14 +231,14 @@ test('test the searchNode for which matches multiple child', async () => {
});
test('test the searchNode, it should not be case sensitive', async () => {
let searchResult: ?SearchResultTree = await searchNodes(
const searchResult: ?SearchResultTree = await searchNodes(
state.elements['root'],
'ChIlD0',
false,
state,
);
expect(searchResult).toBeDefined();
let expectedSearchResult = {
const expectedSearchResult = {
id: 'root',
isMatch: false,
hasChildren: true,
@@ -293,7 +293,7 @@ test('test the searchNode, it should not be case sensitive', async () => {
});
test('test the searchNode for non existent query', async () => {
let searchResult: ?SearchResultTree = await searchNodes(
const searchResult: ?SearchResultTree = await searchNodes(
state.elements['root'],
'Unknown query',
false,
@@ -303,22 +303,22 @@ test('test the searchNode for non existent query', async () => {
});
test('test the call method with getRoot', async () => {
let proxyClient = new ProxyArchiveClient(state);
let root: Element = await proxyClient.call('getRoot');
const proxyClient = new ProxyArchiveClient(state);
const root: Element = await proxyClient.call('getRoot');
expect(root).toEqual(state.elements['root']);
});
test('test the call method with getAXRoot', async () => {
state = constructPersistedState(true);
populateChildren(state, true);
let proxyClient = new ProxyArchiveClient(state);
let root: Element = await proxyClient.call('getAXRoot');
const proxyClient = new ProxyArchiveClient(state);
const root: Element = await proxyClient.call('getAXRoot');
expect(root).toEqual(state.AXelements['root']);
});
test('test the call method with getNodes', async () => {
let proxyClient = new ProxyArchiveClient(state);
let nodes: Array<Element> = await proxyClient.call('getNodes', {
const proxyClient = new ProxyArchiveClient(state);
const nodes: Array<Element> = await proxyClient.call('getNodes', {
ids: ['child0_child1', 'child1_child0'],
});
expect(nodes).toEqual({
@@ -350,8 +350,8 @@ test('test the call method with getNodes', async () => {
test('test the call method with getAXNodes', async () => {
state = constructPersistedState(true);
populateChildren(state, true);
let proxyClient = new ProxyArchiveClient(state);
let nodes: Array<Element> = await proxyClient.call('getAXNodes', {
const proxyClient = new ProxyArchiveClient(state);
const nodes: Array<Element> = await proxyClient.call('getAXNodes', {
ids: ['child0_child1', 'child1_child0'],
});
expect(nodes).toEqual({
@@ -381,7 +381,7 @@ test('test the call method with getAXNodes', async () => {
});
test('test different methods of calls with no params', async () => {
let proxyClient = new ProxyArchiveClient(state);
const proxyClient = new ProxyArchiveClient(state);
await expect(proxyClient.call('getNodes')).rejects.toThrow(
new Error('Called getNodes with no params'),
);
@@ -408,6 +408,6 @@ test('test different methods of calls with no params', async () => {
});
test('test call method isConsoleEnabled', () => {
let proxyClient = new ProxyArchiveClient(state);
const proxyClient = new ProxyArchiveClient(state);
return expect(proxyClient.call('isConsoleEnabled')).resolves.toBe(false);
});

View File

@@ -69,7 +69,7 @@ export default class LeakCanary extends FlipperPlugin<State> {
// collapsed state of the tree view
const newLeaks = processLeaks(results.leaks.slice(this.state.leaksCount));
let leaks = this.state.leaks;
const leaks = this.state.leaks;
for (let i = 0; i < newLeaks.length; i++) {
leaks.push(newLeaks[i]);
}

View File

@@ -53,8 +53,8 @@ function generateFieldsList(
lines: string[],
i: number,
): {|staticFields: {}, instanceFields: {}, packages: {}|} {
let staticFields = {};
let instanceFields = {};
const staticFields = {};
const instanceFields = {};
let staticValues = {};
let instanceValues = {};
@@ -62,7 +62,7 @@ function generateFieldsList(
let elementId = -1;
let elementIdStr = String(-1);
let packages = {};
const packages = {};
// Process everything between Details and Excluded Refs
while (
@@ -127,8 +127,8 @@ function processLeak(output: Leak[], leakInfo: string): Leak[] {
// Elements shows a Object's classname and package, wheras elementsSimple shows
// just its classname
let elements = {};
let elementsSimple = {};
const elements = {};
const elementsSimple = {};
let rootElementId = '';

View File

@@ -429,7 +429,7 @@ export default class LogTable extends FlipperDevicePlugin<
if (highlightedRows.size <= 0) {
// Check if the individual lines in the deeplinkPayload is matched or not.
const arr = deepLinkPayload.split('\n');
for (let msg of arr) {
for (const msg of arr) {
for (let i = rows.length - 1; i >= 0; i--) {
if (rows[i].filterValue && rows[i].filterValue.includes(msg)) {
highlightedRows.add(rows[i].key);

View File

@@ -129,7 +129,7 @@ test('convertRequestToCurlCommand: malicious POST data', () => {
});
test('convertRequestToCurlCommand: control characters', () => {
let request: Request = {
const request: Request = {
id: 'request id',
timestamp: 1234567890,
method: 'GET',
@@ -138,7 +138,7 @@ test('convertRequestToCurlCommand: control characters', () => {
data: btoa('some=\u0007 \u0009 \u000C \u001B&other=param'),
};
let command = convertRequestToCurlCommand(request);
const command = convertRequestToCurlCommand(request);
expect(command).toEqual(
"curl -v -X GET 'https://fbflipper.com/' -d $'some=\\u07 \\u09 \\u0c \\u1b&other=param'",
);

View File

@@ -90,8 +90,8 @@ export default class extends FlipperPlugin<SharedPreferencesState> {
reducers = {
UpdateSharedPreferences(state: SharedPreferencesState, results: Object) {
let update = results.update;
let entry = state.sharedPreferences[update.name] || {changesList: []};
const update = results.update;
const entry = state.sharedPreferences[update.name] || {changesList: []};
entry.preferences = update.preferences;
state.sharedPreferences[update.name] = entry;
return {
@@ -170,7 +170,7 @@ export default class extends FlipperPlugin<SharedPreferencesState> {
preferenceValue: newValue,
})
.then((results: SharedPreferences) => {
let update = {
const update = {
name: this.state.selectedPreferences,
preferences: results,
};

View File

@@ -143,7 +143,7 @@ const reducer = (state: State = INITAL_STATE, action: Action): State => {
selectedPlugin: DEFAULT_PLUGIN,
};
let canBeDefaultDevice = !DEFAULT_DEVICE_BLACKLIST.some(
const canBeDefaultDevice = !DEFAULT_DEVICE_BLACKLIST.some(
blacklistedDevice => payload instanceof blacklistedDevice,
);
@@ -272,7 +272,7 @@ const reducer = (state: State = INITAL_STATE, action: Action): State => {
case 'CLIENT_REMOVED': {
const {payload} = action;
let selected = {};
const selected = {};
if (state.selectedApp === payload) {
selected.selectedApp = null;
selected.selectedPlugin = DEFAULT_PLUGIN;

View File

@@ -76,7 +76,7 @@ export default class Server extends EventEmitter {
): Promise<RSocketServer> {
const server = this;
return new Promise((resolve, reject) => {
let rsServer;
let rsServer; // eslint-disable-line prefer-const
const serverFactory = onConnect => {
const transportServer = sslConfig
? tls.createServer(sslConfig, socket => {

View File

@@ -18,56 +18,56 @@ function getAndroidLog(
test('test shouldParseAndroidLog function for type error and tag is AndroidRuntime', () => {
const referenceDate = new Date();
let log: DeviceLogEntry = getAndroidLog(
const log: DeviceLogEntry = getAndroidLog(
new Date(referenceDate.getTime() + 10000), //This log arrives 10 secs after the refernce time
'error',
'AndroidRuntime',
'Possible runtime crash',
);
let shouldParseTheLog = shouldParseAndroidLog(log, referenceDate);
const shouldParseTheLog = shouldParseAndroidLog(log, referenceDate);
expect(shouldParseTheLog).toEqual(true);
});
test('test shouldParseAndroidLog function for type non-error', () => {
const referenceDate = new Date();
let log: DeviceLogEntry = getAndroidLog(
const log: DeviceLogEntry = getAndroidLog(
new Date(referenceDate.getTime() + 10000), //This log arrives 10 secs after the refernce time
'debug',
'fb4a.activitymanager',
'Possible debug info in activitymanager',
);
let shouldParseTheLog = shouldParseAndroidLog(log, referenceDate);
const shouldParseTheLog = shouldParseAndroidLog(log, referenceDate);
expect(shouldParseTheLog).toEqual(false);
});
test('test shouldParseAndroidLog function for the older android log', () => {
const referenceDate = new Date();
let log: DeviceLogEntry = getAndroidLog(
const log: DeviceLogEntry = getAndroidLog(
new Date(referenceDate.getTime() - 10000), //This log arrives 10 secs before the refernce time
'error',
'fb4a.activitymanager',
'Possible error info in activitymanager',
);
let shouldParseTheLog = shouldParseAndroidLog(log, referenceDate);
const shouldParseTheLog = shouldParseAndroidLog(log, referenceDate);
expect(shouldParseTheLog).toEqual(false);
});
test('test shouldParseAndroidLog function for the fatal log', () => {
const referenceDate = new Date();
let log: DeviceLogEntry = getAndroidLog(
const log: DeviceLogEntry = getAndroidLog(
new Date(referenceDate.getTime() + 10000), //This log arrives 10 secs after the refernce time
'fatal',
'arbitrary tag',
'Possible error info in activitymanager',
);
let shouldParseTheLog = shouldParseAndroidLog(log, referenceDate);
const shouldParseTheLog = shouldParseAndroidLog(log, referenceDate);
expect(shouldParseTheLog).toEqual(true);
});
test('test shouldParseAndroidLog function for the error log which does not staisfy our tags check', () => {
const referenceDate = new Date();
let log: DeviceLogEntry = getAndroidLog(
const log: DeviceLogEntry = getAndroidLog(
new Date(referenceDate.getTime() + 10000), //This log arrives 10 secs after the refernce time
'error',
'arbitrary tag',
'Possible error info in fb4a',
);
let shouldParseTheLog = shouldParseAndroidLog(log, referenceDate);
const shouldParseTheLog = shouldParseAndroidLog(log, referenceDate);
expect(shouldParseTheLog).toEqual(false);
});

View File

@@ -35,7 +35,7 @@ function generateClientIdentifierWithSalt(
identifier: string,
salt: string,
): string {
let array = identifier.split('#');
const array = identifier.split('#');
const serial = array.pop();
return array.join('#') + '#' + salt + '-' + serial;
}
@@ -198,7 +198,7 @@ test('test processStore function for an iOS device connected with client plugin
expect(json).toBeDefined();
//$FlowFixMe Flow doesn't that its a test and the assertion for null is already done
const {pluginStates} = json.store;
let expectedPluginState = {
const expectedPluginState = {
[generateClientIdentifierWithSalt(clientIdentifier, 'salt')]: {
msg: 'Test plugin',
},
@@ -258,7 +258,7 @@ test('test processStore function to have only the client for the selected device
//$FlowFixMe Flow doesn't that its a test and the assertion for null is already added
const {clients} = json;
const {pluginStates} = json.store;
let expectedPluginState = {
const expectedPluginState = {
[generateClientIdentifierWithSalt(selectedDeviceClientIdentifier, 'salt') +
'#testapp']: {
msg: 'Test plugin selected device',
@@ -313,7 +313,7 @@ test('test processStore function to have multiple clients for the selected devic
//$FlowFixMe Flow doesn't that its a test and the assertion for null is already added
const {clients} = json;
const {pluginStates} = json.store;
let expectedPluginState = {
const expectedPluginState = {
[generateClientIdentifierWithSalt(clientIdentifierApp1, 'salt') +
'#testapp1']: {
msg: 'Test plugin App1',
@@ -355,7 +355,7 @@ test('test processStore function for device plugin state and no clients', async
//$FlowFixMe Flow doesn't that its a test and the assertion for null is already done
const {pluginStates} = json.store;
const {clients} = json;
let expectedPluginState = {
const expectedPluginState = {
'salt-serial#TestDevicePlugin': {msg: 'Test Device plugin'},
};
expect(pluginStates).toEqual(expectedPluginState);

View File

@@ -41,18 +41,18 @@ function mockPluginDefinition(name: string): PluginDefinition {
}
test('getActivePluginNames with the plugins getting excluded', () => {
let state = mockPluginState(
const state = mockPluginState(
[mockPluginDefinition('DevicePlugin1')],
[mockPluginDefinition('ClientPlugin1')],
[[mockPluginDefinition('DevicePlugin2'), 'DevicePlugin2']],
);
let list = getActivePluginNames(state);
const list = getActivePluginNames(state);
expect(list).toEqual(['ClientPlugin2']);
});
test('getActivePluginNames with the no plugins getting excluded', () => {
let state = mockPluginState([], [], []);
let list = getActivePluginNames(state);
const state = mockPluginState([], [], []);
const list = getActivePluginNames(state);
expect(list).toEqual([
'ClientPlugin1',
'ClientPlugin2',

View File

@@ -7,10 +7,10 @@
import promiseTimeout from '../promiseTimeout';
test('test promiseTimeout for timeout to happen', () => {
let promise = promiseTimeout(
const promise = promiseTimeout(
200,
new Promise((resolve, reject) => {
let id = setTimeout(() => {
const id = setTimeout(() => {
clearTimeout(id);
resolve();
}, 500);
@@ -22,10 +22,10 @@ test('test promiseTimeout for timeout to happen', () => {
});
test('test promiseTimeout for timeout not to happen', () => {
let promise = promiseTimeout(
const promise = promiseTimeout(
200,
new Promise((resolve, reject) => {
let id = setTimeout(() => {
const id = setTimeout(() => {
clearTimeout(id);
resolve();
}, 100);

View File

@@ -19,12 +19,12 @@ class TestObject extends Object {
set: ?Set<any>;
}
test('test makeObjectSerializable function for unnested object with no Set and Map', () => {
let obj = {key1: 'value1', key2: 'value2'};
const obj = {key1: 'value1', key2: 'value2'};
const output = makeObjectSerializable(obj);
expect(output).toEqual(obj);
// Testing numbers
let obj2 = {key1: 1, key2: 2};
const obj2 = {key1: 1, key2: 2};
const output2 = makeObjectSerializable(obj2);
expect(output2).toEqual(obj2);
});
@@ -36,27 +36,27 @@ test('makeObjectSerializable function for unnested object with values which retu
});
test('test deserializeObject function for unnested object with no Set and Map', () => {
let obj = {key1: 'value1', key2: 'value2'};
const obj = {key1: 'value1', key2: 'value2'};
const output = deserializeObject(obj);
expect(output).toEqual(obj);
// Testing numbers
let obj2 = {key1: 1, key2: 2};
const obj2 = {key1: 1, key2: 2};
const output2 = deserializeObject(obj2);
expect(output2).toEqual(obj2);
});
test('test makeObjectSerializable and deserializeObject function for nested object with no Set and Map', () => {
let subObj = {key1: 'value1', key2: 'value2'};
let subObj2 = {key21: 'value21', key22: 'value22'};
let obj = {key1: subObj, key2: subObj2};
const subObj = {key1: 'value1', key2: 'value2'};
const subObj2 = {key21: 'value21', key22: 'value22'};
const obj = {key1: subObj, key2: subObj2};
const output = makeObjectSerializable(obj);
expect(output).toEqual(obj);
expect(deserializeObject(output)).toEqual(obj);
let subObjNum = {key1: 1, key2: 2};
let subObjNum2 = {key21: 21, key22: 22};
let obj2 = {key1: subObjNum, key2: subObjNum2};
const subObjNum = {key1: 1, key2: 2};
const subObjNum2 = {key21: 21, key22: 22};
const obj2 = {key1: subObjNum, key2: subObjNum2};
const output2 = makeObjectSerializable(obj2);
expect(output2).toEqual(obj2);
expect(deserializeObject(output2)).toEqual(obj2);
@@ -184,19 +184,19 @@ test('test makeObjectSerializable and deserializeObject function for custom Obje
});
test('test makeObjectSerializable and deserializeObject function for Array as input', () => {
let arr = [1, 2, 4, 5];
const arr = [1, 2, 4, 5];
const output = makeObjectSerializable(arr);
expect(output).toEqual(arr);
expect(deserializeObject(output)).toEqual(arr);
let arrMap = [
const arrMap = [
new Map([['a1', 'v1'], ['a2', 'v2']]),
new Map([['b1', 'v1'], ['b2', 'v2']]),
new Map([['c1', 'v1'], ['c2', 'v2']]),
new Map([['d1', 'v1'], ['d2', 'v2']]),
];
let expectedArr = [
const expectedArr = [
{
__flipper_object_type__: 'Map',
data: [['a1', 'v1'], ['a2', 'v2']],
@@ -218,7 +218,7 @@ test('test makeObjectSerializable and deserializeObject function for Array as in
expect(outputMap).toEqual(expectedArr);
expect(deserializeObject(outputMap)).toEqual(arrMap);
let arrStr = ['first', 'second', 'third', 'fourth'];
const arrStr = ['first', 'second', 'third', 'fourth'];
const outputStr = makeObjectSerializable(arrStr);
expect(outputStr).toEqual(arrStr);
expect(deserializeObject(outputStr)).toEqual(arrStr);

View File

@@ -70,8 +70,8 @@ export function processPluginStates(
devicePlugins: Map<string, Class<FlipperDevicePlugin<>>>,
): PluginStatesState {
let pluginStates = {};
for (let key in allPluginStates) {
let keyArray = key.split('#');
for (const key in allPluginStates) {
const keyArray = key.split('#');
const pluginName = keyArray.pop();
const filteredClients = clients.filter(client => {
// Remove the last entry related to plugin
@@ -94,7 +94,7 @@ export function processNotificationStates(
allActiveNotifications: Array<PluginNotification>,
devicePlugins: Map<string, Class<FlipperDevicePlugin<>>>,
): Array<PluginNotification> {
let activeNotifications = allActiveNotifications.filter(notif => {
const activeNotifications = allActiveNotifications.filter(notif => {
const filteredClients = clients.filter(client =>
notif.client ? client.id.includes(notif.client) : false,
);
@@ -176,7 +176,7 @@ export const processStore = async (
if (device) {
const {serial} = device;
const processedClients = processClients(clients, serial);
let processedPluginStates = processPluginStates(
const processedPluginStates = processPluginStates(
processedClients,
serial,
pluginStates,
@@ -210,7 +210,7 @@ export async function fetchMetadata(
const errorArray: Array<Error> = [];
const clients = store.getState().connections.clients;
const selectedDevice = store.getState().connections.selectedDevice;
for (let client of clients) {
for (const client of clients) {
if (
!selectedDevice ||
selectedDevice.isArchived ||
@@ -218,7 +218,7 @@ export async function fetchMetadata(
) {
continue;
}
for (let plugin of client.plugins) {
for (const plugin of client.plugins) {
const pluginClass: ?Class<
FlipperDevicePlugin<> | FlipperPlugin<>,
> = plugin ? pluginsMap.get(plugin) : null;

View File

@@ -22,7 +22,7 @@ async function exportMetrics(
pluginsMap: Map<string, Class<FlipperDevicePlugin<> | FlipperPlugin<>>>,
): Promise<string> {
const metrics: ExportMetricType = {};
for (let key in pluginStates) {
for (const key in pluginStates) {
const pluginStateData = pluginStates[key];
const arr = key.split('#');
const pluginName = arr.pop();

View File

@@ -46,12 +46,12 @@ export function getPersistedState<PersistedState>(
}
export function getActivePluginNames(plugins: PluginsState): Array<string> {
let pluginsMap: Map<
const pluginsMap: Map<
string,
Class<FlipperDevicePlugin<> | FlipperPlugin<>>,
> = pluginsClassMap(plugins);
let arr: Array<PluginDefinition> = plugins.disabledPlugins.concat(
const arr: Array<PluginDefinition> = plugins.disabledPlugins.concat(
plugins.gatekeepedPlugins,
);
arr.forEach((plugin: PluginDefinition) => {

View File

@@ -11,8 +11,8 @@ export default function promiseTimeout<T>(
timeoutMessage: ?string,
): Promise<T> | Promise<void> {
// Create a promise that rejects in <ms> milliseconds
let timeout = new Promise((resolve, reject) => {
let id = setTimeout(() => {
const timeout = new Promise((resolve, reject) => {
const id = setTimeout(() => {
clearTimeout(id);
reject(new Error(timeoutMessage || `Timed out in ${ms} ms.`));
}, ms);

View File

@@ -20,7 +20,7 @@ function processArray(
dict: Map<any, any>,
): {childNeedsIteration: boolean, outputArr: Array<any>} {
// Adds the array item to the stack if it needs to undergo iteration to serialise it. Otherwise it adds the serialized version of the item to the memoization dict
let outputArr = [];
const outputArr = [];
let childNeedsIteration = false;
for (const item of array) {
const isItemInstanceOfObject = item instanceof Object;
@@ -116,7 +116,7 @@ export function makeObjectSerializable(obj: any): any {
if (!(obj instanceof Object)) {
return obj;
}
let stack = [obj];
const stack = [obj];
const dict: Map<any, any> = new Map();
while (stack.length > 0) {
const element = stack[stack.length - 1];

View File

@@ -39,7 +39,7 @@ module.exports = async (
}
watchChanges(plugins, reloadCallback, pluginCache, options);
const dynamicPlugins = [];
for (let plugin of Object.values(plugins)) {
for (const plugin of Object.values(plugins)) {
const dynamicOptions = Object.assign(options, {force: false});
const compiledPlugin = await compilePlugin(
plugin,

View File

@@ -66,7 +66,7 @@ const argv = yargs
.help()
.parse(process.argv.slice(1));
let {config, configPath, flipperDir} = setup(argv);
const {config, configPath, flipperDir} = setup(argv);
const pluginPaths = config.pluginPaths
.concat(

View File

@@ -5,10 +5,10 @@
* @format
*/
let babylon = require('@babel/parser');
let fs = require('fs');
const babylon = require('@babel/parser');
const fs = require('fs');
let electronStubs = babylon.parseExpression(
const electronStubs = babylon.parseExpression(
fs.readFileSync('static/electron-stubs.notjs').toString(),
);