1
0
mirror of https://github.com/lensapp/lens.git synced 2025-05-20 05:10:56 +00:00

Enforce template strings in eslint (#1574)

Signed-off-by: Panu Horsmalahti <phorsmalahti@mirantis.com>
This commit is contained in:
Panu Horsmalahti 2020-11-30 15:35:16 +02:00 committed by GitHub
parent 07e6df9fdc
commit 335778aeef
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
52 changed files with 94 additions and 88 deletions

View File

@ -47,6 +47,8 @@ module.exports = {
}], }],
"semi": ["error", "always"], "semi": ["error", "always"],
"object-shorthand": "error", "object-shorthand": "error",
"prefer-template": "error",
"template-curly-spacing": "error",
} }
}, },
{ {
@ -90,6 +92,8 @@ module.exports = {
"semi": "off", "semi": "off",
"@typescript-eslint/semi": ["error"], "@typescript-eslint/semi": ["error"],
"object-shorthand": "error", "object-shorthand": "error",
"prefer-template": "error",
"template-curly-spacing": "error",
}, },
}, },
{ {
@ -140,6 +144,8 @@ module.exports = {
"semi": "off", "semi": "off",
"@typescript-eslint/semi": ["error"], "@typescript-eslint/semi": ["error"],
"object-shorthand": "error", "object-shorthand": "error",
"prefer-template": "error",
"template-curly-spacing": "error",
}, },
} }
] ]

View File

@ -43,7 +43,7 @@ class KubectlDownloader {
return true; return true;
} }
console.log("Kubectl md5sum " + hash + " does not match the remote etag " + etag + ", unlinking and downloading again"); console.log(`Kubectl md5sum ${hash} does not match the remote etag ${etag}, unlinking and downloading again`);
await fs.promises.unlink(this.path); await fs.promises.unlink(this.path);
} }
@ -103,7 +103,7 @@ const downloads = [
downloads.forEach((dlOpts) => { downloads.forEach((dlOpts) => {
console.log(dlOpts); console.log(dlOpts);
const downloader = new KubectlDownloader(downloadVersion, dlOpts.platform, dlOpts.arch, dlOpts.target); const downloader = new KubectlDownloader(downloadVersion, dlOpts.platform, dlOpts.arch, dlOpts.target);
console.log("Downloading: " + JSON.stringify(dlOpts)); console.log(`Downloading: ${JSON.stringify(dlOpts)}`);
downloader.downloadKubectl().then(() => downloader.checkBinary().then(() => console.log("Download complete"))); downloader.downloadKubectl().then(() => downloader.checkBinary().then(() => console.log("Download complete")));
}); });

View File

@ -6,4 +6,4 @@ import appInfo from "../package.json";
const packagePath = path.join(__dirname, "../src/extensions/npm/extensions/package.json"); const packagePath = path.join(__dirname, "../src/extensions/npm/extensions/package.json");
packageInfo.version = appInfo.version; packageInfo.version = appInfo.version;
fs.writeFileSync(packagePath, JSON.stringify(packageInfo, null, 2) + "\n"); fs.writeFileSync(packagePath, `${JSON.stringify(packageInfo, null, 2)}\n`);

View File

@ -546,7 +546,7 @@ describe("Lens integration tests", () => {
await app.client.keys("metadata:\n"); await app.client.keys("metadata:\n");
await app.client.keys(" name: nginx-create-pod-test\n"); await app.client.keys(" name: nginx-create-pod-test\n");
await app.client.keys(`namespace: ${TEST_NAMESPACE}\n`); await app.client.keys(`namespace: ${TEST_NAMESPACE}\n`);
await app.client.keys(BACKSPACE + "spec:\n"); await app.client.keys(`${BACKSPACE}spec:\n`);
await app.client.keys(" containers:\n"); await app.client.keys(" containers:\n");
await app.client.keys("- name: nginx-create-pod-test\n"); await app.client.keys("- name: nginx-create-pod-test\n");
await app.client.keys(" image: nginx:alpine\n"); await app.client.keys(" image: nginx:alpine\n");

View File

@ -5,7 +5,7 @@ import path from "path";
export function registerFileProtocol(name: string, basePath: string) { export function registerFileProtocol(name: string, basePath: string) {
protocol.registerFileProtocol(name, (request, callback) => { protocol.registerFileProtocol(name, (request, callback) => {
const filePath = request.url.replace(name + "://", ""); const filePath = request.url.replace(`${name}://`, "");
const absPath = path.resolve(basePath, filePath); const absPath = path.resolve(basePath, filePath);
callback({ path: absPath }); callback({ path: absPath });
}); });

View File

@ -6,7 +6,7 @@ import logger from "../main/logger";
if (isMac) { if (isMac) {
for (const crt of macca.all()) { for (const crt of macca.all()) {
const attributes = crt.issuer?.attributes?.map((a: any) => `${a.name}=${a.value}`); const attributes = crt.issuer?.attributes?.map((a: any) => `${a.name}=${a.value}`);
logger.debug("Using host CA: " + attributes.join(",")); logger.debug(`Using host CA: ${attributes.join(",")}`);
} }
} }
if (isWindows) { if (isWindows) {

View File

@ -28,7 +28,7 @@ export class HelmCli extends LensBinary {
} }
protected getOriginalBinaryPath() { protected getOriginalBinaryPath() {
return path.join(this.dirname, this.platformName + "-" + this.arch, this.originalBinaryName); return path.join(this.dirname, `${this.platformName}-${this.arch}`, this.originalBinaryName);
} }
} }

View File

@ -81,7 +81,7 @@ export class KubeconfigManager {
return; return;
} }
logger.info("Deleting temporary kubeconfig: " + this.tempFile); logger.info(`Deleting temporary kubeconfig: ${this.tempFile}`);
await fs.unlink(this.tempFile); await fs.unlink(this.tempFile);
this.tempFile = undefined; this.tempFile = undefined;
} }

View File

@ -81,10 +81,10 @@ export class Kubectl {
if the version map includes that, use that version, if not, fallback to the exact x.y.z of kube version */ if the version map includes that, use that version, if not, fallback to the exact x.y.z of kube version */
if (kubectlMap.has(minorVersion)) { if (kubectlMap.has(minorVersion)) {
this.kubectlVersion = kubectlMap.get(minorVersion); this.kubectlVersion = kubectlMap.get(minorVersion);
logger.debug("Set kubectl version " + this.kubectlVersion + " for cluster version " + clusterVersion + " using version map"); logger.debug(`Set kubectl version ${this.kubectlVersion} for cluster version ${clusterVersion} using version map`);
} else { } else {
this.kubectlVersion = versionParts[1] + versionParts[2]; this.kubectlVersion = versionParts[1] + versionParts[2];
logger.debug("Set kubectl version " + this.kubectlVersion + " for cluster version " + clusterVersion + " using fallback"); logger.debug(`Set kubectl version ${this.kubectlVersion} for cluster version ${clusterVersion} using fallback`);
} }
let arch = null; let arch = null;
@ -197,7 +197,7 @@ export class Kubectl {
} }
return true; return true;
} catch (err) { } catch (err) {
logger.error("Could not copy the bundled kubectl to app-data: " + err); logger.error(`Could not copy the bundled kubectl to app-data: ${err}`);
return false; return false;
} }
} else { } else {
@ -280,7 +280,7 @@ export class Kubectl {
const fsPromises = fs.promises; const fsPromises = fs.promises;
const bashScriptPath = path.join(this.dirname, ".bash_set_path"); const bashScriptPath = path.join(this.dirname, ".bash_set_path");
let bashScript = "" + initScriptVersionString; let bashScript = `${initScriptVersionString}`;
bashScript += "tempkubeconfig=\"$KUBECONFIG\"\n"; bashScript += "tempkubeconfig=\"$KUBECONFIG\"\n";
bashScript += "test -f \"/etc/profile\" && . \"/etc/profile\"\n"; bashScript += "test -f \"/etc/profile\" && . \"/etc/profile\"\n";
bashScript += "if test -f \"$HOME/.bash_profile\"; then\n"; bashScript += "if test -f \"$HOME/.bash_profile\"; then\n";
@ -303,7 +303,7 @@ export class Kubectl {
const zshScriptPath = path.join(this.dirname, ".zlogin"); const zshScriptPath = path.join(this.dirname, ".zlogin");
let zshScript = "" + initScriptVersionString; let zshScript = `${initScriptVersionString}`;
zshScript += "tempkubeconfig=\"$KUBECONFIG\"\n"; zshScript += "tempkubeconfig=\"$KUBECONFIG\"\n";
// restore previous ZDOTDIR // restore previous ZDOTDIR

View File

@ -51,8 +51,8 @@ export class LensBinary {
this.platformName = isWindows ? "windows" : process.platform; this.platformName = isWindows ? "windows" : process.platform;
this.dirname = path.normalize(path.join(baseDir, this.binaryName)); this.dirname = path.normalize(path.join(baseDir, this.binaryName));
if (isWindows) { if (isWindows) {
this.binaryName = this.binaryName + ".exe"; this.binaryName = `${this.binaryName}.exe`;
this.originalBinaryName = this.originalBinaryName + ".exe"; this.originalBinaryName = `${this.originalBinaryName}.exe`;
} }
const tarName = this.getTarName(); const tarName = this.getTarName();
if (tarName) { if (tarName) {

View File

@ -95,7 +95,7 @@ export class LensProxy {
socket.end(); socket.end();
}); });
proxySocket.on("error", function () { proxySocket.on("error", function () {
socket.write("HTTP/" + req.httpVersion + " 500 Connection error\r\n\r\n"); socket.write(`HTTP/${req.httpVersion} 500 Connection error\r\n\r\n`);
socket.end(); socket.end();
}); });
socket.on("data", function (chunk) { socket.on("data", function (chunk) {
@ -117,7 +117,7 @@ export class LensProxy {
return; return;
} }
if (target) { if (target) {
logger.debug("Failed proxy to target: " + JSON.stringify(target, null, 2)); logger.debug(`Failed proxy to target: ${JSON.stringify(target, null, 2)}`);
if (req.method === "GET" && (!res.statusCode || res.statusCode >= 500)) { if (req.method === "GET" && (!res.statusCode || res.statusCode >= 500)) {
const reqId = this.getRequestId(req); const reqId = this.getRequestId(req);
const retryCount = this.retryCounters.get(reqId) || 0; const retryCount = this.retryCounters.get(reqId) || 0;

View File

@ -26,7 +26,7 @@ export class ResourceApplier {
const fileName = tempy.file({ name: "resource.yaml" }); const fileName = tempy.file({ name: "resource.yaml" });
fs.writeFileSync(fileName, content); fs.writeFileSync(fileName, content);
const cmd = `"${kubectlPath}" apply --kubeconfig "${this.cluster.getProxyKubeconfigPath()}" -o json -f "${fileName}"`; const cmd = `"${kubectlPath}" apply --kubeconfig "${this.cluster.getProxyKubeconfigPath()}" -o json -f "${fileName}"`;
logger.debug("shooting manifests with: " + cmd); logger.debug(`shooting manifests with: ${cmd}`);
const execEnv: NodeJS.ProcessEnv = Object.assign({}, process.env); const execEnv: NodeJS.ProcessEnv = Object.assign({}, process.env);
const httpsProxy = this.cluster.preferences?.httpsProxy; const httpsProxy = this.cluster.preferences?.httpsProxy;
if (httpsProxy) { if (httpsProxy) {
@ -58,7 +58,7 @@ export class ResourceApplier {
console.log("shooting manifests with:", cmd); console.log("shooting manifests with:", cmd);
exec(cmd, (error, stdout, stderr) => { exec(cmd, (error, stdout, stderr) => {
if (error) { if (error) {
reject("Error applying manifests:" + error); reject(`Error applying manifests:${error}`);
} }
if (stderr != "") { if (stderr != "") {
reject(stderr); reject(stderr);

View File

@ -102,7 +102,7 @@ export class Router {
// redirect requests to [appName].js, [appName].html /sockjs-node/ to webpack-dev-server (for hot-reload support) // redirect requests to [appName].js, [appName].html /sockjs-node/ to webpack-dev-server (for hot-reload support)
const toWebpackDevServer = filename.includes(appName) || filename.includes("hot-update") || req.url.includes("sockjs-node"); const toWebpackDevServer = filename.includes(appName) || filename.includes("hot-update") || req.url.includes("sockjs-node");
if (isDevelopment && toWebpackDevServer) { if (isDevelopment && toWebpackDevServer) {
const redirectLocation = `http://localhost:${webpackDevServerPort}` + req.url; const redirectLocation = `http://localhost:${webpackDevServerPort}${req.url}`;
res.statusCode = 307; res.statusCode = 307;
res.setHeader("Location", redirectLocation); res.setHeader("Location", redirectLocation);
res.end(); res.end();

View File

@ -37,7 +37,7 @@ class ApiWatcher {
if (this.processor) { if (this.processor) {
clearInterval(this.processor); clearInterval(this.processor);
} }
logger.debug("Stopping watcher for api: " + this.apiUrl); logger.debug(`Stopping watcher for api: ${this.apiUrl}`);
try { try {
this.watchRequest.abort(); this.watchRequest.abort();
this.sendEvent({ this.sendEvent({
@ -47,7 +47,7 @@ class ApiWatcher {
}); });
logger.debug("watch aborted"); logger.debug("watch aborted");
} catch (error) { } catch (error) {
logger.error("Watch abort errored:" + error); logger.error(`Watch abort errored:${error}`);
} }
} }
@ -59,7 +59,7 @@ class ApiWatcher {
} }
private doneHandler(error: Error) { private doneHandler(error: Error) {
if (error) logger.warn("watch ended: " + error.toString()); if (error) logger.warn(`watch ended: ${error.toString()}`);
this.watchRequest.abort(); this.watchRequest.abort();
} }
@ -87,7 +87,7 @@ class WatchRoute extends LensApi {
response.setHeader("Content-Type", "text/event-stream"); response.setHeader("Content-Type", "text/event-stream");
response.setHeader("Cache-Control", "no-cache"); response.setHeader("Cache-Control", "no-cache");
response.setHeader("Connection", "keep-alive"); response.setHeader("Connection", "keep-alive");
logger.debug("watch using kubeconfig:" + JSON.stringify(cluster.getProxyKubeconfig(), null, 2)); logger.debug(`watch using kubeconfig:${JSON.stringify(cluster.getProxyKubeconfig(), null, 2)}`);
apis.forEach(apiUrl => { apis.forEach(apiUrl => {
const watcher = new ApiWatcher(apiUrl, cluster.getProxyKubeconfig(), response); const watcher = new ApiWatcher(apiUrl, cluster.getProxyKubeconfig(), response);

View File

@ -203,6 +203,6 @@ export class ShellSession extends EventEmitter {
} }
protected sendResponse(msg: string) { protected sendResponse(msg: string) {
this.websocket.send("1" + Buffer.from(msg).toString("base64")); this.websocket.send(`1${Buffer.from(msg).toString("base64")}`);
} }
} }

View File

@ -6,7 +6,7 @@ import { KubeApi } from "../kube-api";
export class DeploymentApi extends KubeApi<Deployment> { export class DeploymentApi extends KubeApi<Deployment> {
protected getScaleApiUrl(params: { namespace: string; name: string }) { protected getScaleApiUrl(params: { namespace: string; name: string }) {
return this.getUrl(params) + "/scale"; return `${this.getUrl(params)}/scale`;
} }
getReplicas(params: { namespace: string; name: string }): Promise<number> { getReplicas(params: { namespace: string; name: string }): Promise<number> {

View File

@ -34,7 +34,7 @@ export const helmChartsApi = {
get(repo: string, name: string, readmeVersion?: string) { get(repo: string, name: string, readmeVersion?: string) {
const path = endpoint({ repo, name }); const path = endpoint({ repo, name });
return apiBase return apiBase
.get<IHelmChartDetails>(path + "?" + stringify({ version: readmeVersion })) .get<IHelmChartDetails>(`${path}?${stringify({ version: readmeVersion })}`)
.then(data => { .then(data => {
const versions = data.versions.map(HelmChart.create); const versions = data.versions.map(HelmChart.create);
const readme = data.readme; const readme = data.readme;
@ -47,7 +47,7 @@ export const helmChartsApi = {
getValues(repo: string, name: string, version: string) { getValues(repo: string, name: string, version: string) {
return apiBase return apiBase
.get<string>(`/v2/charts/${repo}/${name}/values?` + stringify({ version })); .get<string>(`/v2/charts/${repo}/${name}/values?${stringify({ version })}`);
} }
}; };

View File

@ -106,17 +106,17 @@ export const helmReleasesApi = {
}, },
getValues(name: string, namespace: string) { getValues(name: string, namespace: string) {
const path = endpoint({ name, namespace }) + "/values"; const path = `${endpoint({ name, namespace })}/values`;
return apiBase.get<string>(path); return apiBase.get<string>(path);
}, },
getHistory(name: string, namespace: string): Promise<IReleaseRevision[]> { getHistory(name: string, namespace: string): Promise<IReleaseRevision[]> {
const path = endpoint({ name, namespace }) + "/history"; const path = `${endpoint({ name, namespace })}/history`;
return apiBase.get(path); return apiBase.get(path);
}, },
rollback(name: string, namespace: string, revision: number) { rollback(name: string, namespace: string, revision: number) {
const path = endpoint({ name, namespace }) + "/rollback"; const path = `${endpoint({ name, namespace })}/rollback`;
return apiBase.put(path, { return apiBase.put(path, {
data: { data: {
revision revision

View File

@ -111,7 +111,7 @@ export class Ingress extends KubeObject {
rule.http.paths.forEach(path => { rule.http.paths.forEach(path => {
const { serviceName, servicePort } = getBackendServiceNamePort(path.backend); const { serviceName, servicePort } = getBackendServiceNamePort(path.backend);
routes.push(protocol + "://" + host + (path.path || "/") + " ⇢ " + serviceName + ":" + servicePort); routes.push(`${protocol}://${host}${path.path || "/"}${serviceName}:${servicePort}`);
}); });
} }
}); });

View File

@ -5,7 +5,7 @@ import { KubeApi } from "../kube-api";
export class PodsApi extends KubeApi<Pod> { export class PodsApi extends KubeApi<Pod> {
async getLogs(params: { namespace: string; name: string }, query?: IPodLogsQuery): Promise<string> { async getLogs(params: { namespace: string; name: string }, query?: IPodLogsQuery): Promise<string> {
const path = this.getUrl(params) + "/log"; const path = `${this.getUrl(params)}/log`;
return this.request.get(path, { query }); return this.request.get(path, { query });
} }

View File

@ -24,7 +24,7 @@ export class ServicePort implements IServicePort {
if (this.nodePort) { if (this.nodePort) {
return `${this.port}:${this.nodePort}/${this.protocol}`; return `${this.port}:${this.nodePort}/${this.protocol}`;
} else { } else {
return `${this.port}${this.port === this.targetPort ? "" : ":" + this.targetPort}/${this.protocol}`; return `${this.port}${this.port === this.targetPort ? "" : `:${this.targetPort}`}/${this.protocol}`;
} }
} }
} }

View File

@ -6,7 +6,7 @@ import { KubeApi } from "../kube-api";
export class StatefulSetApi extends KubeApi<StatefulSet> { export class StatefulSetApi extends KubeApi<StatefulSet> {
protected getScaleApiUrl(params: { namespace: string; name: string }) { protected getScaleApiUrl(params: { namespace: string; name: string }) {
return this.getUrl(params) + "/scale"; return `${this.getUrl(params)}/scale`;
} }
getReplicas(params: { namespace: string; name: string }): Promise<number> { getReplicas(params: { namespace: string; name: string }): Promise<number> {

View File

@ -230,7 +230,7 @@ export class KubeApi<T extends KubeObject = any> {
namespace: this.isNamespaced ? namespace : undefined, namespace: this.isNamespaced ? namespace : undefined,
name, name,
}); });
return resourcePath + (query ? `?` + stringify(this.normalizeQuery(query)) : ""); return resourcePath + (query ? `?${stringify(this.normalizeQuery(query))}` : "");
} }
protected normalizeQuery(query: Partial<IKubeApiQueryParams> = {}) { protected normalizeQuery(query: Partial<IKubeApiQueryParams> = {}) {

View File

@ -78,7 +78,7 @@ export class KubeWatchApi {
return; return;
} }
const query = this.getQuery(); const query = this.getQuery();
const apiUrl = `${apiPrefix}/watch?` + stringify(query); const apiUrl = `${apiPrefix}/watch?${stringify(query)}`;
this.evtSource = new EventSource(apiUrl); this.evtSource = new EventSource(apiUrl);
this.evtSource.onmessage = this.onMessage; this.evtSource.onmessage = this.onMessage;
this.evtSource.onerror = this.onError; this.evtSource.onerror = this.onError;

View File

@ -130,7 +130,7 @@ export class TerminalApi extends WebSocketApi {
} }
let time; let time;
if (showTime) { if (showTime) {
time = (new Date()).toLocaleString() + " "; time = `${(new Date()).toLocaleString()} `;
} }
this.onData.emit(`${showTime ? time : ""}${data}\r\n`); this.onData.emit(`${showTime ? time : ""}${data}\r\n`);
} }

View File

@ -88,7 +88,7 @@ export class WebSocketApi {
reconnect() { reconnect() {
const { reconnectDelaySeconds } = this.params; const { reconnectDelaySeconds } = this.params;
if (!reconnectDelaySeconds) return; if (!reconnectDelaySeconds) return;
this.writeLog("reconnect after", reconnectDelaySeconds + "ms"); this.writeLog("reconnect after", `${reconnectDelaySeconds}ms`);
this.reconnectTimer = setTimeout(() => this.connect(), reconnectDelaySeconds * 1000); this.reconnectTimer = setTimeout(() => this.connect(), reconnectDelaySeconds * 1000);
this.readyState = WebSocketApiState.RECONNECTING; this.readyState = WebSocketApiState.RECONNECTING;
} }

View File

@ -3,7 +3,7 @@ import { buildURL } from "../../../common/utils/buildUrl";
import { appsRoute } from "../+apps/apps.route"; import { appsRoute } from "../+apps/apps.route";
export const helmChartsRoute: RouteProps = { export const helmChartsRoute: RouteProps = {
path: appsRoute.path + "/charts/:repo?/:chartName?" path: `${appsRoute.path}/charts/:repo?/:chartName?`
}; };
export interface IHelmChartsRouteParams { export interface IHelmChartsRouteParams {

View File

@ -3,7 +3,7 @@ import { buildURL } from "../../../common/utils/buildUrl";
import { appsRoute } from "../+apps/apps.route"; import { appsRoute } from "../+apps/apps.route";
export const releaseRoute: RouteProps = { export const releaseRoute: RouteProps = {
path: appsRoute.path + "/releases/:namespace?/:name?" path: `${appsRoute.path}/releases/:namespace?/:name?`
}; };
export interface IReleaseRouteParams { export interface IReleaseRouteParams {

View File

@ -25,7 +25,7 @@ export const ClusterMetrics = observer(() => {
const datasets = [{ const datasets = [{
id: metricType + metricNodeRole, id: metricType + metricNodeRole,
label: metricType.toUpperCase() + " usage", label: `${metricType.toUpperCase()} usage`,
borderColor: colors[metricType], borderColor: colors[metricType],
data data
}]; }];

View File

@ -73,10 +73,10 @@ export const ClusterPieCharts = observer(() => {
}, },
], ],
labels: [ labels: [
i18n._(t`Usage`) + `: ${cpuUsage ? cpuUsage.toFixed(2) : "N/A"}`, `${i18n._(t`Usage`)}: ${cpuUsage ? cpuUsage.toFixed(2) : "N/A"}`,
i18n._(t`Requests`) + `: ${cpuRequests ? cpuRequests.toFixed(2) : "N/A"}`, `${i18n._(t`Requests`)}: ${cpuRequests ? cpuRequests.toFixed(2) : "N/A"}`,
i18n._(t`Limits`) + `: ${cpuLimits ? cpuLimits.toFixed(2) : "N/A"}`, `${i18n._(t`Limits`)}: ${cpuLimits ? cpuLimits.toFixed(2) : "N/A"}`,
i18n._(t`Capacity`) + `: ${cpuCapacity || "N/A"}` `${i18n._(t`Capacity`)}: ${cpuCapacity || "N/A"}`
] ]
}; };
const memoryData: ChartData = { const memoryData: ChartData = {
@ -116,10 +116,10 @@ export const ClusterPieCharts = observer(() => {
}, },
], ],
labels: [ labels: [
i18n._(t`Usage`) + `: ${bytesToUnits(memoryUsage)}`, `${i18n._(t`Usage`)}: ${bytesToUnits(memoryUsage)}`,
i18n._(t`Requests`) + `: ${bytesToUnits(memoryRequests)}`, `${i18n._(t`Requests`)}: ${bytesToUnits(memoryRequests)}`,
i18n._(t`Limits`) + `: ${bytesToUnits(memoryLimits)}`, `${i18n._(t`Limits`)}: ${bytesToUnits(memoryLimits)}`,
i18n._(t`Capacity`) + `: ${bytesToUnits(memoryCapacity)}`, `${i18n._(t`Capacity`)}: ${bytesToUnits(memoryCapacity)}`,
] ]
}; };
const podsData: ChartData = { const podsData: ChartData = {
@ -137,8 +137,8 @@ export const ClusterPieCharts = observer(() => {
}, },
], ],
labels: [ labels: [
i18n._(t`Usage`) + `: ${podUsage || 0}`, `${i18n._(t`Usage`)}: ${podUsage || 0}`,
i18n._(t`Capacity`) + `: ${podCapacity}`, `${i18n._(t`Capacity`)}: ${podCapacity}`,
] ]
}; };
return ( return (

View File

@ -46,7 +46,7 @@ function renderQuotas(quota: ResourceQuota): JSX.Element[] {
max={max} max={max}
value={current} value={current}
tooltip={ tooltip={
<p><Trans>Set</Trans>: {value}. <Trans>Usage</Trans>: {usage + "%"}</p> <p><Trans>Set</Trans>: {value}. <Trans>Usage</Trans>: {`${usage}%`}</p>
} }
/> />
</div> </div>

View File

@ -6,11 +6,11 @@ export const crdRoute: RouteProps = {
}; };
export const crdDefinitionsRoute: RouteProps = { export const crdDefinitionsRoute: RouteProps = {
path: crdRoute.path + "/definitions" path: `${crdRoute.path}/definitions`
}; };
export const crdResourcesRoute: RouteProps = { export const crdResourcesRoute: RouteProps = {
path: crdRoute.path + "/:group/:name" path: `${crdRoute.path}/:group/:name`
}; };
export interface ICRDListQuery { export interface ICRDListQuery {

View File

@ -303,7 +303,7 @@ export class Extensions extends React.Component {
async unpackExtension({ fileName, tempFile, manifest: { name, version } }: InstallRequestValidated) { async unpackExtension({ fileName, tempFile, manifest: { name, version } }: InstallRequestValidated) {
const displayName = extensionDisplayName(name, version); const displayName = extensionDisplayName(name, version);
const extensionFolder = this.getExtensionDestFolder(name); const extensionFolder = this.getExtensionDestFolder(name);
const unpackingTempFolder = path.join(path.dirname(tempFile), path.basename(tempFile) + "-unpacked"); const unpackingTempFolder = path.join(path.dirname(tempFile), `${path.basename(tempFile)}-unpacked`);
const extensionId = path.join(extensionDiscovery.nodeModulesPath, name, "package.json"); const extensionId = path.join(extensionDiscovery.nodeModulesPath, name, "package.json");
logger.info(`Unpacking extension ${displayName}`, { fileName, tempFile }); logger.info(`Unpacking extension ${displayName}`, { fileName, tempFile });

View File

@ -111,7 +111,7 @@ export class NodeDetails extends React.Component<Props> {
<DrawerItem name={<Trans>Taints</Trans>} labelsOnly> <DrawerItem name={<Trans>Taints</Trans>} labelsOnly>
{ {
taints.map(({ key, effect, value }) => ( taints.map(({ key, effect, value }) => (
<Badge key={key} label={key + ": " + effect} tooltip={value}/> <Badge key={key} label={`${key}: ${effect}`} tooltip={value}/>
)) ))
} }
</DrawerItem> </DrawerItem>

View File

@ -57,7 +57,7 @@ export class Nodes extends React.Component<Props> {
value={usage} value={usage}
tooltip={{ tooltip={{
preferredPositions: TooltipPosition.BOTTOM, preferredPositions: TooltipPosition.BOTTOM,
children: _i18n._(t`CPU:`) + ` ${Math.ceil(usage * 100) / cores}\%, ` + _i18n._(t`cores:`) + ` ${cores}` children: `${_i18n._(t`CPU:`)} ${Math.ceil(usage * 100) / cores}\%, ${_i18n._(t`cores:`)} ${cores}`
}} }}
/> />
); );
@ -74,7 +74,7 @@ export class Nodes extends React.Component<Props> {
value={usage} value={usage}
tooltip={{ tooltip={{
preferredPositions: TooltipPosition.BOTTOM, preferredPositions: TooltipPosition.BOTTOM,
children: _i18n._(t`Memory:`) + ` ${Math.ceil(usage * 100 / capacity)}%, ${bytesToUnits(usage, 3)}` children: `${_i18n._(t`Memory:`)} ${Math.ceil(usage * 100 / capacity)}%, ${bytesToUnits(usage, 3)}`
}} }}
/> />
); );
@ -91,7 +91,7 @@ export class Nodes extends React.Component<Props> {
value={usage} value={usage}
tooltip={{ tooltip={{
preferredPositions: TooltipPosition.BOTTOM, preferredPositions: TooltipPosition.BOTTOM,
children: _i18n._(t`Disk:`) + ` ${Math.ceil(usage * 100 / capacity)}%, ${bytesToUnits(usage, 3)}` children: `${_i18n._(t`Disk:`)} ${Math.ceil(usage * 100 / capacity)}%, ${bytesToUnits(usage, 3)}`
}} }}
/> />
); );

View File

@ -43,7 +43,7 @@ export class CronJobTriggerDialog extends Component<Props> {
onOpen = async () => { onOpen = async () => {
const { cronjob } = this; const { cronjob } = this;
this.jobName = cronjob ? cronjob.getName() + "-manual-" + Math.random().toString(36).slice(2, 7) : ""; this.jobName = cronjob ? `${cronjob.getName()}-manual-${Math.random().toString(36).slice(2, 7)}` : "";
this.jobName = this.jobName.slice(0, 63); this.jobName = this.jobName.slice(0, 63);
this.ready = true; this.ready = true;
}; };

View File

@ -55,7 +55,7 @@ export class OverviewWorkloadStatus extends React.Component<Props> {
if (val !== 0) { if (val !== 0) {
dataset.data.push(val); dataset.data.push(val);
dataset.backgroundColor.push(this.getStatusColor(key)); dataset.backgroundColor.push(this.getStatusColor(key));
chartData.labels.push(capitalize(key) + ": " + val); chartData.labels.push(`${capitalize(key)}: ${val}`);
} }
}); });
chartData.datasets[0] = dataset; chartData.datasets[0] = dataset;

View File

@ -39,7 +39,7 @@ export class PodContainerPort extends React.Component<Props> {
render() { render() {
const { port } = this.props; const { port } = this.props;
const { name, containerPort, protocol } = port; const { name, containerPort, protocol } = port;
const text = (name ? name + ": " : "")+`${containerPort}/${protocol}`; const text = `${name ? `${name}: ` : ""}${containerPort}/${protocol}`;
return ( return (
<div className={cssNames("PodContainerPort", { waiting: this.waiting })}> <div className={cssNames("PodContainerPort", { waiting: this.waiting })}>
<span title={_i18n._(t`Open in a browser`)} onClick={() => this.portForward() }> <span title={_i18n._(t`Open in a browser`)} onClick={() => this.portForward() }>

View File

@ -138,12 +138,12 @@ export class App extends React.Component {
const tabRoutes = this.getTabLayoutRoutes(menu); const tabRoutes = this.getTabLayoutRoutes(menu);
if (tabRoutes.length > 0) { if (tabRoutes.length > 0) {
const pageComponent = () => <TabLayout tabs={tabRoutes} />; const pageComponent = () => <TabLayout tabs={tabRoutes} />;
return <Route key={"extension-tab-layout-route-" + index} component={pageComponent} path={tabRoutes.map((tab) => tab.routePath)} />; return <Route key={`extension-tab-layout-route-${index}`} component={pageComponent} path={tabRoutes.map((tab) => tab.routePath)} />;
} else { } else {
const page = clusterPageRegistry.getByPageMenuTarget(menu.target); const page = clusterPageRegistry.getByPageMenuTarget(menu.target);
if (page) { if (page) {
const pageComponent = () => <page.components.Page />; const pageComponent = () => <page.components.Page />;
return <Route key={"extension-tab-layout-route-" + index} path={page.routePath} exact={page.exact} component={pageComponent}/>; return <Route key={`extension-tab-layout-route-${index}`} path={page.routePath} exact={page.exact} component={pageComponent}/>;
} }
} }
}); });
@ -153,7 +153,7 @@ export class App extends React.Component {
return clusterPageRegistry.getItems().map((page, index) => { return clusterPageRegistry.getItems().map((page, index) => {
const menu = clusterPageMenuRegistry.getByPage(page); const menu = clusterPageMenuRegistry.getByPage(page);
if (!menu) { if (!menu) {
return <Route key={"extension-route-" + index} path={page.routePath} exact={page.exact} component={page.components.Page}/>; return <Route key={`extension-route-${index}`} path={page.routePath} exact={page.exact} component={page.components.Page}/>;
} }
}); });
} }

View File

@ -26,7 +26,7 @@ export class PieChart extends React.Component<Props> {
const metaData = Object.values<{ total: number }>(dataset["_meta"])[0]; const metaData = Object.values<{ total: number }>(dataset["_meta"])[0];
const percent = Math.round((dataset["data"][tooltipItem["index"]] / metaData.total) * 100); const percent = Math.round((dataset["data"][tooltipItem["index"]] / metaData.total) * 100);
if (isNaN(percent)) return "N/A"; if (isNaN(percent)) return "N/A";
return percent + "%"; return `${percent}%`;
}, },
}, },
filter: ({ datasetIndex, index }, { datasets }) => { filter: ({ datasetIndex, index }, { datasets }) => {

View File

@ -46,10 +46,10 @@ export const ZebraStripes = {
if (this.getStripesElem(chart)) return; if (this.getStripesElem(chart)) return;
cover.className = "zebra-cover"; cover.className = "zebra-cover";
styles.width = right - left + "px"; styles.width = `${right - left}px`;
styles.left = left + "px"; styles.left = `${left}px`;
styles.top = top + "px"; styles.top = `${top}px`;
styles.height = bottom - top + "px"; styles.height = `${bottom - top}px`;
styles.backgroundImage = ` styles.backgroundImage = `
repeating-linear-gradient(to right, ${stripeColor} 0px, ${stripeColor} ${stripeWidth}px, repeating-linear-gradient(to right, ${stripeColor} 0px, ${stripeColor} ${stripeWidth}px,
transparent ${stripeWidth}px, transparent ${stripeWidth * 2 + step}px) transparent ${stripeWidth}px, transparent ${stripeWidth * 2 + step}px)
@ -89,7 +89,7 @@ export const ZebraStripes = {
if (minutes > 0) { if (minutes > 0) {
// Move position regarding to difference in time // Move position regarding to difference in time
const cover = this.getStripesElem(chart); const cover = this.getStripesElem(chart);
cover.style.backgroundPositionX = -step * minutes + "px"; cover.style.backgroundPositionX = `${-step * minutes}px`;
} }
} }
}; };

View File

@ -33,7 +33,7 @@ export class Checkbox extends React.PureComponent<CheckboxProps> {
inline, inline,
checked: value, checked: value,
disabled: this.props.disabled, disabled: this.props.disabled,
["theme-" + theme]: theme, [`theme-${theme}`]: theme,
}); });
return ( return (
<label className={componentClass}> <label className={componentClass}>

View File

@ -70,7 +70,7 @@ export class ClusterIcon extends React.Component<Props> {
{showErrors && eventCount > 0 && !isActive && ( {showErrors && eventCount > 0 && !isActive && (
<Badge <Badge
className={cssNames("events-count", errorClass)} className={cssNames("events-count", errorClass)}
label={eventCount >= 1000 ? Math.ceil(eventCount / 1000) + "k+" : eventCount} label={eventCount >= 1000 ? `${Math.ceil(eventCount / 1000)}k+` : eventCount}
/> />
)} )}
{children} {children}

View File

@ -39,7 +39,7 @@ export const PodLogControls = observer((props: Props) => {
const downloadLogs = () => { const downloadLogs = () => {
const fileName = selectedContainer ? selectedContainer.name : pod.getName(); const fileName = selectedContainer ? selectedContainer.name : pod.getName();
saveFileDialog(fileName + ".log", logs.join("\n"), "text/plain"); saveFileDialog(`${fileName}.log`, logs.join("\n"), "text/plain");
}; };
const onContainerChange = (option: SelectOption) => { const onContainerChange = (option: SelectOption) => {
@ -100,7 +100,7 @@ export const PodLogControls = observer((props: Props) => {
material="av_timer" material="av_timer"
onClick={toggleTimestamps} onClick={toggleTimestamps}
className={cssNames("timestamps-icon", { active: showTimestamps })} className={cssNames("timestamps-icon", { active: showTimestamps })}
tooltip={(showTimestamps ? _i18n._(t`Hide`) : _i18n._(t`Show`)) + " " + _i18n._(t`timestamps`)} tooltip={`${showTimestamps ? _i18n._(t`Hide`) : _i18n._(t`Show`)} ${_i18n._(t`timestamps`)}`}
/> />
<Icon <Icon
material="history" material="history"

View File

@ -56,7 +56,7 @@ export class EditableList<T> extends React.Component<Props<T>> {
<div className="el-contents"> <div className="el-contents">
{ {
items.map((item, index) => ( items.map((item, index) => (
<div key={item + `${index}`} className="el-item Badge"> <div key={`${item}${index}`} className="el-item Badge">
<div>{renderItem(item, index)}</div> <div>{renderItem(item, index)}</div>
<div className="el-value-remove"> <div className="el-value-remove">
<Icon material="delete_outline" onClick={() => remove(({ index, oldItem: item }))} /> <Icon material="delete_outline" onClick={() => remove(({ index, oldItem: item }))} />

View File

@ -89,7 +89,7 @@ export class Icon extends React.PureComponent<IconProps> {
// render as inline svg-icon // render as inline svg-icon
if (svg) { if (svg) {
const svgIconText = require("!!raw-loader!./" + svg + ".svg").default; const svgIconText = require(`!!raw-loader!./${svg}.svg`).default;
iconContent = <span className="icon" dangerouslySetInnerHTML={{ __html: svgIconText }}/>; iconContent = <span className="icon" dangerouslySetInnerHTML={{ __html: svgIconText }}/>;
} }

View File

@ -104,7 +104,7 @@ export class Input extends React.Component<InputProps, State> {
const lineHeight = parseFloat(window.getComputedStyle(textArea).lineHeight); const lineHeight = parseFloat(window.getComputedStyle(textArea).lineHeight);
const rowsCount = (this.getValue().match(/\n/g) || []).length + 1; const rowsCount = (this.getValue().match(/\n/g) || []).length + 1;
const height = lineHeight * Math.min(Math.max(rowsCount, rows), maxRows); const height = lineHeight * Math.min(Math.max(rowsCount, rows), maxRows);
textArea.style.height = height + "px"; textArea.style.height = `${height}px`;
} }
private validationId: string; private validationId: string;

View File

@ -115,7 +115,7 @@ export class Sidebar extends React.Component<Props> {
} }
return ( return (
<SidebarNavItem <SidebarNavItem
key={"registered-item-" + index} key={`registered-item-${index}`}
url={pageUrl} url={pageUrl}
text={menuItem.title} text={menuItem.title}
icon={<menuItem.components.Icon/>} icon={<menuItem.components.Icon/>}

View File

@ -29,7 +29,7 @@ export class LineProgress extends React.PureComponent<LineProgressProps> {
} }
return ( return (
<div className={cssNames("LineProgress", className)} {...props}> <div className={cssNames("LineProgress", className)} {...props}>
<div className="line" style={{ width: valuePercents + "%" }}></div> <div className="line" style={{ width: `${valuePercents}%` }}></div>
{children} {children}
</div> </div>
); );

View File

@ -129,18 +129,18 @@ export class Menu extends React.Component<MenuProps, State> {
// setup initial position // setup initial position
const position: MenuPosition = { left: true, bottom: true }; const position: MenuPosition = { left: true, bottom: true };
this.elem.style.left = left + "px"; this.elem.style.left = `${left}px`;
this.elem.style.top = bottom + "px"; this.elem.style.top = `${bottom}px`;
// correct position if menu doesn't fit to viewport // correct position if menu doesn't fit to viewport
const menuPos = this.elem.getBoundingClientRect(); const menuPos = this.elem.getBoundingClientRect();
if (menuPos.right > window.innerWidth) { if (menuPos.right > window.innerWidth) {
this.elem.style.left = (right - this.elem.offsetWidth) + "px"; this.elem.style.left = `${right - this.elem.offsetWidth}px`;
position.right = true; position.right = true;
delete position.left; delete position.left;
} }
if (menuPos.bottom > window.innerHeight) { if (menuPos.bottom > window.innerHeight) {
this.elem.style.top = (top - this.elem.offsetHeight) + "px"; this.elem.style.top = `${top - this.elem.offsetHeight}px`;
position.top = true; position.top = true;
delete position.bottom; delete position.bottom;
} }

View File

@ -133,8 +133,8 @@ export class Tooltip extends React.Component<TooltipProps> {
protected setPosition(pos: { left: number, top: number }) { protected setPosition(pos: { left: number, top: number }) {
const elemStyle = this.elem.style; const elemStyle = this.elem.style;
elemStyle.left = pos.left + "px"; elemStyle.left = `${pos.left}px`;
elemStyle.top = pos.top + "px"; elemStyle.top = `${pos.top}px`;
} }
protected getPosition(position: TooltipPosition, tooltipBounds: DOMRect, targetBounds: DOMRect) { protected getPosition(position: TooltipPosition, tooltipBounds: DOMRect, targetBounds: DOMRect) {

View File

@ -10,7 +10,7 @@ export function cssVar(elem: HTMLElement) {
}; };
}, },
set(name: string, value: number | string) { set(name: string, value: number | string) {
if (typeof value === "number") value = value + "px"; if (typeof value === "number") value = `${value}px`;
elem.style.setProperty(name, value); elem.style.setProperty(name, value);
} }
}; };