Clean up versioning and packageJson uses (#6196)

This commit is contained in:
Sebastian Malton authored and GitHub committed 2022-09-15 17:20:58 -04:00
1 parent cfe35ded90
commit 67ac1692b2
116 files changed
+1154 -644

No files matched your search

@@ -1,22 +0,0 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import isDevelopmentInjectable from "../../../common/vars/is-development.injectable";
import productNameInjectable from "./product-name.injectable";
const appNameInjectable = getInjectable({
id: "app-name",
instantiate: (di) => {
const isDevelopment = di.inject(isDevelopmentInjectable);
const productName = di.inject(productNameInjectable);
return `${productName}${isDevelopment ? "Dev" : ""}`;
},
causesSideEffects: true,
});
export default appNameInjectable;
@@ -6,7 +6,6 @@ import { getInjectable } from "@ogre-tools/injectable";
import type { AppPaths } from "../../common/app-paths/app-path-injection-token";
import getElectronAppPathInjectable from "./get-electron-app-path/get-electron-app-path.injectable";
import setElectronAppPathInjectable from "./set-electron-app-path/set-electron-app-path.injectable";
import appNameInjectable from "./app-name/app-name.injectable";
import directoryForIntegrationTestingInjectable from "./directory-for-integration-testing/directory-for-integration-testing.injectable";
import appPathsStateInjectable from "../../common/app-paths/app-paths-state.injectable";
import { pathNames } from "../../common/app-paths/app-path-names";
@@ -14,6 +13,7 @@ import { fromPairs, map } from "lodash/fp";
import { pipeline } from "@ogre-tools/fp";
import joinPathsInjectable from "../../common/path/join-paths.injectable";
import { beforeElectronIsReadyInjectionToken } from "../start-main-application/runnable-tokens/before-electron-is-ready-injection-token";
import appNameInjectable from "../../common/vars/app-name.injectable";
const setupAppPathsInjectable = getInjectable({
id: "setup-app-paths",
@@ -9,7 +9,7 @@ import asyncFn from "@async-fn/jest";
import type { AppUpdater, UpdateCheckResult } from "electron-updater";
import type { CheckForPlatformUpdates } from "./check-for-platform-updates.injectable";
import checkForPlatformUpdatesInjectable from "./check-for-platform-updates.injectable";
import type { UpdateChannel, UpdateChannelId } from "../../../common/application-update/update-channels";
import type { UpdateChannel, ReleaseChannel } from "../../../common/application-update/update-channels";
import { getPromiseStatus } from "../../../common/test-utils/get-promise-status";
import loggerInjectable from "../../../common/logger.injectable";
import type { Logger } from "../../../common/logger";
@@ -47,7 +47,7 @@ describe("check-for-platform-updates", () => {
beforeEach(() => {
const testUpdateChannel: UpdateChannel = {
id: "some-update-channel" as UpdateChannelId,
id: "some-update-channel" as ReleaseChannel,
label: "Some update channel",
moreStableUpdateChannel: null,
};
@@ -6,14 +6,14 @@ import { getInjectable } from "@ogre-tools/injectable";
import { afterApplicationIsLoadedInjectionToken } from "../start-main-application/runnable-tokens/after-application-is-loaded-injection-token";
import emitEventInjectable from "../../common/app-event-bus/emit-event.injectable";
import { getCurrentDateTime } from "../../common/utils/date/get-current-date-time";
import appVersionInjectable from "../../common/vars/app-version.injectable";
import buildVersionInjectable from "../vars/build-version/build-version.injectable";
const emitCurrentVersionToAnalyticsInjectable = getInjectable({
id: "emit-current-version-to-analytics",
instantiate: (di) => {
const emitEvent = di.inject(emitEventInjectable);
const appVersion = di.inject(appVersionInjectable);
const buildVersion = di.inject(buildVersionInjectable);
return {
run: () => {
@@ -22,7 +22,7 @@ const emitCurrentVersionToAnalyticsInjectable = getInjectable({
action: "current-version",
params: {
version: appVersion,
version: buildVersion.get(),
currentDateTime: getCurrentDateTime(),
},
});
@@ -3,18 +3,11 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import packageJsonInjectable from "../../common/vars/package-json.injectable";
import { has } from "lodash/fp";
import applicationInformationInjectable from "../../common/vars/application-information.injectable";
// TOOO: Rename to something less technical
const publishIsConfiguredInjectable = getInjectable({
id: "publish-is-configured",
instantiate: (di) => {
const packageJson = di.inject(packageJsonInjectable);
return has("build.publish", packageJson);
},
instantiate: (di) => Boolean(di.inject(applicationInformationInjectable).build.publish?.length),
});
export default publishIsConfiguredInjectable;
@@ -0,0 +1,23 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import { requestChannelListenerInjectionToken } from "../../common/utils/channel/request-channel-listener-injection-token";
import { buildVersionChannel } from "../../common/vars/build-semantic-version.injectable";
import buildVersionInjectable from "../vars/build-version/build-version.injectable";
const setupBuildVersionRequestChannelInjectable = getInjectable({
id: "setup-build-version-request-channel",
instantiate: (di) => {
const buildVersion = di.inject(buildVersionInjectable);
return {
channel: buildVersionChannel,
handler: () => buildVersion.get(),
};
},
injectionToken: requestChannelListenerInjectionToken,
});
export default setupBuildVersionRequestChannelInjectable;
@@ -4,6 +4,8 @@
*/
import { getGlobalOverride } from "../../common/test-utils/get-global-override";
import buildVersionInjectable from "./build-version.injectable";
import electronAppInjectable from "./electron-app.injectable";
export default getGlobalOverride(buildVersionInjectable, () => "6.0.0");
export default getGlobalOverride(electronAppInjectable, () => ({
getVersion: () => "6.0.0",
} as Electron.App));
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import appNameInjectable from "../../app-paths/app-name/app-name.injectable";
import appNameInjectable from "../../../common/vars/app-name.injectable";
import { beforeElectronIsReadyInjectionToken } from "../../start-main-application/runnable-tokens/before-electron-is-ready-injection-token";
import electronAppInjectable from "../electron-app.injectable";
-9
View File
@@ -7,7 +7,6 @@ import { kebabCase, noop, chunk } from "lodash/fp";
import type { DiContainer, Injectable } from "@ogre-tools/injectable";
import { createContainer } from "@ogre-tools/injectable";
import { Environments, setLegacyGlobalDiForExtensionApi } from "../extensions/as-legacy-globals-for-extension-api/legacy-global-di-for-extension-api";
import appNameInjectable from "./app-paths/app-name/app-name.injectable";
import writeJsonFileInjectable from "../common/fs/write-json-file.injectable";
import readJsonFileInjectable from "../common/fs/read-json-file.injectable";
import readFileInjectable from "../common/fs/read-file.injectable";
@@ -33,7 +32,6 @@ import lensResourcesDirInjectable from "../common/vars/lens-resources-dir.inject
import environmentVariablesInjectable from "../common/utils/environment-variables.injectable";
import setupIpcMainHandlersInjectable from "./electron-app/runnables/setup-ipc-main-handlers/setup-ipc-main-handlers.injectable";
import setupLensProxyInjectable from "./start-main-application/runnables/setup-lens-proxy.injectable";
import setupSentryInjectable from "./start-main-application/runnables/setup-sentry.injectable";
import setupShellInjectable from "./start-main-application/runnables/setup-shell.injectable";
import setupSyncingOfWeblinksInjectable from "./start-main-application/runnables/setup-syncing-of-weblinks.injectable";
import stopServicesAndExitAppInjectable from "./stop-services-and-exit-app.injectable";
@@ -63,7 +61,6 @@ import broadcastMessageInjectable from "../common/ipc/broadcast-message.injectab
import getElectronThemeInjectable from "./electron-app/features/get-electron-theme.injectable";
import syncThemeFromOperatingSystemInjectable from "./electron-app/features/sync-theme-from-operating-system.injectable";
import platformInjectable from "../common/vars/platform.injectable";
import productNameInjectable from "./app-paths/app-name/product-name.injectable";
import electronQuitAndInstallUpdateInjectable from "./electron-app/features/electron-quit-and-install-update.injectable";
import electronUpdaterIsActiveInjectable from "./electron-app/features/electron-updater-is-active.injectable";
import publishIsConfiguredInjectable from "./application-update/publish-is-configured.injectable";
@@ -73,7 +70,6 @@ import setUpdateOnQuitInjectable from "./electron-app/features/set-update-on-qui
import downloadPlatformUpdateInjectable from "./application-update/download-platform-update/download-platform-update.injectable";
import startCatalogSyncInjectable from "./catalog-sync-to-renderer/start-catalog-sync.injectable";
import startKubeConfigSyncInjectable from "./start-main-application/runnables/kube-config-sync/start-kube-config-sync.injectable";
import appVersionInjectable from "../common/vars/app-version.injectable";
import getRandomIdInjectable from "../common/utils/get-random-id.injectable";
import periodicalCheckForUpdatesInjectable from "./application-update/periodical-check-for-updates/periodical-check-for-updates.injectable";
import execFileInjectable from "../common/fs/exec-file.injectable";
@@ -148,9 +144,6 @@ export function getDiForUnitTesting(opts: { doGeneralOverrides?: boolean } = {})
di.override(environmentVariablesInjectable, () => ({}));
di.override(commandLineArgumentsInjectable, () => []);
di.override(productNameInjectable, () => "some-product-name");
di.override(appVersionInjectable, () => "1.0.0");
di.override(clusterFramesInjectable, () => observable.map<string, ClusterFrameInfo>());
di.override(stopServicesAndExitAppInjectable, () => () => {});
@@ -179,7 +172,6 @@ export function getDiForUnitTesting(opts: { doGeneralOverrides?: boolean } = {})
// TODO: Remove usages of globally exported appEventBus to get rid of this
di.override(appEventBusInjectable, () => new EventEmitter<[AppEvent]>());
di.override(appNameInjectable, () => "some-app-name");
di.override(broadcastMessageInjectable, () => (channel) => {
throw new Error(`Tried to broadcast message to channel "${channel}" over IPC without explicit override.`);
});
@@ -210,7 +202,6 @@ const overrideRunnablesHavingSideEffects = (di: DiContainer) => {
initializeExtensionsInjectable,
setupIpcMainHandlersInjectable,
setupLensProxyInjectable,
setupSentryInjectable,
setupShellInjectable,
setupSyncingOfWeblinksInjectable,
setupSystemCaInjectable,
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import { getBundledKubectlVersion } from "../../common/utils";
import bundledKubectlVersionInjectable from "../../common/vars/bundled-kubectl-version.injectable";
import createKubectlInjectable from "./create-kubectl.injectable";
const bundledKubectlInjectable = getInjectable({
@@ -11,8 +11,7 @@ const bundledKubectlInjectable = getInjectable({
instantiate: (di) => {
const createKubectl = di.inject(createKubectlInjectable);
const bundledKubectlVersion = getBundledKubectlVersion();
const bundledKubectlVersion = di.inject(bundledKubectlVersionInjectable);
return createKubectl(bundledKubectlVersion);
},
@@ -12,6 +12,8 @@ import normalizedPlatformInjectable from "../../common/vars/normalized-platform.
import kubectlBinaryNameInjectable from "./binary-name.injectable";
import bundledKubectlBinaryPathInjectable from "./bundled-binary-path.injectable";
import baseBundledBinariesDirectoryInjectable from "../../common/vars/base-bundled-binaries-dir.injectable";
import bundledKubectlVersionInjectable from "../../common/vars/bundled-kubectl-version.injectable";
import kubectlVersionMapInjectable from "./version-map.injectable";
const createKubectlInjectable = getInjectable({
id: "create-kubectl",
@@ -25,6 +27,8 @@ const createKubectlInjectable = getInjectable({
kubectlBinaryName: di.inject(kubectlBinaryNameInjectable),
bundledKubectlBinaryPath: di.inject(bundledKubectlBinaryPathInjectable),
baseBundeledBinariesDirectory: di.inject(baseBundledBinariesDirectoryInjectable),
bundledKubectlVersion: di.inject(bundledKubectlVersionInjectable),
kubectlVersionMap: di.inject(kubectlVersionMapInjectable),
};
return (clusterVersion: string) => new Kubectl(dependencies, clusterVersion);
+5 -25
View File
@@ -9,7 +9,6 @@ import { promiseExecFile } from "../../common/utils/promise-exec";
import logger from "../logger";
import { ensureDir, pathExists } from "fs-extra";
import * as lockFile from "proper-lockfile";
import { getBundledKubectlVersion } from "../../common/utils/app-version";
import { SemVer } from "semver";
import { defaultPackageMirror, packageMirrors } from "../../common/user-store/preferences-helpers";
import got from "got/dist/source";
@@ -17,26 +16,6 @@ import { promisify } from "util";
import stream from "stream";
import { noop } from "lodash/fp";
const bundledVersion = getBundledKubectlVersion();
const kubectlMap: Map<string, string> = new Map([
["1.7", "1.8.15"],
["1.8", "1.9.10"],
["1.9", "1.10.13"],
["1.10", "1.11.10"],
["1.11", "1.12.10"],
["1.12", "1.13.12"],
["1.13", "1.13.12"],
["1.14", "1.14.10"],
["1.15", "1.15.11"],
["1.16", "1.16.15"],
["1.17", "1.17.17"],
["1.18", "1.18.20"],
["1.19", "1.19.12"],
["1.20", "1.20.8"],
["1.21", "1.21.9"],
["1.22", "1.22.6"],
["1.23", bundledVersion],
]);
const initScriptVersionString = "# lens-initscript v3";
export interface KubectlDependencies {
@@ -52,6 +31,8 @@ export interface KubectlDependencies {
readonly downloadKubectlBinaries: boolean;
readonly downloadMirror: string;
};
readonly bundledKubectlVersion: string;
readonly kubectlVersionMap: Map<string, string>;
}
export class Kubectl {
@@ -60,7 +41,6 @@ export class Kubectl {
protected readonly path: string;
protected readonly dirname: string;
public static readonly bundledKubectlVersion = bundledVersion;
public static invalidBundle = false;
constructor(protected readonly dependencies: KubectlDependencies, clusterVersion: string) {
@@ -69,10 +49,10 @@ export class Kubectl {
try {
version = new SemVer(clusterVersion);
} catch {
version = new SemVer(Kubectl.bundledKubectlVersion);
version = new SemVer(this.dependencies.bundledKubectlVersion);
}
const fromMajorMinor = kubectlMap.get(`${version.major}.${version.minor}`);
const fromMajorMinor = this.dependencies.kubectlVersionMap.get(`${version.major}.${version.minor}`);
/**
* minorVersion is the first two digits of kube server version if the version map includes that,
@@ -189,7 +169,7 @@ export class Kubectl {
}
protected async checkBundled(): Promise<boolean> {
if (this.kubectlVersion === Kubectl.bundledKubectlVersion) {
if (this.kubectlVersion === this.dependencies.bundledKubectlVersion) {
try {
const exist = await pathExists(this.path);
@@ -0,0 +1,35 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import bundledKubectlVersionInjectable from "../../common/vars/bundled-kubectl-version.injectable";
const kubectlVersionMapInjectable = getInjectable({
id: "kubectl-version-map",
instantiate: (di) => {
const bundledKubectlVersion = di.inject(bundledKubectlVersionInjectable);
return new Map([
["1.7", "1.8.15"],
["1.8", "1.9.10"],
["1.9", "1.10.13"],
["1.10", "1.11.10"],
["1.11", "1.12.10"],
["1.12", "1.13.12"],
["1.13", "1.13.12"],
["1.14", "1.14.10"],
["1.15", "1.15.11"],
["1.16", "1.16.15"],
["1.17", "1.17.17"],
["1.18", "1.18.20"],
["1.19", "1.19.12"],
["1.20", "1.20.8"],
["1.21", "1.21.9"],
["1.22", "1.22.6"],
["1.23", bundledKubectlVersion],
]);
},
});
export default kubectlVersionMapInjectable;
+10 -16
View File
@@ -10,26 +10,20 @@ import httpProxy from "http-proxy";
import clusterManagerInjectable from "../cluster-manager.injectable";
import shellApiRequestInjectable from "./proxy-functions/shell-api-request/shell-api-request.injectable";
import lensProxyPortInjectable from "./lens-proxy-port.injectable";
import contentSecurityPolicyInjectable from "../../common/vars/content-security-policy.injectable";
const lensProxyInjectable = getInjectable({
id: "lens-proxy",
instantiate: (di) => {
const clusterManager = di.inject(clusterManagerInjectable);
const router = di.inject(routerInjectable);
const shellApiRequest = di.inject(shellApiRequestInjectable);
const proxy = httpProxy.createProxy();
const lensProxyPort = di.inject(lensProxyPortInjectable);
return new LensProxy({
router,
proxy,
kubeApiUpgradeRequest,
shellApiRequest,
getClusterForRequest: clusterManager.getClusterForRequest,
lensProxyPort,
});
},
instantiate: (di) => new LensProxy({
router: di.inject(routerInjectable),
proxy: httpProxy.createProxy(),
kubeApiUpgradeRequest,
shellApiRequest: di.inject(shellApiRequestInjectable),
getClusterForRequest: di.inject(clusterManagerInjectable).getClusterForRequest,
lensProxyPort: di.inject(lensProxyPortInjectable),
contentSecurityPolicy: di.inject(contentSecurityPolicyInjectable),
}),
});
export default lensProxyInjectable;
+7 -9
View File
@@ -7,7 +7,7 @@ import net from "net";
import type http from "http";
import spdy from "spdy";
import type httpProxy from "http-proxy";
import { apiPrefix, apiKubePrefix, contentSecurityPolicy } from "../../common/vars";
import { apiPrefix, apiKubePrefix } from "../../common/vars";
import type { Router } from "../router/router";
import type { ClusterContextHandler } from "../context-handler/context-handler";
import logger from "../logger";
@@ -26,9 +26,10 @@ interface Dependencies {
getClusterForRequest: GetClusterForRequest;
shellApiRequest: (args: ProxyApiRequestArgs) => void | Promise<void>;
kubeApiUpgradeRequest: (args: ProxyApiRequestArgs) => void | Promise<void>;
router: Router;
proxy: httpProxy;
lensProxyPort: { set: (portNumber: number) => void };
readonly router: Router;
readonly proxy: httpProxy;
readonly lensProxyPort: { set: (portNumber: number) => void };
readonly contentSecurityPolicy: string;
}
const watchParam = "watch";
@@ -63,7 +64,7 @@ export class LensProxy {
protected closed = false;
protected retryCounters = new Map<string, number>();
constructor(private dependencies: Dependencies) {
constructor(private readonly dependencies: Dependencies) {
this.configureProxy(dependencies.proxy);
this.proxyServer = spdy.createServer({
@@ -239,10 +240,7 @@ export class LensProxy {
}
}
if (contentSecurityPolicy) {
res.setHeader("Content-Security-Policy", contentSecurityPolicy);
}
res.setHeader("Content-Security-Policy", this.dependencies.contentSecurityPolicy);
this.dependencies.router.route(cluster, req, res);
}
}
@@ -3,12 +3,11 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import { docsUrl, productName, supportUrl } from "../../common/vars";
import { docsUrl, supportUrl } from "../../common/vars";
import { broadcastMessage } from "../../common/ipc";
import type { MenuItemConstructorOptions } from "electron";
import { webContents } from "electron";
import loggerInjectable from "../../common/logger.injectable";
import appNameInjectable from "../app-paths/app-name/app-name.injectable";
import electronMenuItemsInjectable from "./electron-menu-items.injectable";
import updatingIsEnabledInjectable from "../application-update/updating-is-enabled.injectable";
import navigateToPreferencesInjectable from "../../common/front-end-routing/routes/preferences/navigate-to-preferences.injectable";
@@ -24,6 +23,8 @@ import reloadCurrentApplicationWindowInjectable from "../start-main-application/
import showApplicationWindowInjectable from "../start-main-application/lens-window/show-application-window.injectable";
import processCheckingForUpdatesInjectable from "../application-update/check-for-updates/process-checking-for-updates.injectable";
import openLinkInBrowserInjectable from "../../common/utils/open-link-in-browser.injectable";
import appNameInjectable from "../../common/vars/app-name.injectable";
import productNameInjectable from "../../common/vars/product-name.injectable";
function ignoreIf(check: boolean, menuItems: MenuItemOpts[]) {
return check ? [] : menuItems;
@@ -39,6 +40,7 @@ const applicationMenuItemsInjectable = getInjectable({
instantiate: (di) => {
const logger = di.inject(loggerInjectable);
const appName = di.inject(appNameInjectable);
const productName = di.inject(productNameInjectable);
const isMac = di.inject(isMacInjectable);
const updatingIsEnabled = di.inject(updatingIsEnabledInjectable);
const electronMenuItems = di.inject(electronMenuItemsInjectable);
-13
View File
@@ -1,13 +0,0 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import electronAppInjectable from "../electron-app/electron-app.injectable";
const buildVersionInjectable = getInjectable({
id: "build-version",
instantiate: (di) => di.inject(electronAppInjectable).getVersion(),
});
export default buildVersionInjectable;
-26
View File
@@ -3,36 +3,10 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { Menu } from "electron";
import { appName, isWindows, productName } from "../../common/vars";
import packageJson from "../../../package.json";
import type { MenuItemOpts } from "./application-menu-items.injectable";
import type { ShowMessagePopup } from "../electron-app/features/show-message-popup.injectable";
export type MenuTopId = "mac" | "file" | "edit" | "view" | "help";
interface Dependencies {
appVersion: string;
extensionApiVersion: string;
showMessagePopup: ShowMessagePopup;
}
export const showAbout = ({ showMessagePopup, extensionApiVersion, appVersion }: Dependencies) => async () => {
const appInfo = [
`${appName}: ${appVersion}`,
`Extension API: ${extensionApiVersion}`,
`Electron: ${process.versions.electron}`,
`Chrome: ${process.versions.chrome}`,
`Node: ${process.versions.node}`,
packageJson.copyright,
];
await showMessagePopup(
`${isWindows ? " ".repeat(2) : ""}${appName}`,
productName,
appInfo.join("\r\n"),
);
};
export function buildMenu(applicationMenuItems: MenuItemOpts[]) {
Menu.setApplicationMenu(
Menu.buildFromTemplate(applicationMenuItems),
+32 -9
View File
@@ -3,20 +3,43 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import { showAbout } from "./menu";
import showMessagePopupInjectable from "../electron-app/features/show-message-popup.injectable";
import appVersionInjectable from "../../common/vars/app-version.injectable";
import buildVersionInjectable from "./build-version.injectable";
import isWindowsInjectable from "../../common/vars/is-windows.injectable";
import appNameInjectable from "../../common/vars/app-name.injectable";
import productNameInjectable from "../../common/vars/product-name.injectable";
import buildVersionInjectable from "../vars/build-version/build-version.injectable";
import extensionApiVersionInjectable from "../../common/vars/extension-api-version.injectable";
import applicationCopyrightInjectable from "../../common/vars/application-copyright.injectable";
const showAboutInjectable = getInjectable({
id: "show-about",
instantiate: (di) =>
showAbout({
appVersion: di.inject(buildVersionInjectable),
extensionApiVersion: di.inject(appVersionInjectable),
showMessagePopup: di.inject(showMessagePopupInjectable),
}),
instantiate: (di) => {
const buildVersion = di.inject(buildVersionInjectable);
const extensionApiVersion = di.inject(extensionApiVersionInjectable);
const showMessagePopup = di.inject(showMessagePopupInjectable);
const isWindows = di.inject(isWindowsInjectable);
const appName = di.inject(appNameInjectable);
const productName = di.inject(productNameInjectable);
const applicationCopyright = di.inject(applicationCopyrightInjectable);
return () => {
const appInfo = [
`${appName}: ${buildVersion.get()}`,
`Extension API: ${extensionApiVersion}`,
`Electron: ${process.versions.electron}`,
`Chrome: ${process.versions.chrome}`,
`Node: ${process.versions.node}`,
applicationCopyright,
];
showMessagePopup(
`${isWindows ? " ".repeat(2) : ""}${appName}`,
productName,
appInfo.join("\r\n"),
);
};
},
});
export default showAboutInjectable;
+54 -39
View File
@@ -6,7 +6,7 @@ import type { SupportedFileExtension } from "../router/router-content-types";
import { contentTypes } from "../router/router-content-types";
import logger from "../logger";
import { getRouteInjectable } from "../router/router.injectable";
import { appName, publicPath } from "../../common/vars";
import { publicPath } from "../../common/vars";
import path from "path";
import isDevelopmentInjectable from "../../common/vars/is-development.injectable";
import httpProxy from "http-proxy";
@@ -19,66 +19,78 @@ import { webpackDevServerPort } from "../../../webpack/vars";
import type { LensApiRequest, RouteResponse } from "../router/route";
import { route } from "../router/route";
import staticFilesDirectoryInjectable from "../../common/vars/static-files-directory.injectable";
import appNameInjectable from "../../common/vars/app-name.injectable";
interface ProductionDependencies {
readFileBuffer: (path: string) => Promise<Buffer>;
getAbsolutePath: GetAbsolutePath;
joinPaths: JoinPaths;
staticFilesDirectory: string;
appName: string;
}
const handleStaticFileInProduction =
({ readFileBuffer, getAbsolutePath, joinPaths, staticFilesDirectory }: ProductionDependencies) =>
async ({ params }: LensApiRequest<"/{path*}">): Promise<RouteResponse<Buffer>> => {
let filePath = params.path;
const handleStaticFileInProduction = ({
readFileBuffer,
getAbsolutePath,
joinPaths,
staticFilesDirectory,
appName,
}: ProductionDependencies) => (
async ({ params }: LensApiRequest<"/{path*}">): Promise<RouteResponse<Buffer>> => {
let filePath = params.path;
for (let retryCount = 0; retryCount < 5; retryCount += 1) {
const asset = joinPaths(staticFilesDirectory, filePath);
const normalizedFilePath = getAbsolutePath(asset);
for (let retryCount = 0; retryCount < 5; retryCount += 1) {
const asset = joinPaths(staticFilesDirectory, filePath);
const normalizedFilePath = getAbsolutePath(asset);
if (!normalizedFilePath.startsWith(staticFilesDirectory)) {
return { statusCode: 404 };
}
try {
const fileExtension = path
.extname(asset)
.slice(1) as SupportedFileExtension;
const contentType = contentTypes[fileExtension] || contentTypes.txt;
return { response: await readFileBuffer(asset), contentType };
} catch (err) {
if (retryCount > 5) {
logger.error("handleStaticFile:", String(err));
if (!normalizedFilePath.startsWith(staticFilesDirectory)) {
return { statusCode: 404 };
}
try {
const fileExtension = path
.extname(asset)
.slice(1) as SupportedFileExtension;
const contentType = contentTypes[fileExtension] || contentTypes.txt;
return { response: await readFileBuffer(asset), contentType };
} catch (err) {
if (retryCount > 5) {
logger.error("handleStaticFile:", String(err));
return { statusCode: 404 };
}
filePath = `${publicPath}/${appName}.html`;
}
filePath = `${publicPath}/${appName}.html`;
}
}
return { statusCode: 404 };
};
return { statusCode: 404 };
}
);
interface DevelopmentDependencies {
proxy: httpProxy;
appName: string;
}
const handleStaticFileInDevelopment =
({ proxy }: DevelopmentDependencies) =>
({ raw: { req, res }}: LensApiRequest<"/{path*}">): RouteResponse<Buffer> => {
if (req.url === "/" || !req.url?.startsWith("/build/")) {
req.url = `${publicPath}/${appName}.html`;
}
const handleStaticFileInDevelopment = ({
proxy,
appName,
}: DevelopmentDependencies) => (
({ raw: { req, res }}: LensApiRequest<"/{path*}">): RouteResponse<Buffer> => {
if (req.url === "/" || !req.url?.startsWith("/build/")) {
req.url = `${publicPath}/${appName}.html`;
}
proxy.web(req, res, {
target: `http://127.0.0.1:${webpackDevServerPort}`,
});
proxy.web(req, res, {
target: `http://127.0.0.1:${webpackDevServerPort}`,
});
return { proxy };
};
return { proxy };
}
);
const staticFileRouteInjectable = getRouteInjectable({
id: "static-file-route",
@@ -89,6 +101,7 @@ const staticFileRouteInjectable = getRouteInjectable({
const getAbsolutePath = di.inject(getAbsolutePathInjectable);
const joinPaths = di.inject(joinPathsInjectable);
const staticFilesDirectory = di.inject(staticFilesDirectoryInjectable);
const appName = di.inject(appNameInjectable);
return route({
method: "get",
@@ -97,12 +110,14 @@ const staticFileRouteInjectable = getRouteInjectable({
isDevelopment
? handleStaticFileInDevelopment({
proxy: httpProxy.createProxy(),
appName,
})
: handleStaticFileInProduction({
readFileBuffer,
getAbsolutePath,
joinPaths,
staticFilesDirectory,
appName,
}),
);
},
@@ -3,20 +3,24 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getRouteInjectable } from "../../router/router.injectable";
import { getAppVersion } from "../../../common/utils";
import { route } from "../../router/route";
import buildVersionInjectable from "../../vars/build-version/build-version.injectable";
const getVersionRouteInjectable = getRouteInjectable({
id: "get-version-route",
instantiate: () => route({
method: "get",
path: `/version`,
})(() => ({
response: {
version: getAppVersion(),
},
})),
instantiate: (di) => {
const buildVersion = di.inject(buildVersionInjectable);
return route({
method: "get",
path: `/version`,
})(() => ({
response: {
version: buildVersion.get(),
},
}));
},
});
export default getVersionRouteInjectable;
-40
View File
@@ -1,40 +0,0 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { shellEnv } from "./utils/shell-env";
import os from "os";
import { app } from "electron";
import logger from "./logger";
import { isSnap } from "../common/vars";
import { unionPATHs } from "../common/utils/union-env-path";
/**
* shellSync loads what would have been the environment if this application was
* run from the command line, into the process.env object. This is especially
* useful on macos where this always needs to be done.
*/
export async function shellSync() {
const env = await shellEnv(os.userInfo().shell);
if (!env.LANG) {
// the LANG env var expects an underscore instead of electron's dash
env.LANG = `${app.getLocale().replace("-", "_")}.UTF-8`;
} else if (!env.LANG.endsWith(".UTF-8")) {
env.LANG += ".UTF-8";
}
if (!isSnap) {
// Prefer the synced PATH over the initial one
process.env.PATH = unionPATHs(env.PATH ?? "", process.env.PATH ?? "");
}
// The spread operator allows joining of objects. The precedence is last to first.
process.env = {
...env,
...process.env,
};
logger.debug(`[SHELL-SYNC]: Synced shell env, and updating`, env, process.env);
}
@@ -6,11 +6,11 @@ import { getInjectable } from "@ogre-tools/injectable";
import createLensWindowInjectable from "./create-lens-window.injectable";
import lensProxyPortInjectable from "../../../lens-proxy/lens-proxy-port.injectable";
import isMacInjectable from "../../../../common/vars/is-mac.injectable";
import appNameInjectable from "../../../app-paths/app-name/app-name.injectable";
import appEventBusInjectable from "../../../../common/app-event-bus/app-event-bus.injectable";
import waitUntilBundledExtensionsAreLoadedInjectable from "./wait-until-bundled-extensions-are-loaded.injectable";
import { applicationWindowInjectionToken } from "./application-window-injection-token";
import { runInAction } from "mobx";
import appNameInjectable from "../../../../common/vars/app-name.injectable";
const createApplicationWindowInjectable = getInjectable({
id: "create-application-window",
@@ -0,0 +1,9 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getGlobalOverride } from "../../../../common/test-utils/get-global-override";
import initializeSentryOnMainInjectable from "./initialize-on-main.injectable";
export default getGlobalOverride(initializeSentryOnMainInjectable, () => () => {});
@@ -3,12 +3,12 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import packageInfo from "../../../../package.json";
import { init } from "@sentry/electron/main";
const productNameInjectable = getInjectable({
id: "product-name",
instantiate: () => packageInfo.productName,
const initializeSentryOnMainInjectable = getInjectable({
id: "initialize-sentry-on-main",
instantiate: () => init,
causesSideEffects: true,
});
export default productNameInjectable;
export default initializeSentryOnMainInjectable;
@@ -0,0 +1,23 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import { beforeElectronIsReadyInjectionToken } from "../../runnable-tokens/before-electron-is-ready-injection-token";
import initializeSentryReportingWithInjectable from "../../../../common/error-reporting/initialize-sentry-reporting.injectable";
import initializeSentryOnMainInjectable from "./initialize-on-main.injectable";
const setupSentryInjectable = getInjectable({
id: "setup-sentry",
instantiate: (di) => {
const initializeSentryReportingWith = di.inject(initializeSentryReportingWithInjectable);
const initializeSentryOnMain = di.inject(initializeSentryOnMainInjectable);
return {
run: () => initializeSentryReportingWith(initializeSentryOnMain),
};
},
injectionToken: beforeElectronIsReadyInjectionToken,
});
export default setupSentryInjectable;
@@ -3,7 +3,7 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import { getAppVersion, getAppVersionFromProxyServer } from "../../../common/utils";
import { getAppVersionFromProxyServer } from "../../../common/utils";
import exitAppInjectable from "../../electron-app/features/exit-app.injectable";
import lensProxyInjectable from "../../lens-proxy/lens-proxy.injectable";
import loggerInjectable from "../../../common/logger.injectable";
@@ -11,6 +11,7 @@ import lensProxyPortInjectable from "../../lens-proxy/lens-proxy-port.injectable
import isWindowsInjectable from "../../../common/vars/is-windows.injectable";
import showErrorPopupInjectable from "../../electron-app/features/show-error-popup.injectable";
import { beforeApplicationIsLoadingInjectionToken } from "../runnable-tokens/before-application-is-loading-injection-token";
import buildVersionInjectable from "../../vars/build-version/build-version.injectable";
const setupLensProxyInjectable = getInjectable({
id: "setup-lens-proxy",
@@ -22,6 +23,7 @@ const setupLensProxyInjectable = getInjectable({
const lensProxyPort = di.inject(lensProxyPortInjectable);
const isWindows = di.inject(isWindowsInjectable);
const showErrorPopup = di.inject(showErrorPopupInjectable);
const buildVersion = di.inject(buildVersionInjectable);
return {
run: async () => {
@@ -41,7 +43,7 @@ const setupLensProxyInjectable = getInjectable({
lensProxyPort.get(),
);
if (getAppVersion() !== versionFromProxy) {
if (buildVersion.get() !== versionFromProxy) {
logger.error("Proxy server responded with invalid response");
return exitApp();
@@ -1,24 +0,0 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import { initializeSentryReporting } from "../../../common/sentry";
import { init } from "@sentry/electron/main";
import { beforeElectronIsReadyInjectionToken } from "../runnable-tokens/before-electron-is-ready-injection-token";
const setupSentryInjectable = getInjectable({
id: "setup-sentry",
instantiate: () => ({
run: () => {
initializeSentryReporting(init);
},
}),
causesSideEffects: true,
injectionToken: beforeElectronIsReadyInjectionToken,
});
export default setupSentryInjectable;
@@ -3,21 +3,47 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import { shellSync } from "../../shell-sync";
import loggerInjectable from "../../../common/logger.injectable";
import { onLoadOfApplicationInjectionToken } from "../runnable-tokens/on-load-of-application-injection-token";
import { shellEnv } from "../../utils/shell-env";
import os from "os";
import { unionPATHs } from "../../../common/utils/union-env-path";
import isSnapPackageInjectable from "../../../common/vars/is-snap-package.injectable";
import electronAppInjectable from "../../electron-app/electron-app.injectable";
const setupShellInjectable = getInjectable({
id: "setup-shell",
instantiate: (di) => {
const logger = di.inject(loggerInjectable);
const isSnapPackage = di.inject(isSnapPackageInjectable);
const electronApp = di.inject(electronAppInjectable);
return {
run: async () => {
logger.info("🐚 Syncing shell environment");
await shellSync();
const env = await shellEnv(os.userInfo().shell);
if (!env.LANG) {
// the LANG env var expects an underscore instead of electron's dash
env.LANG = `${electronApp.getLocale().replace("-", "_")}.UTF-8`;
} else if (!env.LANG.endsWith(".UTF-8")) {
env.LANG += ".UTF-8";
}
if (!isSnapPackage) {
// Prefer the synced PATH over the initial one
process.env.PATH = unionPATHs(env.PATH ?? "", process.env.PATH ?? "");
}
// The spread operator allows joining of objects. The precedence is last to first.
process.env = {
...env,
...process.env,
};
logger.debug(`[SHELL-SYNC]: Synced shell env, and updating`, env, process.env);
},
};
},
@@ -4,12 +4,12 @@
*/
import { getInjectable } from "@ogre-tools/injectable";
import { Menu, Tray } from "electron";
import packageJsonInjectable from "../../../common/vars/package-json.injectable";
import showApplicationWindowInjectable from "../../start-main-application/lens-window/show-application-window.injectable";
import isWindowsInjectable from "../../../common/vars/is-windows.injectable";
import loggerInjectable from "../../../common/logger.injectable";
import { convertToElectronMenuTemplate } from "../reactive-tray-menu-items/converters";
import trayIconInjectable from "../menu-icon/tray-icon.injectable";
import applicationDescriptionInjectable from "../../../common/vars/application-description.injectable";
const TRAY_LOG_PREFIX = "[TRAY]";
@@ -34,7 +34,7 @@ const electronTrayInjectable = getInjectable({
id: "electron-tray",
instantiate: (di): ElectronTray => {
const packageJson = di.inject(packageJsonInjectable);
const applicationDescription = di.inject(applicationDescriptionInjectable);
const showApplicationWindow = di.inject(showApplicationWindowInjectable);
const isWindows = di.inject(isWindowsInjectable);
const logger = di.inject(loggerInjectable);
@@ -46,7 +46,7 @@ const electronTrayInjectable = getInjectable({
start: () => {
tray = new Tray(trayIcon.get().iconPath);
tray.setToolTip(packageJson.description);
tray.setToolTip(applicationDescription);
tray.setIgnoreDoubleClickEvents(true);
if (isWindows) {
@@ -3,7 +3,6 @@
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import productNameInjectable from "../../../app-paths/app-name/product-name.injectable";
import showApplicationWindowInjectable from "../../../start-main-application/lens-window/show-application-window.injectable";
import showAboutInjectable from "../../../menu/show-about.injectable";
import { trayMenuItemInjectionToken } from "../tray-menu-item-injection-token";
@@ -11,6 +10,7 @@ import { computed } from "mobx";
import withErrorLoggingInjectable from "../../../../common/utils/with-error-logging/with-error-logging.injectable";
import { withErrorSuppression } from "../../../../common/utils/with-error-suppression/with-error-suppression";
import { pipeline } from "@ogre-tools/fp";
import productNameInjectable from "../../../../common/vars/product-name.injectable";
const aboutAppTrayItemInjectable = getInjectable({
id: "about-app-tray-item",
@@ -32,15 +32,10 @@ const aboutAppTrayItemInjectable = getInjectable({
click: pipeline(
async () => {
await showApplicationWindow();
await showAbout();
showAbout();
},
withErrorLoggingFor(() => "[TRAY]: Opening of show about failed."),
// TODO: Find out how to improve typing so that instead of
// x => withErrorSuppression(x) there could only be withErrorSuppression
(x) => withErrorSuppression(x),
withErrorSuppression,
),
};
},
@@ -4,12 +4,12 @@
*/
import { getInjectable } from "@ogre-tools/injectable";
import { trayMenuItemInjectionToken } from "../tray-menu-item-injection-token";
import productNameInjectable from "../../../app-paths/app-name/product-name.injectable";
import showApplicationWindowInjectable from "../../../start-main-application/lens-window/show-application-window.injectable";
import { computed } from "mobx";
import withErrorLoggingInjectable from "../../../../common/utils/with-error-logging/with-error-logging.injectable";
import { withErrorSuppression } from "../../../../common/utils/with-error-suppression/with-error-suppression";
import { pipeline } from "@ogre-tools/fp";
import productNameInjectable from "../../../../common/vars/product-name.injectable";
const openAppTrayItemInjectable = getInjectable({
id: "open-app-tray-item",
@@ -28,15 +28,9 @@ const openAppTrayItemInjectable = getInjectable({
visible: computed(() => true),
click: pipeline(
async () => {
await showApplicationWindow();
},
showApplicationWindow,
withErrorLoggingFor(() => "[TRAY]: Opening of application window failed."),
// TODO: Find out how to improve typing so that instead of
// x => withErrorSuppression(x) there could only be withErrorSuppression
(x) => withErrorSuppression(x),
withErrorSuppression,
),
};
},
@@ -0,0 +1,19 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { createInitializableState } from "../../../common/initializable-state/create";
import { buildVersionInjectionToken } from "../../../common/vars/build-semantic-version.injectable";
import getBuildVersionInjectable from "./get-build-version.injectable";
const buildVersionInjectable = createInitializableState({
id: "build-version",
init: (di) => {
const getBuildVersion = di.inject(getBuildVersionInjectable);
return getBuildVersion();
},
injectionToken: buildVersionInjectionToken,
});
export default buildVersionInjectable;
@@ -0,0 +1,17 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import electronAppInjectable from "../../electron-app/electron-app.injectable";
const getBuildVersionInjectable = getInjectable({
id: "get-build-version",
instantiate: (di) => {
const electronApp = di.inject(electronAppInjectable);
return () => electronApp.getVersion();
},
});
export default getBuildVersionInjectable;
@@ -0,0 +1,21 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import { beforeApplicationIsLoadingInjectionToken } from "../../start-main-application/runnable-tokens/before-application-is-loading-injection-token";
import buildVersionInjectable from "./build-version.injectable";
const initializeBuildVersionAsyncSyncBoxInjectable = getInjectable({
id: "initialize-build-version-async-sync-box",
instantiate: (di) => {
const buildVersion = di.inject(buildVersionInjectable);
return {
run: () => buildVersion.init(),
};
},
injectionToken: beforeApplicationIsLoadingInjectionToken,
});
export default initializeBuildVersionAsyncSyncBoxInjectable;
@@ -0,0 +1,23 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import defaultUpdateChannelInjectable from "../../../common/application-update/selected-update-channel/default-update-channel.injectable";
import initSemanticBuildVersionInjectable from "../../../renderer/vars/semantic-build-version/init.injectable";
import { beforeApplicationIsLoadingInjectionToken } from "../../start-main-application/runnable-tokens/before-application-is-loading-injection-token";
const initDefaultUpdateChannelInjectableInjectable = getInjectable({
id: "init-default-update-channel-injectable",
instantiate: (di) => {
const defaultUpdateChannel = di.inject(defaultUpdateChannelInjectable);
return {
run: () => defaultUpdateChannel.init(),
runAfter: di.inject(initSemanticBuildVersionInjectable),
};
},
injectionToken: beforeApplicationIsLoadingInjectionToken,
});
export default initDefaultUpdateChannelInjectableInjectable;
@@ -0,0 +1,23 @@
/**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import buildSemanticVersionInjectable from "../../../common/vars/build-semantic-version.injectable";
import { beforeApplicationIsLoadingInjectionToken } from "../../start-main-application/runnable-tokens/before-application-is-loading-injection-token";
import initializeBuildVersionInjectable from "../build-version/init.injectable";
const initSemanticBuildVersionInjectable = getInjectable({
id: "init-semantic-build-version",
instantiate: (di) => {
const buildSemanticVersion = di.inject(buildSemanticVersionInjectable);
return {
run: () => buildSemanticVersion.init(),
runAfter: di.inject(initializeBuildVersionInjectable),
};
},
injectionToken: beforeApplicationIsLoadingInjectionToken,
});
export default initSemanticBuildVersionInjectable;