mirror of
https://github.com/lensapp/lens.git
synced 2025-05-20 05:10:56 +00:00
Merge branch 'master' into show-extension-preferences-in-separate-page
This commit is contained in:
commit
00efcad5ee
39 files changed
+2567
-1789
No files matched your search
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
.ClusterNoMetrics {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
line-height: 1.7;
|
||||
flex-grow: 1;
|
||||
|
||||
.link {
|
||||
color: var(--blue);
|
||||
cursor: pointer;
|
||||
}
|
||||
}
|
||||
@@ -3,20 +3,53 @@
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import styles from "./cluster-no-metrics.module.scss";
|
||||
|
||||
import React from "react";
|
||||
import { Icon } from "../icon";
|
||||
import { cssNames } from "../../utils";
|
||||
import type { NavigateToEntitySettings } from "../../../common/front-end-routing/routes/entity-settings/navigate-to-entity-settings.injectable";
|
||||
import { withInjectables } from "@ogre-tools/injectable-react";
|
||||
import navigateToEntitySettingsInjectable from "../../../common/front-end-routing/routes/entity-settings/navigate-to-entity-settings.injectable";
|
||||
import hostedClusterInjectable from "../../../common/cluster-store/hosted-cluster.injectable";
|
||||
|
||||
export interface ClusterNoMetricsProps {
|
||||
className: string;
|
||||
}
|
||||
|
||||
export function ClusterNoMetrics({ className }: ClusterNoMetricsProps) {
|
||||
interface Dependencies {
|
||||
navigateToEntitySettings: NavigateToEntitySettings;
|
||||
clusterId: string | undefined;
|
||||
}
|
||||
|
||||
export function NonInjectedClusterNoMetrics({ className, navigateToEntitySettings, clusterId }: Dependencies & ClusterNoMetricsProps) {
|
||||
function openMetricSettingsPage() {
|
||||
if (clusterId) {
|
||||
navigateToEntitySettings(clusterId, "metrics");
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cssNames("ClusterNoMetrics flex column box grow justify-center align-center", className)}>
|
||||
<div className={cssNames(styles.ClusterNoMetrics, className)} data-testid="no-metrics-message">
|
||||
<Icon material="info"/>
|
||||
<p>Metrics are not available due to missing or invalid Prometheus configuration.</p>
|
||||
<p>Right click cluster icon to open cluster settings.</p>
|
||||
<p><span className={styles.link} onClick={openMetricSettingsPage}>Open cluster settings</span></p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export const ClusterNoMetrics = withInjectables<Dependencies, ClusterNoMetricsProps>(
|
||||
NonInjectedClusterNoMetrics,
|
||||
|
||||
{
|
||||
getProps: (di, props) => {
|
||||
const cluster = di.inject(hostedClusterInjectable);
|
||||
|
||||
return {
|
||||
navigateToEntitySettings: di.inject(navigateToEntitySettingsInjectable),
|
||||
clusterId: cluster?.id,
|
||||
...props,
|
||||
};
|
||||
},
|
||||
},
|
||||
);
|
||||
@@ -7,7 +7,7 @@
|
||||
background: var(--contentColor);
|
||||
min-height: 280px;
|
||||
text-align: center;
|
||||
padding: calc(var(--padding) * 2) 0;
|
||||
padding: calc(var(--padding) * 2);
|
||||
}
|
||||
|
||||
.chart {
|
||||
@@ -15,3 +15,8 @@
|
||||
background: var(--contentColor);
|
||||
padding: calc(var(--padding) * 2) var(--padding);
|
||||
}
|
||||
|
||||
.noMetrics {
|
||||
display: flex;
|
||||
flex-grow: 1;
|
||||
}
|
||||
@@ -232,7 +232,11 @@ const NonInjectedClusterPieCharts = observer(({ clusterOverviewStore }: Dependen
|
||||
const { memoryCapacity, cpuCapacity, podCapacity } = getMetricLastPoints(clusterOverviewStore.metrics);
|
||||
|
||||
if (!memoryCapacity || !cpuCapacity || !podCapacity) {
|
||||
return <ClusterNoMetrics className={styles.empty}/>;
|
||||
return (
|
||||
<div className={styles.noMetrics}>
|
||||
<ClusterNoMetrics className={styles.empty}/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return renderCharts();
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
import "./crd-resource-details.scss";
|
||||
|
||||
import React from "react";
|
||||
import jsonPath from "jsonpath";
|
||||
import { observer } from "mobx-react";
|
||||
import { cssNames } from "../../utils";
|
||||
import { Badge } from "../badge";
|
||||
@@ -16,10 +15,11 @@ import { KubeObjectMeta } from "../kube-object-meta";
|
||||
import { Input } from "../input";
|
||||
import type { AdditionalPrinterColumnsV1 } from "../../../common/k8s-api/endpoints/crd.api";
|
||||
import { CustomResourceDefinition } from "../../../common/k8s-api/endpoints/crd.api";
|
||||
import { parseJsonPath } from "../../utils/jsonPath";
|
||||
import { convertKubectlJsonPathToNodeJsonPath } from "../../utils/jsonPath";
|
||||
import type { KubeObjectMetadata, KubeObjectStatus } from "../../../common/k8s-api/kube-object";
|
||||
import { KubeObject } from "../../../common/k8s-api/kube-object";
|
||||
import logger from "../../../common/logger";
|
||||
import { JSONPath } from "@astronautlabs/jsonpath";
|
||||
|
||||
export interface CustomResourceDetailsProps extends KubeObjectDetailsProps<KubeObject> {
|
||||
crd: CustomResourceDefinition;
|
||||
@@ -48,9 +48,9 @@ function convertSpecValue(value: any): any {
|
||||
@observer
|
||||
export class CustomResourceDetails extends React.Component<CustomResourceDetailsProps> {
|
||||
renderAdditionalColumns(resource: KubeObject, columns: AdditionalPrinterColumnsV1[]) {
|
||||
return columns.map(({ name, jsonPath: jp }) => (
|
||||
return columns.map(({ name, jsonPath }) => (
|
||||
<DrawerItem key={name} name={name} renderBoolean>
|
||||
{convertSpecValue(jsonPath.value(resource, parseJsonPath(jp.slice(1))))}
|
||||
{convertSpecValue(JSONPath.query(resource, convertKubectlJsonPathToNodeJsonPath(jsonPath)))}
|
||||
</DrawerItem>
|
||||
));
|
||||
}
|
||||
|
||||
@@ -6,14 +6,13 @@
|
||||
import "./crd-resources.scss";
|
||||
|
||||
import React from "react";
|
||||
import { value } from "jsonpath";
|
||||
import { observer } from "mobx-react";
|
||||
import { KubeObjectListLayout } from "../kube-object-list-layout";
|
||||
import type { IComputedValue } from "mobx";
|
||||
import { computed, makeObservable } from "mobx";
|
||||
import { crdStore } from "./crd.store";
|
||||
import { apiManager } from "../../../common/k8s-api/api-manager";
|
||||
import { parseJsonPath } from "../../utils/jsonPath";
|
||||
import { safeJSONPathValue } from "../../utils/jsonPath";
|
||||
import { TabLayout } from "../layout/tab-layout-2";
|
||||
import { withInjectables } from "@ogre-tools/injectable-react";
|
||||
import customResourcesRouteParametersInjectable from "./custom-resources-route-parameters.injectable";
|
||||
@@ -70,7 +69,7 @@ class NonInjectedCrdResources extends React.Component<Dependencies> {
|
||||
[columnId.age]: customResource => -customResource.getCreationTimestamp(),
|
||||
...Object.fromEntries(extraColumns.map(({ name, jsonPath }) => [
|
||||
name,
|
||||
customResource => value(customResource, parseJsonPath(jsonPath.slice(1))),
|
||||
customResource => safeJSONPathValue(customResource, jsonPath),
|
||||
])),
|
||||
}}
|
||||
searchFilters={[
|
||||
@@ -95,22 +94,11 @@ class NonInjectedCrdResources extends React.Component<Dependencies> {
|
||||
})),
|
||||
{ title: "Age", className: "age", sortBy: columnId.age, id: columnId.age },
|
||||
]}
|
||||
renderTableContents={crdInstance => [
|
||||
crdInstance.getName(),
|
||||
isNamespaced && crdInstance.getNs(),
|
||||
...extraColumns.map((column) => {
|
||||
let rawValue = value(crdInstance, parseJsonPath(column.jsonPath.slice(1)));
|
||||
|
||||
if (Array.isArray(rawValue) || typeof rawValue === "object") {
|
||||
rawValue = JSON.stringify(rawValue);
|
||||
}
|
||||
|
||||
return {
|
||||
renderBoolean: true,
|
||||
children: rawValue,
|
||||
};
|
||||
}),
|
||||
<KubeObjectAge key="age" object={crdInstance} />,
|
||||
renderTableContents={customResource => [
|
||||
customResource.getName(),
|
||||
isNamespaced && customResource.getNs(),
|
||||
...extraColumns.map((column) => safeJSONPathValue(customResource, column.jsonPath)),
|
||||
<KubeObjectAge key="age" object={customResource} />,
|
||||
]}
|
||||
failedToLoadMessage={(
|
||||
<>
|
||||
|
||||
@@ -7,8 +7,7 @@ import "./namespace-select-filter.scss";
|
||||
|
||||
import React from "react";
|
||||
import { observer } from "mobx-react";
|
||||
import type { OptionTypeBase, PlaceholderProps } from "react-select";
|
||||
import { components } from "react-select";
|
||||
import { components, type PlaceholderProps } from "react-select";
|
||||
|
||||
import { Icon } from "../icon";
|
||||
import { NamespaceSelect } from "./namespace-select";
|
||||
@@ -78,7 +77,7 @@ export const NamespaceSelectFilter = withInjectables<Dependencies, SelectProps>(
|
||||
}),
|
||||
});
|
||||
|
||||
export interface CustomPlaceholderProps extends PlaceholderProps<OptionTypeBase, boolean> {}
|
||||
export interface CustomPlaceholderProps extends PlaceholderProps {}
|
||||
|
||||
interface PlaceholderDependencies {
|
||||
namespaceStore: NamespaceStore;
|
||||
|
||||
@@ -64,7 +64,7 @@ const NonInjectedKubectlBinaries: React.FC<Dependencies> = observer(
|
||||
options={downloadMirrorOptions}
|
||||
value={userStore.downloadMirror}
|
||||
onChange={({ value }: SelectOption) => userStore.downloadMirror = value}
|
||||
disabled={!userStore.downloadKubectlBinaries}
|
||||
isDisabled={!userStore.downloadKubectlBinaries}
|
||||
isOptionDisabled={({ platforms }) =>
|
||||
!platforms.has(process.platform)
|
||||
}
|
||||
|
||||
@@ -9,12 +9,12 @@ import { observer } from "mobx-react";
|
||||
import { action, computed, makeObservable, observable, reaction } from "mobx";
|
||||
import { editor, Uri } from "monaco-editor";
|
||||
import type { MonacoTheme } from "./monaco-themes";
|
||||
import type { MonacoValidator } from "./monaco-validators";
|
||||
import { monacoValidators } from "./monaco-validators";
|
||||
import { type MonacoValidator, monacoValidators } from "./monaco-validators";
|
||||
import { debounce, merge } from "lodash";
|
||||
import { cssNames, disposer } from "../../utils";
|
||||
import { autoBind, cssNames, disposer } from "../../utils";
|
||||
import { UserStore } from "../../../common/user-store";
|
||||
import { ThemeStore } from "../../theme.store";
|
||||
import logger from "../../../main/logger";
|
||||
|
||||
export type MonacoEditorId = string;
|
||||
|
||||
@@ -45,32 +45,28 @@ export const defaultEditorProps: Partial<MonacoEditorProps> = {
|
||||
|
||||
@observer
|
||||
export class MonacoEditor extends React.Component<MonacoEditorProps> {
|
||||
static defaultProps = defaultEditorProps as object;
|
||||
static viewStates = new WeakMap<Uri, editor.ICodeEditorViewState>();
|
||||
static readonly defaultProps = defaultEditorProps as object;
|
||||
static readonly viewStates = new WeakMap<Uri, editor.ICodeEditorViewState>();
|
||||
|
||||
static createUri(id: MonacoEditorId): Uri {
|
||||
return Uri.file(`/monaco-editor/${id}`);
|
||||
}
|
||||
|
||||
public staticId = `editor-id#${Math.round(1e7 * Math.random())}`;
|
||||
public dispose = disposer();
|
||||
|
||||
// TODO: investigate how to replace with "common/logger"
|
||||
// currently leads for stucking UI forever & infinite loop.
|
||||
// e.g. happens on tab change/create, maybe some other cases too.
|
||||
logger = console;
|
||||
private staticId = `editor-id#${Math.round(1e7 * Math.random())}`;
|
||||
private dispose = disposer();
|
||||
|
||||
@observable.ref containerElem: HTMLElement;
|
||||
@observable.ref editor: editor.IStandaloneCodeEditor;
|
||||
@observable dimensions: { width?: number; height?: number } = {};
|
||||
@observable unmounting = false;
|
||||
@observable readonly dimensions: { width?: number; height?: number } = {};
|
||||
@observable private unmounting = false;
|
||||
|
||||
constructor(props: MonacoEditorProps) {
|
||||
super(props);
|
||||
makeObservable(this);
|
||||
autoBind(this);
|
||||
}
|
||||
|
||||
@computed get id() {
|
||||
@computed get id(): MonacoEditorId {
|
||||
return this.props.id ?? this.staticId;
|
||||
}
|
||||
|
||||
@@ -94,7 +90,8 @@ export class MonacoEditor extends React.Component<MonacoEditorProps> {
|
||||
);
|
||||
}
|
||||
|
||||
@computed get logMetadata() {
|
||||
@computed
|
||||
private get logMetadata() {
|
||||
return {
|
||||
editorId: this.id,
|
||||
model: this.model,
|
||||
@@ -121,8 +118,8 @@ export class MonacoEditor extends React.Component<MonacoEditorProps> {
|
||||
return () => resizeObserver.unobserve(containerElem);
|
||||
}
|
||||
|
||||
onModelChange = (model: editor.ITextModel, oldModel?: editor.ITextModel) => {
|
||||
this.logger?.info("[MONACO]: model change", { model, oldModel }, this.logMetadata);
|
||||
protected onModelChange(model: editor.ITextModel, oldModel?: editor.ITextModel) {
|
||||
logger.info("[MONACO]: model change", { model, oldModel }, this.logMetadata);
|
||||
|
||||
if (oldModel) {
|
||||
this.saveViewState(oldModel);
|
||||
@@ -134,18 +131,17 @@ export class MonacoEditor extends React.Component<MonacoEditorProps> {
|
||||
this.editor.focus(); // keep focus in editor, e.g. when clicking between dock-tabs
|
||||
this.props.onModelChange?.(model, oldModel);
|
||||
this.validateLazy();
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Save current view-model state in the editor.
|
||||
* This will allow restore cursor position, selected text, etc.
|
||||
* @param {editor.ITextModel} model
|
||||
*/
|
||||
private saveViewState(model: editor.ITextModel) {
|
||||
protected saveViewState(model: editor.ITextModel) {
|
||||
MonacoEditor.viewStates.set(model.uri, this.editor.saveViewState());
|
||||
}
|
||||
|
||||
private restoreViewState(model: editor.ITextModel) {
|
||||
protected restoreViewState(model: editor.ITextModel) {
|
||||
const viewState = MonacoEditor.viewStates.get(model.uri);
|
||||
|
||||
if (viewState) {
|
||||
@@ -156,9 +152,9 @@ export class MonacoEditor extends React.Component<MonacoEditorProps> {
|
||||
componentDidMount() {
|
||||
try {
|
||||
this.createEditor();
|
||||
this.logger?.info(`[MONACO]: editor did mount`, this.logMetadata);
|
||||
logger.info(`[MONACO]: editor did mount`, this.logMetadata);
|
||||
} catch (error) {
|
||||
this.logger?.error(`[MONACO]: mounting failed: ${error}`, this.logMetadata);
|
||||
logger.error(`[MONACO]: mounting failed: ${error}`, this.logMetadata);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -168,7 +164,7 @@ export class MonacoEditor extends React.Component<MonacoEditorProps> {
|
||||
this.destroy();
|
||||
}
|
||||
|
||||
private createEditor() {
|
||||
protected createEditor() {
|
||||
if (!this.containerElem || this.editor || this.unmounting) {
|
||||
return;
|
||||
}
|
||||
@@ -184,7 +180,7 @@ export class MonacoEditor extends React.Component<MonacoEditorProps> {
|
||||
...this.options,
|
||||
});
|
||||
|
||||
this.logger?.info(`[MONACO]: editor created for language=${language}, theme=${theme}`, this.logMetadata);
|
||||
logger.info(`[MONACO]: editor created for language=${language}, theme=${theme}`, this.logMetadata);
|
||||
this.validateLazy(); // validate initial value
|
||||
this.restoreViewState(this.model); // restore previous state if any
|
||||
|
||||
@@ -250,7 +246,8 @@ export class MonacoEditor extends React.Component<MonacoEditorProps> {
|
||||
this.editor?.focus();
|
||||
}
|
||||
|
||||
validate = action((value = this.getValue()) => {
|
||||
@action
|
||||
validate(value = this.getValue()) {
|
||||
const validators: MonacoValidator[] = [
|
||||
monacoValidators[this.props.language], // parsing syntax check
|
||||
].filter(Boolean);
|
||||
@@ -262,19 +259,21 @@ export class MonacoEditor extends React.Component<MonacoEditorProps> {
|
||||
this.props.onError?.(error); // emit error outside
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// avoid excessive validations during typing
|
||||
validateLazy = debounce(this.validate, 250);
|
||||
|
||||
bindRef = (elem: HTMLElement) => this.containerElem = elem;
|
||||
protected bindRef(elem: HTMLElement) {
|
||||
this.containerElem = elem;
|
||||
}
|
||||
|
||||
render() {
|
||||
const { className, style } = this.props;
|
||||
|
||||
return (
|
||||
<div
|
||||
data-test-component="monaco-editor"
|
||||
data-test-id="monaco-editor"
|
||||
className={cssNames(styles.MonacoEditor, className)}
|
||||
style={style}
|
||||
ref={this.bindRef}
|
||||
|
||||
@@ -7,22 +7,25 @@
|
||||
// API docs: https://react-select.com/
|
||||
import "./select.scss";
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
import React from "react";
|
||||
import { computed, makeObservable } from "mobx";
|
||||
import { observer } from "mobx-react";
|
||||
import ReactSelect, { components } from "react-select";
|
||||
import ReactSelectCreatable from "react-select/creatable";
|
||||
import type { ActionMeta, OptionTypeBase, Props as ReactSelectProps, Styles } from "react-select";
|
||||
import type { CreatableProps } from "react-select/creatable";
|
||||
|
||||
import ReactSelect, {
|
||||
type ActionMeta,
|
||||
components,
|
||||
type GroupBase,
|
||||
type Props as ReactSelectProps,
|
||||
type StylesConfig,
|
||||
} from "react-select";
|
||||
import ReactSelectCreatable, { type CreatableProps } from "react-select/creatable";
|
||||
import { ThemeStore } from "../../theme.store";
|
||||
import { autoBind, cssNames } from "../../utils";
|
||||
import { merge } from "lodash";
|
||||
|
||||
const { Menu } = components;
|
||||
|
||||
export interface GroupSelectOption<T extends SelectOption = SelectOption> {
|
||||
label: ReactNode;
|
||||
label: React.ReactNode;
|
||||
options: T[];
|
||||
}
|
||||
|
||||
@@ -31,7 +34,7 @@ export interface SelectOption<T = any> {
|
||||
label?: React.ReactNode;
|
||||
}
|
||||
|
||||
export interface SelectProps<T = any> extends ReactSelectProps<T, boolean>, CreatableProps<T, boolean> {
|
||||
export interface SelectProps<T = any> extends ReactSelectProps<T, boolean>, CreatableProps<T, boolean, GroupBase<T>> {
|
||||
id?: string; // Optional only because of Extension API. Required to make Select deterministic in unit tests
|
||||
value?: T;
|
||||
themeName?: "dark" | "light" | "outlined" | "lens";
|
||||
@@ -61,12 +64,16 @@ export class Select extends React.Component<SelectProps> {
|
||||
return `theme-${themeName}`;
|
||||
}
|
||||
|
||||
private styles: Styles<OptionTypeBase, boolean> = {
|
||||
menuPortal: styles => ({
|
||||
...styles,
|
||||
zIndex: "auto",
|
||||
}),
|
||||
};
|
||||
@computed get styles(): StylesConfig {
|
||||
const defaultStyles: StylesConfig = {
|
||||
menuPortal: styles => ({
|
||||
...styles,
|
||||
zIndex: "auto",
|
||||
}),
|
||||
};
|
||||
|
||||
return merge(defaultStyles, this.props.styles);
|
||||
}
|
||||
|
||||
protected isValidOption(opt: SelectOption | any) {
|
||||
return typeof opt === "object" && opt.value !== undefined;
|
||||
@@ -104,7 +111,7 @@ export class Select extends React.Component<SelectProps> {
|
||||
}
|
||||
}
|
||||
|
||||
onKeyDown(evt: React.KeyboardEvent<HTMLElement>) {
|
||||
onKeyDown(evt: React.KeyboardEvent<HTMLDivElement>) {
|
||||
if (this.props.onKeyDown) {
|
||||
this.props.onKeyDown(evt);
|
||||
}
|
||||
@@ -122,7 +129,7 @@ export class Select extends React.Component<SelectProps> {
|
||||
|
||||
const selectProps: Partial<SelectProps> = {
|
||||
...props,
|
||||
...(inputId ? { inputId }: {}),
|
||||
...(inputId ? { inputId } : {}),
|
||||
styles: this.styles,
|
||||
value: autoConvertOptions ? this.selectedOption : value,
|
||||
options: autoConvertOptions ? this.options : options,
|
||||
@@ -142,7 +149,7 @@ export class Select extends React.Component<SelectProps> {
|
||||
};
|
||||
|
||||
return isCreatable
|
||||
? <ReactSelectCreatable {...selectProps}/>
|
||||
: <ReactSelect {...selectProps}/>;
|
||||
? <ReactSelectCreatable {...selectProps} /> // select list with ability to add new options
|
||||
: <ReactSelect {...selectProps} />;
|
||||
}
|
||||
}
|
||||
@@ -3,44 +3,166 @@
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import { parseJsonPath } from "../jsonPath";
|
||||
import { convertKubectlJsonPathToNodeJsonPath, safeJSONPathValue } from "../jsonPath";
|
||||
|
||||
describe("parseJsonPath", () => {
|
||||
test("should convert \\. to use indexed notation", () => {
|
||||
const res = parseJsonPath(".metadata.labels.kubesphere\\.io/alias-name");
|
||||
it("should convert \\. to use indexed notation", () => {
|
||||
const res = convertKubectlJsonPathToNodeJsonPath(".metadata.labels.kubesphere\\.io/alias-name");
|
||||
|
||||
expect(res).toBe(".metadata.labels['kubesphere.io/alias-name']");
|
||||
expect(res).toBe("$.metadata.labels['kubesphere.io/alias-name']");
|
||||
});
|
||||
|
||||
test("should convert keys with escaped characters to use indexed notation", () => {
|
||||
const res = parseJsonPath(".metadata.labels.kubesphere\\\"io/alias-name");
|
||||
it("should convert keys with escaped characters to use indexed notation", () => {
|
||||
const res = convertKubectlJsonPathToNodeJsonPath(".metadata.labels.kubesphere\\\"io/alias-name");
|
||||
|
||||
expect(res).toBe(".metadata.labels['kubesphere\"io/alias-name']");
|
||||
expect(res).toBe("$.metadata.labels['kubesphere\"io/alias-name']");
|
||||
});
|
||||
|
||||
test("should convert '-' to use indexed notation", () => {
|
||||
const res = parseJsonPath(".metadata.labels.alias-name");
|
||||
it("should convert '-' to use indexed notation", () => {
|
||||
const res = convertKubectlJsonPathToNodeJsonPath(".metadata.labels.alias-name");
|
||||
|
||||
expect(res).toBe(".metadata.labels['alias-name']");
|
||||
expect(res).toBe("$.metadata.labels['alias-name']");
|
||||
});
|
||||
|
||||
test("should handle scenario when both \\. and indexed notation are present", () => {
|
||||
const rest = parseJsonPath(".metadata.labels\\.serving['some.other.item']");
|
||||
it("should drop leading dot if first group is converted to index notation", () => {
|
||||
const res = convertKubectlJsonPathToNodeJsonPath(".metadata\\.labels.alias-name");
|
||||
|
||||
expect(rest).toBe(".metadata['labels.serving']['some.other.item']");
|
||||
expect(res).toBe("$['metadata.labels']['alias-name']");
|
||||
});
|
||||
|
||||
it("should handle scenario when both \\. and indexed notation are present", () => {
|
||||
const rest = convertKubectlJsonPathToNodeJsonPath(".metadata.labels\\.serving['some.other.item']");
|
||||
|
||||
test("should not touch given jsonPath if no invalid characters present", () => {
|
||||
const res = parseJsonPath(".status.conditions[?(@.type=='Ready')].status");
|
||||
|
||||
expect(res).toBe(".status.conditions[?(@.type=='Ready')].status");
|
||||
expect(rest).toBe("$.metadata['labels.serving']['some.other.item']");
|
||||
});
|
||||
|
||||
test("strips '\\' away from the result", () => {
|
||||
const res = parseJsonPath(".metadata.labels['serving\\.knative\\.dev/configuration']");
|
||||
it("should not touch given jsonPath if no invalid characters present", () => {
|
||||
const res = convertKubectlJsonPathToNodeJsonPath(".status.conditions[?(@.type=='Ready')].status");
|
||||
|
||||
expect(res).toBe(".metadata.labels['serving.knative.dev/configuration']");
|
||||
expect(res).toBe("$.status.conditions[?(@.type=='Ready')].status");
|
||||
});
|
||||
|
||||
it("strips '\\' away from the result", () => {
|
||||
const res = convertKubectlJsonPathToNodeJsonPath(".metadata.labels['serving\\.knative\\.dev/configuration']");
|
||||
|
||||
expect(res).toBe("$.metadata.labels['serving.knative.dev/configuration']");
|
||||
});
|
||||
|
||||
it("converts all [] to [0]", () => {
|
||||
const res = convertKubectlJsonPathToNodeJsonPath(".metadata.labels[].foo[]");
|
||||
|
||||
expect(res).toBe("$.metadata.labels[0].foo[0]");
|
||||
});
|
||||
|
||||
it("converts ending .. to ..*", () => {
|
||||
const res = convertKubectlJsonPathToNodeJsonPath(".metadata.labels[]..");
|
||||
|
||||
expect(res).toBe("$.metadata.labels[0]");
|
||||
});
|
||||
|
||||
it("converts ending ...name to ..name", () => {
|
||||
const res = convertKubectlJsonPathToNodeJsonPath(".metadata.labels[]...name");
|
||||
|
||||
expect(res).toBe("$.metadata.labels[0]..name");
|
||||
});
|
||||
});
|
||||
|
||||
describe("safeJSONPathValue", () => {
|
||||
let oldWarn: typeof console["warn"];
|
||||
|
||||
beforeEach(() => {
|
||||
oldWarn = console.warn;
|
||||
console.warn = jest.fn();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
console.warn = oldWarn;
|
||||
});
|
||||
|
||||
it("should convert boolean values to strings", () => {
|
||||
const res = safeJSONPathValue({ bar: false }, ".bar");
|
||||
|
||||
expect(res).toBe("false");
|
||||
});
|
||||
|
||||
it("should convert number values to strings", () => {
|
||||
const res = safeJSONPathValue({ bar: 0 }, ".bar");
|
||||
|
||||
expect(res).toBe("0");
|
||||
});
|
||||
|
||||
it("should join sliced entries with commas only", () => {
|
||||
const res = safeJSONPathValue({
|
||||
bar: [
|
||||
{
|
||||
foo: 1,
|
||||
},
|
||||
{
|
||||
foo: "hello",
|
||||
},
|
||||
],
|
||||
}, ".bar[].foo");
|
||||
|
||||
expect(res).toBe("1");
|
||||
});
|
||||
|
||||
it("should join an array of values using JSON.stringify", () => {
|
||||
const res = safeJSONPathValue({
|
||||
bar: [
|
||||
"world",
|
||||
"hello",
|
||||
],
|
||||
}, ".bar");
|
||||
|
||||
expect(res).toBe(`["world","hello"]`);
|
||||
});
|
||||
|
||||
it("should stringify an object value", () => {
|
||||
const res = safeJSONPathValue({
|
||||
foo: { bar: "bat" },
|
||||
}, ".foo");
|
||||
|
||||
expect(res).toBe(`{"bar":"bat"}`);
|
||||
});
|
||||
|
||||
it("should use convertKubectlJsonPathToNodeJsonPath", () => {
|
||||
const res = safeJSONPathValue({
|
||||
foo: { "hello.world": "bat" },
|
||||
}, ".foo.hello\\.world");
|
||||
|
||||
expect(res).toBe("bat");
|
||||
});
|
||||
|
||||
it("should not throw when given '.spec.metrics[*].external.highWatermark..'", () => {
|
||||
const obj = {
|
||||
spec: {
|
||||
metrics: [
|
||||
{
|
||||
external: {
|
||||
metricName: "cpu",
|
||||
highWatermark: "100",
|
||||
},
|
||||
},
|
||||
{
|
||||
external: {
|
||||
metricName: "memory",
|
||||
highWatermark: "100",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const res = safeJSONPathValue(obj, ".spec.metrics[*].external.highWatermark..");
|
||||
|
||||
expect(res).toBe("100, 100");
|
||||
});
|
||||
|
||||
it("should not throw if path is invalid jsonpath", () => {
|
||||
const res = safeJSONPathValue({
|
||||
foo: { "hello.world": "bat" },
|
||||
}, "asd[");
|
||||
|
||||
expect(res).toBe("<unknown>");
|
||||
});
|
||||
});
|
||||
@@ -3,28 +3,63 @@
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
// Helper to convert strings used for jsonPath where \. or - is present to use indexed notation,
|
||||
// for example: .metadata.labels.kubesphere\.io/alias-name -> .metadata.labels['kubesphere\.io/alias-name']
|
||||
import { JSONPath } from "@astronautlabs/jsonpath";
|
||||
|
||||
export function parseJsonPath(jsonPath: string) {
|
||||
let pathExpression = jsonPath;
|
||||
const slashDashSearch = /[\\-]/g;
|
||||
const pathByBareDots = /(?<=\w)\./;
|
||||
const textBeforeFirstSquare = /^.*(?=\[)/g;
|
||||
const backSlash = /\\/g;
|
||||
const kubectlOptionPrefix = /^\$?\.?(?<pathExpression>.*)/;
|
||||
const sliceVersion = /\[]/g;
|
||||
const tripleDotName = /\.\.\.(?<trailing>.)/g;
|
||||
const trailingDotDot = /\.\.$/;
|
||||
|
||||
if (jsonPath.match(/[\\-]/g)) { // search for '\' and '-'
|
||||
const [first, ...rest] = jsonPath.split(/(?<=\w)\./); // split jsonPath by '.' (\. cases are ignored)
|
||||
/**
|
||||
* The GO package that kubectl and kubernetes uses for its JSONpath implementation has some
|
||||
* shorthand conveniences that are not part of the official spec. This function tries to convert
|
||||
* those shorthands to the official spec.
|
||||
*
|
||||
* Known shorthands:
|
||||
* - Leading `$` is optional (but implied)
|
||||
* - The string `\.` is used to denote the "value of '.'" and not "next key"
|
||||
* - The string `-` can be used while not in quotes
|
||||
* - `[]` as shorthand for `[0]`
|
||||
* - Remove `..` at the end of a path, we will just format it slightly differently
|
||||
* - Allow `...foo` as well as `..foo`
|
||||
*/
|
||||
export function convertKubectlJsonPathToNodeJsonPath(jsonPath: string) {
|
||||
const startMatch = jsonPath.match(kubectlOptionPrefix);
|
||||
let start = "$";
|
||||
|
||||
if (!startMatch) {
|
||||
return start;
|
||||
}
|
||||
|
||||
let { pathExpression } = startMatch.groups;
|
||||
|
||||
if (pathExpression.match(slashDashSearch)) {
|
||||
const [first, ...rest] = pathExpression.split(pathByBareDots);
|
||||
|
||||
pathExpression = `${convertToIndexNotation(first, true)}${rest.map(value => convertToIndexNotation(value)).join("")}`;
|
||||
}
|
||||
|
||||
pathExpression = pathExpression.replace(trailingDotDot, "");
|
||||
pathExpression = pathExpression.replace(tripleDotName, "..$<trailing>");
|
||||
|
||||
if (!pathExpression.startsWith("[")) {
|
||||
start += ".";
|
||||
}
|
||||
|
||||
// strip '\' characters from the result
|
||||
return pathExpression.replace(/\\/g, "");
|
||||
return `${start}${pathExpression.replace(backSlash, "").replace(sliceVersion, "[0]")}`;
|
||||
}
|
||||
|
||||
function convertToIndexNotation(key: string, firstItem = false) {
|
||||
if (key.match(/[\\-]/g)) { // check if found '\' and '-' in key
|
||||
if (key.match(slashDashSearch)) {
|
||||
if (key.includes("[")) { // handle cases where key contains [...]
|
||||
const keyToConvert = key.match(/^.*(?=\[)/g); // get the text from the key before '['
|
||||
const keyToConvert = key.match(textBeforeFirstSquare); // get the text from the key before '['
|
||||
|
||||
if (keyToConvert && keyToConvert[0].match(/[\\-]/g)) { // check if that part contains illegal characters
|
||||
if (keyToConvert && keyToConvert[0].match(slashDashSearch)) { // check if that part contains illegal characters
|
||||
return key.replace(keyToConvert[0], `['${keyToConvert[0]}']`); // surround key with '[' and ']'
|
||||
} else {
|
||||
return `.${key}`; // otherwise return as is with leading '.'
|
||||
@@ -38,3 +73,35 @@ function convertToIndexNotation(key: string, firstItem = false) {
|
||||
return `${prefix}${key}`;
|
||||
}
|
||||
}
|
||||
|
||||
function formatJSONValue(value: unknown) {
|
||||
if (typeof value === "object") {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
return String(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* This function is a safer version of `JSONPath.value(obj, path)` with untrusted jsonpath strings
|
||||
*
|
||||
* This function will also stringify the value retreived from the object
|
||||
*/
|
||||
export function safeJSONPathValue(obj: object, path: string): string {
|
||||
try {
|
||||
const parsedPath = JSONPath.parse(convertKubectlJsonPathToNodeJsonPath(path));
|
||||
const isSlice = parsedPath.some((exp: any) => exp.expression.type === "slice" || "wildcard");
|
||||
const value = JSONPath.query(obj, JSONPath.stringify(parsedPath), isSlice ? Infinity : 1);
|
||||
|
||||
if (isSlice) {
|
||||
return value.map(formatJSONValue).join(", ");
|
||||
}
|
||||
|
||||
return formatJSONValue(value[0]);
|
||||
} catch (error) {
|
||||
// something failed
|
||||
console.warn("[JSON-PATH]: failed to parse jsonpath", error);
|
||||
|
||||
return "<unknown>";
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user