Stop using @electron/remote to obtain app.getPath() (#4078)

* Stop using remote to obtain app.getPath()

- Initialize entire map in bootstrap()

- Updated unit tests

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Resolve PR comments

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix test

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix build

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Ensure that init can only be called once and catch errors

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Replace basically all uses of app.getPath() with AppPaths.get()

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix unit tests

Signed-off-by: Sebastian Malton <sebastian@malton.name>
This commit is contained in:
Sebastian Malton authored and GitHub committed 2021-10-27 21:07:41 -04:00
1 parent 65b6908bf1
commit f297407156
45 files changed
+521 -200

No files matched your search

+12 -7
View File
@@ -36,8 +36,6 @@ import { ClusterStore } from "../common/cluster-store";
import { UserStore } from "../common/user-store";
import { ExtensionDiscovery } from "../extensions/extension-discovery";
import { ExtensionLoader } from "../extensions/extension-loader";
import { App } from "./components/app";
import { LensApp } from "./lens-app";
import { HelmRepoManager } from "../main/helm/helm-repo-manager";
import { ExtensionInstallationStateStore } from "./components/+extensions/extension-install.store";
import { DefaultProps } from "./mui-base-theme";
@@ -51,6 +49,7 @@ import { ThemeStore } from "./theme.store";
import { SentryInit } from "../common/sentry";
import { TerminalStore } from "./components/dock/terminal.store";
import cloudsMidnight from "./monaco-themes/Clouds Midnight.json";
import { AppPaths } from "../common/app-paths";
configurePackages();
@@ -69,7 +68,8 @@ type AppComponent = React.ComponentType & {
init?(rootElem: HTMLElement): Promise<void>;
};
export async function bootstrap(App: AppComponent) {
export async function bootstrap(comp: () => Promise<AppComponent>) {
await AppPaths.init();
const rootElem = document.getElementById("app");
await attachChromeDebugger();
@@ -124,9 +124,10 @@ export async function bootstrap(App: AppComponent) {
cs.registerIpcListener();
// init app's dependencies if any
if (App.init) {
await App.init(rootElem);
}
const App = await comp();
await App.init(rootElem);
render(<>
{isMac && <div id="draggable-top" />}
{DefaultProps(App)}
@@ -134,7 +135,11 @@ export async function bootstrap(App: AppComponent) {
}
// run
bootstrap(process.isMainFrame ? LensApp : App);
bootstrap(
async () => process.isMainFrame
? (await import("./lens-app")).LensApp
: (await import("./components/app")).App
);
/**
@@ -31,26 +31,30 @@ import { CatalogEntityRegistry } from "../../../renderer/api/catalog-entity-regi
import { CatalogEntityDetailRegistry } from "../../../extensions/registries";
import { CatalogEntityItem } from "./catalog-entity-item";
import { CatalogEntityStore } from "./catalog-entity.store";
import { AppPaths } from "../../../common/app-paths";
mockWindow();
jest.mock("electron", () => ({
app: {
getVersion: () => "99.99.99",
getName: () => "lens",
setName: jest.fn(),
setPath: jest.fn(),
getPath: () => "tmp",
getLocale: () => "en",
setLoginItemSettings: jest.fn(),
},
ipcMain: {
on: jest.fn(),
handle: jest.fn(),
},
}));
// avoid TypeError: Cannot read property 'getPath' of undefined
jest.mock("@electron/remote", () => {
return {
app: {
getPath: () => {
// avoid TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received undefined
return "";
},
},
};
});
AppPaths.init();
jest.mock("./hotbar-toggle-menu-item", () => {
return {
HotbarToggleMenuItem: () => <div>menu item</div>
};
});
jest.mock("./hotbar-toggle-menu-item", () => ({
HotbarToggleMenuItem: () => <div>menu item</div>
}));
class MockCatalogEntity extends CatalogEntity {
public apiVersion = "api";
+3 -3
View File
@@ -37,7 +37,7 @@ import { CatalogAddButton } from "./catalog-add-button";
import type { RouteComponentProps } from "react-router";
import { Notifications } from "../notifications";
import { MainLayout } from "../layout/main-layout";
import { createAppStorage, cssNames, prevDefault } from "../../utils";
import { createStorage, cssNames, prevDefault } from "../../utils";
import { makeCss } from "../../../common/utils/makeCss";
import { CatalogEntityDetails } from "./catalog-entity-details";
import { browseCatalogTab, catalogURL, CatalogViewRouteParam } from "../../../common/routes";
@@ -47,7 +47,7 @@ import { RenderDelay } from "../render-delay/render-delay";
import { Icon } from "../icon";
import { HotbarToggleMenuItem } from "./hotbar-toggle-menu-item";
export const previousActiveTab = createAppStorage("catalog-previous-active-tab", browseCatalogTab);
export const previousActiveTab = createStorage("catalog-previous-active-tab", browseCatalogTab);
enum sortBy {
name = "name",
@@ -74,7 +74,7 @@ export class Catalog extends React.Component<Props> {
this.catalogEntityStore = props.catalogEntityStore;
}
static defaultProps = {
catalogEntityStore: new CatalogEntityStore(),
catalogEntityStore: new CatalogEntityStore(),
};
get routeActiveTab(): string {
@@ -31,6 +31,7 @@ import { ExtensionInstallationStateStore } from "../extension-install.store";
import { Extensions } from "../extensions";
import mockFs from "mock-fs";
import { mockWindow } from "../../../../../__mocks__/windowMock";
import { AppPaths } from "../../../../common/app-paths";
mockWindow();
@@ -38,23 +39,39 @@ jest.setTimeout(30000);
jest.mock("fs-extra");
jest.mock("../../notifications");
jest.mock("../../../../common/utils", () => ({
...jest.requireActual<any>("../../../../common/utils"),
downloadFile: jest.fn(() => ({
promise: Promise.resolve()
jest.mock("../../../../common/utils/downloadFile", () => ({
downloadFile: jest.fn(({ url }) => ({
promise: Promise.resolve(),
url,
cancel: () => {},
})),
downloadJson: jest.fn(({ url }) => ({
promise: Promise.resolve({}),
url,
cancel: () => { },
})),
extractTar: jest.fn(() => Promise.resolve())
}));
jest.mock("../../../../common/utils/tar");
jest.mock("electron", () => ({
app: {
getVersion: () => "99.99.99",
getName: () => "lens",
setName: jest.fn(),
setPath: jest.fn(),
getPath: () => "tmp",
getLocale: () => "en",
setLoginItemSettings: (): void => void 0,
}
setLoginItemSettings: jest.fn(),
},
ipcMain: {
on: jest.fn(),
handle: jest.fn(),
},
}));
AppPaths.init();
describe("Extensions", () => {
beforeEach(async () => {
mockFs({
@@ -47,7 +47,7 @@ import { Notice } from "./notice";
import { SettingLayout } from "../layout/setting-layout";
import { docsUrl } from "../../../common/vars";
import { dialog } from "../../remote-helpers";
import { getPath } from "../../../common/utils/getPath";
import { AppPaths } from "../../../common/app-paths";
function getMessageFromError(error: any): string {
if (!error || typeof error !== "object") {
@@ -469,7 +469,7 @@ const supportedFormats = ["tar", "tgz"];
async function installFromSelectFileDialog() {
const { canceled, filePaths } = await dialog.showOpenDialog({
defaultPath: getPath("downloads"),
defaultPath: AppPaths.get("downloads"),
properties: ["openFile", "multiSelections"],
message: `Select extensions to install (formats: ${supportedFormats.join(", ")}), `,
buttonLabel: "Use configuration",
@@ -27,13 +27,26 @@ import selectEvent from "react-select-event";
import { Cluster } from "../../../../main/cluster";
import { DeleteClusterDialog } from "../delete-cluster-dialog";
import { AppPaths } from "../../../../common/app-paths";
jest.mock("electron", () => ({
app: {
getVersion: () => "99.99.99",
getName: () => "lens",
setName: jest.fn(),
setPath: jest.fn(),
getPath: () => "tmp",
getLocale: () => "en",
setLoginItemSettings: jest.fn(),
},
ipcMain: {
on: jest.fn(),
handle: jest.fn(),
},
}));
AppPaths.init();
const kubeconfig = `
apiVersion: v1
clusters:
@@ -30,6 +30,7 @@ import { noop } from "../../../utils";
import { ThemeStore } from "../../../theme.store";
import { TerminalStore } from "../terminal.store";
import { UserStore } from "../../../../common/user-store";
import { AppPaths } from "../../../../common/app-paths";
jest.mock("react-monaco-editor", () => ({
monaco: {
@@ -41,9 +42,20 @@ jest.mock("react-monaco-editor", () => ({
jest.mock("electron", () => ({
app: {
getVersion: () => "99.99.99",
getName: () => "lens",
setName: jest.fn(),
setPath: jest.fn(),
getPath: () => "tmp",
getLocale: () => "en",
setLoginItemSettings: jest.fn(),
},
ipcMain: {
on: jest.fn(),
handle: jest.fn(),
},
}));
AppPaths.init();
const initialTabs: DockTab[] = [
{ id: "terminal", kind: TabKind.TERMINAL, title: "Terminal", pinned: false, },
@@ -31,15 +31,28 @@ import { dockerPod, deploymentPod1 } from "./pod.mock";
import { ThemeStore } from "../../../theme.store";
import { UserStore } from "../../../../common/user-store";
import mockFs from "mock-fs";
import { AppPaths } from "../../../../common/app-paths";
jest.mock("react-monaco-editor", () => null);
jest.mock("electron", () => ({
app: {
getVersion: () => "99.99.99",
getName: () => "lens",
setName: jest.fn(),
setPath: jest.fn(),
getPath: () => "tmp",
getLocale: () => "en",
setLoginItemSettings: jest.fn(),
},
ipcMain: {
on: jest.fn(),
handle: jest.fn(),
},
}));
AppPaths.init();
const getComponent = (tabData: LogTabData) => {
return (
<LogResourceSelector
@@ -28,6 +28,7 @@ import { logTabStore } from "../log-tab.store";
import { deploymentPod1, deploymentPod2, deploymentPod3, dockerPod } from "./pod.mock";
import fse from "fs-extra";
import { mockWindow } from "../../../../../__mocks__/windowMock";
import { AppPaths } from "../../../../common/app-paths";
mockWindow();
@@ -35,10 +36,22 @@ jest.mock("react-monaco-editor", () => null);
jest.mock("electron", () => ({
app: {
getVersion: () => "99.99.99",
getName: () => "lens",
setName: jest.fn(),
setPath: jest.fn(),
getPath: () => "tmp",
getLocale: () => "en",
setLoginItemSettings: jest.fn(),
},
ipcMain: {
on: jest.fn(),
handle: jest.fn(),
},
}));
AppPaths.init();
podsStore.items.push(new Pod(dockerPod));
podsStore.items.push(new Pod(deploymentPod1));
podsStore.items.push(new Pod(deploymentPod2));
@@ -27,14 +27,26 @@ import { ThemeStore } from "../../../theme.store";
import { UserStore } from "../../../../common/user-store";
import { Notifications } from "../../notifications";
import mockFs from "mock-fs";
import { AppPaths } from "../../../../common/app-paths";
jest.mock("electron", () => ({
app: {
getVersion: () => "99.99.99",
getName: () => "lens",
setName: jest.fn(),
setPath: jest.fn(),
getPath: () => "tmp",
getLocale: () => "en",
setLoginItemSettings: jest.fn(),
},
ipcMain: {
on: jest.fn(),
handle: jest.fn(),
},
}));
AppPaths.init();
const mockHotbars: {[id: string]: any} = {
"1": {
id: "1",
+27 -35
View File
@@ -26,7 +26,6 @@ import { comparer, observable, reaction, toJS, when } from "mobx";
import fse from "fs-extra";
import { StorageHelper } from "./storageHelper";
import logger from "../../main/logger";
import { getHostedClusterId, getPath } from "../../common/utils";
import { isTestEnv } from "../../common/vars";
const storage = observable({
@@ -37,55 +36,48 @@ const storage = observable({
/**
* Creates a helper for saving data under the "key" intended for window.localStorage
* @param key
* @param defaultValue
* @param key The descriptor of the data
* @param defaultValue The default value of the data, must be JSON serializable
*/
export function createStorage<T>(key: string, defaultValue: T) {
return createAppStorage(key, defaultValue, getHostedClusterId());
}
export function createAppStorage<T>(key: string, defaultValue: T, clusterId?: string | undefined) {
const { logPrefix } = StorageHelper;
const folder = path.resolve(getPath("userData"), "lens-local-storage");
const fileName = `${clusterId ?? "app"}.json`;
const filePath = path.resolve(folder, fileName);
if (!storage.initialized) {
init(); // called once per cluster-view
}
function init() {
storage.initialized = true;
// read previously saved state (if any)
fse.readJson(filePath)
.then(data => storage.data = data)
.catch(() => null) // ignore empty / non-existing / invalid json files
.finally(() => {
(async () => {
const filePath = await StorageHelper.getLocalStoragePath();
try {
storage.data = await fse.readJson(filePath);
} catch {} finally {
if (!isTestEnv) {
logger.info(`${logPrefix} loading finished for ${filePath}`);
}
storage.loaded = true;
}
// bind auto-saving data changes to %storage-file.json
reaction(() => toJS(storage.data), saveFile, {
delay: 250, // lazy, avoid excessive writes to fs
equals: comparer.structural, // save only when something really changed
});
// bind auto-saving data changes to %storage-file.json
reaction(() => toJS(storage.data), saveFile, {
delay: 250, // lazy, avoid excessive writes to fs
equals: comparer.structural, // save only when something really changed
});
async function saveFile(state: Record<string, any> = {}) {
logger.info(`${logPrefix} saving ${filePath}`);
async function saveFile(state: Record<string, any> = {}) {
logger.info(`${logPrefix} saving ${filePath}`);
try {
await fse.ensureDir(folder, { mode: 0o755 });
await fse.writeJson(filePath, state, { spaces: 2 });
} catch (error) {
logger.error(`${logPrefix} saving failed: ${error}`, {
json: state, jsonFilePath: filePath
});
try {
await fse.ensureDir(path.dirname(filePath), { mode: 0o755 });
await fse.writeJson(filePath, state, { spaces: 2 });
} catch (error) {
logger.error(`${logPrefix} saving failed: ${error}`, {
json: state, jsonFilePath: filePath
});
}
}
}
})()
.catch(error => logger.error(`${logPrefix} Failed to initialize storage: ${error}`));
}
return new StorageHelper<T>(key, {
+7
View File
@@ -24,6 +24,9 @@ import { action, comparer, makeObservable, observable, toJS, when, } from "mobx"
import produce, { Draft, isDraft } from "immer";
import { isEqual, isPlainObject } from "lodash";
import logger from "../../main/logger";
import { getHostedClusterId } from "../../common/utils";
import path from "path";
import { AppPaths } from "../../common/app-paths";
export interface StorageAdapter<T> {
[metadata: string]: any;
@@ -40,6 +43,10 @@ export interface StorageHelperOptions<T> {
}
export class StorageHelper<T> {
static async getLocalStoragePath() {
return path.resolve(await AppPaths.getAsync("userData"), "lens-local-storage", `${getHostedClusterId() || "app"}.json`);
}
static logPrefix = "[StorageHelper]:";
readonly storage: StorageAdapter<T>;