Upgrade js-yaml to 4.X (#3623)

This commit is contained in:
Sebastian Malton authored and GitHub committed 2021-10-18 10:03:10 -04:00
1 parent fcb3010033
commit 5998b4ca84
17 files changed
+90 -57

No files matched your search

+1 -1
View File
@@ -426,7 +426,7 @@ describe("pre 2.6.0 config with a cluster that has arrays in auth config", () =>
it("replaces array format access token and expiry into string", async () => {
const file = ClusterStore.getInstance().clustersList[0].kubeConfigPath;
const config = fs.readFileSync(file, "utf8");
const kc = yaml.safeLoad(config);
const kc = yaml.load(config) as Record<string, any>;
expect(kc.users[0].user["auth-provider"].config["access-token"]).toBe("should be string");
expect(kc.users[0].user["auth-provider"].config["expiry"]).toBe("should be string");
@@ -19,7 +19,7 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import jsYaml from "js-yaml";
import yaml from "js-yaml";
import { autoBind, formatDuration } from "../../utils";
import capitalize from "lodash/capitalize";
import { apiBase } from "../index";
@@ -113,21 +113,31 @@ export async function getRelease(name: string, namespace: string): Promise<IRele
}
export async function createRelease(payload: IReleaseCreatePayload): Promise<IReleaseUpdateDetails> {
const { repo, ...data } = payload;
const { repo, chart: rawChart, values: rawValues, ...data } = payload;
const chart = `${repo}/${rawChart}`;
const values = yaml.load(rawValues);
data.chart = `${repo}/${data.chart}`;
data.values = jsYaml.safeLoad(data.values);
return apiBase.post(endpoint(), { data });
return apiBase.post(endpoint(), {
data: {
chart,
values,
...data,
}
});
}
export async function updateRelease(name: string, namespace: string, payload: IReleaseUpdatePayload): Promise<IReleaseUpdateDetails> {
const { repo, ...data } = payload;
const { repo, chart: rawChart, values: rawValues, ...data } = payload;
const chart = `${repo}/${rawChart}`;
const values = yaml.load(rawValues);
data.chart = `${repo}/${data.chart}`;
data.values = jsYaml.safeLoad(data.values);
return apiBase.put(endpoint({ name, namespace }), { data });
return apiBase.put(endpoint({ name, namespace }), {
data: {
chart,
values,
...data,
}
});
}
export async function deleteRelease(name: string, namespace: string): Promise<JsonApiData> {
@@ -19,7 +19,7 @@
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import jsYaml from "js-yaml";
import yaml from "js-yaml";
import type { KubeJsonApiData } from "../kube-json-api";
import { apiBase } from "../index";
import type { Patch } from "rfc6902";
@@ -30,7 +30,13 @@ export const annotations = [
export async function update(resource: object | string): Promise<KubeJsonApiData> {
if (typeof resource === "string") {
resource = jsYaml.safeLoad(resource);
const parsed = yaml.load(resource);
if (typeof parsed !== "object") {
throw new Error("Cannot update resource to string or number");
}
resource = parsed;
}
return apiBase.post<KubeJsonApiData>("/stack", { data: resource });
+2 -2
View File
@@ -133,7 +133,7 @@ export class ResourceStack {
if (!resourceData.trim()) continue;
const resourceArray = yaml.safeLoadAll(resourceData.toString());
const resourceArray = yaml.loadAll(resourceData.toString());
resourceArray.forEach((resource) => {
if (resource?.metadata) {
@@ -143,7 +143,7 @@ export class ResourceStack {
resource.metadata.labels["app.kubernetes.io/created-by"] = "resource-stack";
}
resources.push(yaml.safeDump(resource));
resources.push(yaml.dump(resource));
});
}
+2 -2
View File
@@ -111,7 +111,7 @@ interface OptionsResult {
}
function loadToOptions(rawYaml: string): OptionsResult {
const parsed = yaml.safeLoad(rawYaml);
const parsed = yaml.load(rawYaml);
const { error } = kubeConfigSchema.validate(parsed, {
abortEarly: false,
allowUnknown: true,
@@ -248,7 +248,7 @@ export function dumpConfigYaml(kubeConfig: Partial<KubeConfig>): string {
logger.debug("Dumping KubeConfig:", config);
// skipInvalid: true makes dump ignore undefined values
return yaml.safeDump(config, { skipInvalid: true });
return yaml.dump(config, { skipInvalid: true });
}
/**
+11 -2
View File
@@ -29,6 +29,11 @@ import { helmCli } from "./helm-cli";
import type { RepoHelmChartList } from "../../common/k8s-api/endpoints/helm-charts.api";
import { sortCharts } from "../../common/utils";
export interface HelmCacheFile {
apiVersion: string;
entries: RepoHelmChartList;
}
export class HelmChartManager {
static #cache = new Map<string, Buffer>();
@@ -82,7 +87,11 @@ export class HelmChartManager {
protected async cachedYaml(): Promise<RepoHelmChartList> {
if (!HelmChartManager.#cache.has(this.repo.name)) {
const cacheFile = await fs.promises.readFile(this.repo.cacheFilePath, "utf-8");
const { entries } = yaml.safeLoad(cacheFile) as { entries: RepoHelmChartList };
const data = yaml.load(cacheFile) as string | number | HelmCacheFile;
if (typeof data !== "object" || !data) {
return {};
}
/**
* Do some initial preprocessing on the data, so as to avoid needing to do it later
@@ -92,7 +101,7 @@ export class HelmChartManager {
*/
const normalized = Object.fromEntries(
Object.entries(entries)
Object.entries(data.entries)
.map(([name, charts]) => [
name,
sortCharts(
+2 -2
View File
@@ -53,7 +53,7 @@ export async function installChart(chart: string, values: any, name: string | un
const helm = await helmCli.binaryPath();
const fileName = tempy.file({ name: "values.yaml" });
await fse.writeFile(fileName, yaml.safeDump(values));
await fse.writeFile(fileName, yaml.dump(values));
try {
let generateName = "";
@@ -83,7 +83,7 @@ export async function upgradeRelease(name: string, chart: string, values: any, n
const helm = await helmCli.binaryPath();
const fileName = tempy.file({ name: "values.yaml" });
await fse.writeFile(fileName, yaml.safeDump(values));
await fse.writeFile(fileName, yaml.dump(values));
try {
const proxyKubeconfig = await cluster.getProxyKubeconfigPath();
+16 -6
View File
@@ -101,18 +101,28 @@ export class HelmRepoManager extends Singleton {
return repos.find(repo => repo.name === name);
}
private async readConfig(): Promise<HelmRepoConfig> {
try {
const rawConfig = await readFile(this.helmEnv.HELM_REPOSITORY_CONFIG, "utf8");
const parsedConfig = yaml.load(rawConfig);
if (typeof parsedConfig === "object" && parsedConfig) {
return parsedConfig as HelmRepoConfig;
}
} catch { }
return {
repositories: []
};
}
public async repositories(): Promise<HelmRepo[]> {
try {
if (!this.initialized) {
await this.init();
}
const repoConfigFile = this.helmEnv.HELM_REPOSITORY_CONFIG;
const { repositories }: HelmRepoConfig = await readFile(repoConfigFile, "utf8")
.then((yamlContent: string) => yaml.safeLoad(yamlContent))
.catch(() => ({
repositories: []
}));
const { repositories } = await this.readConfig();
if (!repositories.length) {
await HelmRepoManager.addRepo({ name: "bitnami", url: "https://charts.bitnami.com/bitnami" });
+1 -1
View File
@@ -78,7 +78,7 @@ export class ResourceApplier {
resource = this.sanitizeObject(resource);
appEventBus.emit({ name: "resource", action: "apply" });
return this.kubectlApply(yaml.safeDump(resource));
return this.kubectlApply(yaml.dump(resource));
}
protected async kubectlApply(content: string): Promise<string> {
+7 -3
View File
@@ -32,9 +32,13 @@ export default {
const cluster = value[1];
if (!cluster.kubeConfig) continue;
const kubeConfig = yaml.safeLoad(cluster.kubeConfig);
const config = yaml.load(cluster.kubeConfig);
if (!kubeConfig.hasOwnProperty("users")) continue;
if (!config || typeof config !== "object" || !config.hasOwnProperty("users")) {
continue;
}
const kubeConfig = config as Record<string, any>;
const userObj = kubeConfig.users[0];
if (userObj) {
@@ -56,7 +60,7 @@ export default {
name: userObj.name,
user
}];
cluster.kubeConfig = yaml.safeDump(kubeConfig);
cluster.kubeConfig = yaml.dump(kubeConfig);
store.set(clusterKey, cluster);
}
}
@@ -21,7 +21,7 @@
import "./pod-details-affinities.scss";
import React from "react";
import jsYaml from "js-yaml";
import yaml from "js-yaml";
import { DrawerParamToggler, DrawerItem } from "../drawer";
import type { Pod, Deployment, DaemonSet, StatefulSet, ReplicaSet, Job } from "../../../common/k8s-api/endpoints";
import MonacoEditor from "react-monaco-editor";
@@ -50,7 +50,7 @@ export class PodDetailsAffinities extends React.Component<Props> {
className={cssNames("MonacoEditor")}
theme={ThemeStore.getInstance().activeTheme.monacoTheme}
language="yaml"
value={jsYaml.dump(affinities)}
value={yaml.dump(affinities)}
/>
</div>
</DrawerParamToggler>
@@ -25,7 +25,7 @@ import React from "react";
import path from "path";
import fs from "fs-extra";
import {Select, GroupSelectOption, SelectOption} from "../select";
import jsYaml from "js-yaml";
import yaml from "js-yaml";
import { observable, makeObservable } from "mobx";
import { observer } from "mobx-react";
import { cssNames } from "../../utils";
@@ -101,15 +101,14 @@ export class CreateResource extends React.Component<Props> {
return null;
}
// skip empty documents if "---" pasted at the beginning or end
const resources = jsYaml.safeLoadAll(this.data).filter(Boolean);
// skip empty documents
const resources = yaml.loadAll(this.data).filter(Boolean);
const createdResources: string[] = [];
if (resources.length === 0) {
return void logger.info("Nothing to create");
}
const createdResources: string[] = [];
for (const result of await Promise.allSettled(resources.map(resourceApplierApi.update))) {
if (result.status === "fulfilled") {
createdResources.push(result.value.metadata.name);
@@ -72,13 +72,13 @@ export class EditResource extends React.Component<Props> {
return draft;
}
return yaml.safeDump(this.resource.toPlainObject()); // dump resource first time
return yaml.dump(this.resource.toPlainObject()); // dump resource first time
}
@action
saveDraft(draft: string | object) {
if (typeof draft === "object") {
draft = draft ? yaml.safeDump(draft) : undefined;
draft = draft ? yaml.dump(draft) : undefined;
}
editResourceStore.setData(this.tabId, {
@@ -99,8 +99,8 @@ export class EditResource extends React.Component<Props> {
}
const store = editResourceStore.getStore(this.tabId);
const currentVersion = yaml.safeLoad(this.draft);
const firstVersion = yaml.safeLoad(editResourceStore.getData(this.tabId).firstDraft ?? this.draft);
const currentVersion = yaml.load(this.draft);
const firstVersion = yaml.load(editResourceStore.getData(this.tabId).firstDraft ?? this.draft);
const patches = createPatch(firstVersion, currentVersion);
const updatedResource = await store.patch(this.resource, patches);
@@ -21,7 +21,7 @@
import MonacoEditor, {monaco} from "react-monaco-editor";
import React from "react";
import jsYaml from "js-yaml";
import yaml from "js-yaml";
import { observable, makeObservable } from "mobx";
import { disposeOnUnmount, observer } from "mobx-react";
import { dockStore, TabId } from "./dock.store";
@@ -63,14 +63,14 @@ export class EditorPanel extends React.Component<Props> {
editorDidMount = (editor: monaco.editor.IStandaloneCodeEditor) => {
this.editor = editor;
const model = monacoModelsManager.getModel(this.props.tabId);
model.setValue(this.props.value ?? "");
this.editor.setModel(model);
};
validate(value: string) {
try {
jsYaml.safeLoadAll(value);
yaml.loadAll(value);
this.yamlError = "";
} catch (err) {
this.yamlError = err.toString();
@@ -24,7 +24,7 @@ import "./kubeconfig-dialog.scss";
import React from "react";
import { observable, makeObservable } from "mobx";
import { observer } from "mobx-react";
import jsYaml from "js-yaml";
import yaml from "js-yaml";
import type { ServiceAccount } from "../../../common/k8s-api/endpoints";
import { copyToClipboard, cssNames, saveFileDialog } from "../../utils";
import { Button } from "../button";
@@ -88,7 +88,7 @@ export class KubeConfigDialog extends React.Component<Props> {
this.close();
});
this.config = config ? jsYaml.dump(config) : "";
this.config = config ? yaml.dump(config) : "";
}
copyToClipboard = () => {