@intentius/chant-lexicon-k8s 0.107.1 → 0.108.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/config-schema.d.ts +115 -1
- package/dist/config-schema.d.ts.map +1 -1
- package/dist/config.d.ts +58 -3
- package/dist/config.d.ts.map +1 -1
- package/dist/crd/loader.d.ts +4 -0
- package/dist/crd/loader.d.ts.map +1 -1
- package/dist/crd/parser.d.ts +5 -0
- package/dist/crd/parser.d.ts.map +1 -1
- package/dist/crd/project-codegen.d.ts +33 -0
- package/dist/crd/project-codegen.d.ts.map +1 -0
- package/dist/include/entity.d.ts +73 -0
- package/dist/include/entity.d.ts.map +1 -0
- package/dist/include/resolve.d.ts +29 -0
- package/dist/include/resolve.d.ts.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/integrity.json +3 -3
- package/dist/kustomize/rendered-entity.d.ts +15 -1
- package/dist/kustomize/rendered-entity.d.ts.map +1 -1
- package/dist/kustomize/root.d.ts +11 -2
- package/dist/kustomize/root.d.ts.map +1 -1
- package/dist/lint/post-synth/crd-schema-helpers.d.ts +5 -1
- package/dist/lint/post-synth/crd-schema-helpers.d.ts.map +1 -1
- package/dist/manifest.json +1 -1
- package/dist/patch/json-patch.d.ts +51 -0
- package/dist/patch/json-patch.d.ts.map +1 -0
- package/dist/patch/rendered-patch.d.ts +90 -0
- package/dist/patch/rendered-patch.d.ts.map +1 -0
- package/dist/plugin.d.ts.map +1 -1
- package/dist/project-kinds.d.ts +46 -0
- package/dist/project-kinds.d.ts.map +1 -0
- package/dist/rules/crd-schema-helpers.ts +10 -2
- package/dist/serializer.d.ts.map +1 -1
- package/package.json +3 -3
- package/src/config-augmentation.test.ts +28 -0
- package/src/config-schema.ts +47 -1
- package/src/config.ts +44 -3
- package/src/crd/loader.ts +1 -1
- package/src/crd/parser.ts +9 -5
- package/src/crd/project-codegen.test.ts +239 -0
- package/src/crd/project-codegen.ts +327 -0
- package/src/include/entity.ts +119 -0
- package/src/include/include.test.ts +345 -0
- package/src/include/resolve.ts +204 -0
- package/src/index.ts +23 -0
- package/src/kustomize/rendered-entity.ts +43 -1
- package/src/kustomize/root.test.ts +39 -0
- package/src/kustomize/root.ts +16 -30
- package/src/lint/post-synth/crd-schema-helpers.ts +10 -2
- package/src/patch/json-patch.test.ts +91 -0
- package/src/patch/json-patch.ts +189 -0
- package/src/patch/rendered-patch.test.ts +143 -0
- package/src/patch/rendered-patch.ts +180 -0
- package/src/plugin.ts +16 -2
- package/src/project-kinds.ts +75 -0
- package/src/serializer.ts +10 -0
- package/src/testdata/include/bundle.yaml +45 -0
|
@@ -157,6 +157,45 @@ describe("renderKustomizeRoots", () => {
|
|
|
157
157
|
).rejects.toThrow(/no kustomization file.*kustomization\.yaml/);
|
|
158
158
|
});
|
|
159
159
|
|
|
160
|
+
test("an entry with patches applies them to the rendered documents (#3566)", async () => {
|
|
161
|
+
const { entities } = await renderKustomizeRoots({
|
|
162
|
+
projectRoot: fixtureRoot,
|
|
163
|
+
roots: [
|
|
164
|
+
{
|
|
165
|
+
path: "overlays/prod",
|
|
166
|
+
patches: [
|
|
167
|
+
{ kind: "Deployment", name: "prod-web", merge: { spec: { replicas: 5 } } },
|
|
168
|
+
{
|
|
169
|
+
kind: "Service",
|
|
170
|
+
name: "prod-web",
|
|
171
|
+
jsonPatch: [{ op: "add", path: "/metadata/labels", value: { tier: "edge" } }],
|
|
172
|
+
},
|
|
173
|
+
],
|
|
174
|
+
},
|
|
175
|
+
],
|
|
176
|
+
run: cannedRunner([]),
|
|
177
|
+
});
|
|
178
|
+
const props = (key: string) => (entities.get(key) as unknown as { props: Record<string, unknown> }).props;
|
|
179
|
+
expect((props("overlays/prod/deploymentProdWeb").spec as { replicas: number }).replicas).toBe(5);
|
|
180
|
+
expect((props("overlays/prod/serviceProdWeb").metadata as { labels: unknown }).labels).toEqual({ tier: "edge" });
|
|
181
|
+
// The provenance annotation is stamped after patching, so it survives.
|
|
182
|
+
expect(
|
|
183
|
+
(props("overlays/prod/serviceProdWeb").metadata as { annotations: Record<string, string> }).annotations[
|
|
184
|
+
KUSTOMIZE_ROOT_ANNOTATION
|
|
185
|
+
],
|
|
186
|
+
).toBe("overlays/prod");
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
test("a patch that matches no rendered document fails, naming the root", async () => {
|
|
190
|
+
await expect(
|
|
191
|
+
renderKustomizeRoots({
|
|
192
|
+
projectRoot: fixtureRoot,
|
|
193
|
+
roots: [{ path: "overlays/prod", patches: [{ kind: "Deployment", name: "web", merge: {} }] }],
|
|
194
|
+
run: cannedRunner([]),
|
|
195
|
+
}),
|
|
196
|
+
).rejects.toThrow(/kustomize root "overlays\/prod": patch 0 \(kind Deployment, name web\) matched no document/);
|
|
197
|
+
});
|
|
198
|
+
|
|
160
199
|
test("a rendered document without apiVersion/kind is skipped with a warning", async () => {
|
|
161
200
|
const { entities, warnings } = await renderKustomizeRoots({
|
|
162
201
|
projectRoot: fixtureRoot,
|
package/src/kustomize/root.ts
CHANGED
|
@@ -29,7 +29,14 @@ import { existsSync } from "node:fs";
|
|
|
29
29
|
import { isAbsolute, join, relative, resolve } from "node:path";
|
|
30
30
|
import type { Declarable } from "@intentius/chant/declarable";
|
|
31
31
|
import { defaultKustomizeRunner, renderKustomizeDocuments, type KustomizeRunner } from "./render";
|
|
32
|
-
import { renderedManifestEntity } from "./rendered-entity";
|
|
32
|
+
import { addRenderedEntity, renderedManifestEntity } from "./rendered-entity";
|
|
33
|
+
import { applyRenderedPatches, type RenderedPatch } from "../patch/rendered-patch";
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* One `k8s.kustomize.roots` entry: a directory, or a directory plus patches
|
|
37
|
+
* applied to its rendered documents (#3566).
|
|
38
|
+
*/
|
|
39
|
+
export type KustomizeRootEntry = string | { path: string; patches?: RenderedPatch[] };
|
|
33
40
|
|
|
34
41
|
const KUSTOMIZATION_FILES = ["kustomization.yaml", "kustomization.yml", "Kustomization"];
|
|
35
42
|
|
|
@@ -38,18 +45,6 @@ export interface KustomizeRootsResult {
|
|
|
38
45
|
warnings: string[];
|
|
39
46
|
}
|
|
40
47
|
|
|
41
|
-
/** `Deployment` + `my-app` → `deploymentMyApp`, the import path's naming. */
|
|
42
|
-
function logicalId(kind: string, name: string | undefined): string {
|
|
43
|
-
const prefix = kind.charAt(0).toLowerCase() + kind.slice(1);
|
|
44
|
-
if (!name) return prefix;
|
|
45
|
-
const pascal = name
|
|
46
|
-
.split(/[^a-zA-Z0-9]+/)
|
|
47
|
-
.filter(Boolean)
|
|
48
|
-
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
|
|
49
|
-
.join("");
|
|
50
|
-
return `${prefix}${pascal}`;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
48
|
/**
|
|
54
49
|
* Render each configured kustomization root into entities, keyed
|
|
55
50
|
* `<root>/<kindName>` (namespace-qualified, then numbered, on collision).
|
|
@@ -57,8 +52,8 @@ function logicalId(kind: string, name: string | undefined): string {
|
|
|
57
52
|
export async function renderKustomizeRoots(opts: {
|
|
58
53
|
/** Directory the project config was loaded from; relative roots resolve against it. */
|
|
59
54
|
projectRoot: string;
|
|
60
|
-
/** `k8s.kustomize.roots` — kustomization dirs, usually relative. */
|
|
61
|
-
roots: readonly
|
|
55
|
+
/** `k8s.kustomize.roots` — kustomization dirs, usually relative, optionally with patches. */
|
|
56
|
+
roots: readonly KustomizeRootEntry[];
|
|
62
57
|
/** Injectable renderer (tests); defaults to the real subprocess runner. */
|
|
63
58
|
run?: KustomizeRunner;
|
|
64
59
|
}): Promise<KustomizeRootsResult> {
|
|
@@ -66,7 +61,9 @@ export async function renderKustomizeRoots(opts: {
|
|
|
66
61
|
const entities = new Map<string, Declarable>();
|
|
67
62
|
const warnings: string[] = [];
|
|
68
63
|
|
|
69
|
-
for (const
|
|
64
|
+
for (const entry of opts.roots) {
|
|
65
|
+
const root = typeof entry === "string" ? entry : entry.path;
|
|
66
|
+
const patches = typeof entry === "string" ? undefined : entry.patches;
|
|
70
67
|
const rootDir = isAbsolute(root) ? root : resolve(opts.projectRoot, root);
|
|
71
68
|
// The label rendered docs carry as provenance: the declared (relative)
|
|
72
69
|
// form when possible, so it names the overlay the way the config does.
|
|
@@ -82,26 +79,15 @@ export async function renderKustomizeRoots(opts: {
|
|
|
82
79
|
);
|
|
83
80
|
}
|
|
84
81
|
|
|
85
|
-
const
|
|
82
|
+
const rendered = await renderKustomizeDocuments(rootDir, run);
|
|
83
|
+
const documents = applyRenderedPatches(rendered, patches, `kustomize root "${rootLabel}"`);
|
|
86
84
|
for (const doc of documents) {
|
|
87
85
|
const entity = renderedManifestEntity(doc, rootLabel);
|
|
88
86
|
if (!entity) {
|
|
89
87
|
warnings.push(`kustomize root "${rootLabel}" rendered a document without apiVersion/kind — skipped`);
|
|
90
88
|
continue;
|
|
91
89
|
}
|
|
92
|
-
|
|
93
|
-
const kind = entity.props.kind as string;
|
|
94
|
-
const name = typeof metadata.name === "string" ? metadata.name : undefined;
|
|
95
|
-
const namespace = typeof metadata.namespace === "string" ? metadata.namespace : undefined;
|
|
96
|
-
|
|
97
|
-
// Deterministic, human-readable keys. Two documents can share
|
|
98
|
-
// kind+name (different namespaces, or different API groups with the
|
|
99
|
-
// same kind word) — qualify by namespace first, then number.
|
|
100
|
-
const base = `${rootLabel}/${logicalId(kind, name)}`;
|
|
101
|
-
let key = base;
|
|
102
|
-
if (entities.has(key) && namespace) key = `${base}.${namespace}`;
|
|
103
|
-
for (let n = 2; entities.has(key); n++) key = `${base}~${n}`;
|
|
104
|
-
entities.set(key, entity);
|
|
90
|
+
addRenderedEntity(entities, rootLabel, entity);
|
|
105
91
|
}
|
|
106
92
|
}
|
|
107
93
|
|
|
@@ -15,6 +15,7 @@ import { createRequire } from "module";
|
|
|
15
15
|
import type { PostSynthContext } from "@intentius/chant/lint/post-synth";
|
|
16
16
|
import type { CrdFieldSchema } from "../../spec/parse";
|
|
17
17
|
import { docsToManifests, type K8sManifest } from "./k8s-helpers";
|
|
18
|
+
import { projectSpecSchema } from "../../project-kinds";
|
|
18
19
|
|
|
19
20
|
export type { CrdFieldSchema };
|
|
20
21
|
|
|
@@ -61,10 +62,17 @@ export function setCrdSchemaRegistry(registry: Map<string, CrdFieldSchema> | nul
|
|
|
61
62
|
cachedRegistry = registry;
|
|
62
63
|
}
|
|
63
64
|
|
|
64
|
-
/**
|
|
65
|
+
/**
|
|
66
|
+
* The schema for a manifest's `apiVersion`/`kind`: one the project generated
|
|
67
|
+
* from its own CRDs (`chant generate`, ../../project-kinds.ts) first, then one
|
|
68
|
+
* the lexicon ships.
|
|
69
|
+
*/
|
|
65
70
|
export function specSchemaFor(manifest: K8sManifest): CrdFieldSchema | undefined {
|
|
66
71
|
if (typeof manifest.apiVersion !== "string" || typeof manifest.kind !== "string") return undefined;
|
|
67
|
-
return
|
|
72
|
+
return (
|
|
73
|
+
projectSpecSchema(manifest.apiVersion, manifest.kind) ??
|
|
74
|
+
getCrdSchemaRegistry().get(registryKey(manifest.apiVersion, manifest.kind))
|
|
75
|
+
);
|
|
68
76
|
}
|
|
69
77
|
|
|
70
78
|
/** Every manifest in the build that has a shipped spec schema, with that schema. */
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { describe, test, expect } from "vitest";
|
|
2
|
+
import { applyJsonPatch, applyMergePatch } from "./json-patch";
|
|
3
|
+
|
|
4
|
+
const doc = () => ({
|
|
5
|
+
metadata: { name: "web", labels: { app: "web" } },
|
|
6
|
+
spec: { replicas: 1, containers: [{ name: "a" }, { name: "b" }] },
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
describe("applyJsonPatch", () => {
|
|
10
|
+
test("add sets a member, inserts into an array, and appends with -", () => {
|
|
11
|
+
const out = applyJsonPatch(doc(), [
|
|
12
|
+
{ op: "add", path: "/metadata/labels/tier", value: "frontend" },
|
|
13
|
+
{ op: "add", path: "/spec/containers/1", value: { name: "mid" } },
|
|
14
|
+
{ op: "add", path: "/spec/containers/-", value: { name: "last" } },
|
|
15
|
+
]);
|
|
16
|
+
expect(out.metadata.labels).toEqual({ app: "web", tier: "frontend" });
|
|
17
|
+
expect(out.spec.containers.map((c) => c.name)).toEqual(["a", "mid", "b", "last"]);
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
test("replace changes an existing value and refuses a missing one", () => {
|
|
21
|
+
expect(applyJsonPatch(doc(), [{ op: "replace", path: "/spec/replicas", value: 3 }]).spec.replicas).toBe(3);
|
|
22
|
+
expect(() => applyJsonPatch(doc(), [{ op: "replace", path: "/spec/paused", value: true }])).toThrow(
|
|
23
|
+
/operation 0 \(replace\): path \/spec\/paused does not exist/,
|
|
24
|
+
);
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
test("remove deletes a member or an array element and refuses a missing path", () => {
|
|
28
|
+
const out = applyJsonPatch(doc(), [
|
|
29
|
+
{ op: "remove", path: "/metadata/labels/app" },
|
|
30
|
+
{ op: "remove", path: "/spec/containers/0" },
|
|
31
|
+
]);
|
|
32
|
+
expect(out.metadata.labels).toEqual({});
|
|
33
|
+
expect(out.spec.containers).toEqual([{ name: "b" }]);
|
|
34
|
+
expect(() => applyJsonPatch(doc(), [{ op: "remove", path: "/spec/containers/5" }])).toThrow(/out of bounds/);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
test("test passes on a deep-equal value and fails with both values in the message", () => {
|
|
38
|
+
expect(() =>
|
|
39
|
+
applyJsonPatch(doc(), [{ op: "test", path: "/spec/containers/0", value: { name: "a" } }]),
|
|
40
|
+
).not.toThrow();
|
|
41
|
+
expect(() => applyJsonPatch(doc(), [{ op: "test", path: "/spec/replicas", value: 2 }])).toThrow(
|
|
42
|
+
/test failed at \/spec\/replicas: expected 2, found 1/,
|
|
43
|
+
);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
test("move and copy", () => {
|
|
47
|
+
const out = applyJsonPatch(doc(), [
|
|
48
|
+
{ op: "copy", from: "/metadata/labels", path: "/spec/selector" },
|
|
49
|
+
{ op: "move", from: "/spec/replicas", path: "/spec/count" },
|
|
50
|
+
]);
|
|
51
|
+
expect(out).toMatchObject({ spec: { selector: { app: "web" }, count: 1 } });
|
|
52
|
+
expect((out.spec as Record<string, unknown>).replicas).toBeUndefined();
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
test("pointer escapes ~0 and ~1 address keys holding ~ and /", () => {
|
|
56
|
+
const out = applyJsonPatch({ metadata: { annotations: {} as Record<string, string> } }, [
|
|
57
|
+
{ op: "add", path: "/metadata/annotations/example.com~1a~0b", value: "x" },
|
|
58
|
+
]);
|
|
59
|
+
expect(out.metadata.annotations).toEqual({ "example.com/a~b": "x" });
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
test("never mutates its input, even when a later operation fails", () => {
|
|
63
|
+
const input = doc();
|
|
64
|
+
expect(() =>
|
|
65
|
+
applyJsonPatch(input, [
|
|
66
|
+
{ op: "replace", path: "/spec/replicas", value: 9 },
|
|
67
|
+
{ op: "test", path: "/spec/replicas", value: 1 },
|
|
68
|
+
]),
|
|
69
|
+
).toThrow(/operation 1 \(test\)/);
|
|
70
|
+
expect(input).toEqual(doc());
|
|
71
|
+
});
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
describe("applyMergePatch (RFC 7386)", () => {
|
|
75
|
+
test("merges objects, replaces arrays, deletes on null", () => {
|
|
76
|
+
const out = applyMergePatch(doc(), {
|
|
77
|
+
metadata: { labels: { app: null, tier: "frontend" } },
|
|
78
|
+
spec: { containers: [{ name: "only" }] },
|
|
79
|
+
});
|
|
80
|
+
expect(out.metadata.labels).toEqual({ tier: "frontend" });
|
|
81
|
+
expect(out.spec.containers).toEqual([{ name: "only" }]);
|
|
82
|
+
expect(out.spec.replicas).toBe(1);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
test("creates missing intermediate objects and leaves the input alone", () => {
|
|
86
|
+
const input = doc();
|
|
87
|
+
const out = applyMergePatch(input, { spec: { strategy: { type: "Recreate" } } });
|
|
88
|
+
expect(out).toMatchObject({ spec: { strategy: { type: "Recreate" } } });
|
|
89
|
+
expect(input).toEqual(doc());
|
|
90
|
+
});
|
|
91
|
+
});
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* RFC 6902 JSON Patch and RFC 7386 JSON Merge Patch, for rendered documents.
|
|
3
|
+
*
|
|
4
|
+
* Core carries an RFC 6902 applier for cfn-lint codegen
|
|
5
|
+
* (`packages/core/src/codegen/json-patch.ts`), but it skips `test`, `move`
|
|
6
|
+
* and `copy`, and it works on JSON strings. A patch on a rendered manifest
|
|
7
|
+
* needs `test` most of all: it is how an author pins the value a chart
|
|
8
|
+
* upgrade might change underneath them. So this module is a small, complete
|
|
9
|
+
* applier over plain objects, with no imports, usable from the build path and
|
|
10
|
+
* from the helm lexicon's `HelmRender`.
|
|
11
|
+
*
|
|
12
|
+
* Both appliers return a new document and never mutate their input.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/** One RFC 6902 operation. `path` and `from` are RFC 6901 JSON Pointers. */
|
|
16
|
+
export type JsonPatchOperation =
|
|
17
|
+
| { op: "add"; path: string; value: unknown }
|
|
18
|
+
| { op: "remove"; path: string }
|
|
19
|
+
| { op: "replace"; path: string; value: unknown }
|
|
20
|
+
| { op: "move"; from: string; path: string }
|
|
21
|
+
| { op: "copy"; from: string; path: string }
|
|
22
|
+
| { op: "test"; path: string; value: unknown };
|
|
23
|
+
|
|
24
|
+
type Container = Record<string, unknown> | unknown[];
|
|
25
|
+
|
|
26
|
+
function isObject(value: unknown): value is Record<string, unknown> {
|
|
27
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function clone<T>(value: T): T {
|
|
31
|
+
return value === undefined ? value : (JSON.parse(JSON.stringify(value)) as T);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** "" -> [], "/a/b~1c" -> ["a", "b/c"]. */
|
|
35
|
+
function parsePointer(pointer: string): string[] {
|
|
36
|
+
if (pointer === "") return [];
|
|
37
|
+
if (!pointer.startsWith("/")) throw new Error(`"${pointer}" is not a JSON Pointer (it must start with "/")`);
|
|
38
|
+
return pointer
|
|
39
|
+
.slice(1)
|
|
40
|
+
.split("/")
|
|
41
|
+
.map((t) => t.replace(/~1/g, "/").replace(/~0/g, "~"));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function arrayIndex(arr: unknown[], token: string, pointer: string, allowEnd: boolean): number {
|
|
45
|
+
if (!/^(0|[1-9][0-9]*)$/.test(token)) throw new Error(`"${token}" in ${pointer} is not an array index`);
|
|
46
|
+
const idx = Number(token);
|
|
47
|
+
const max = allowEnd ? arr.length : arr.length - 1;
|
|
48
|
+
if (idx > max) throw new Error(`index ${idx} in ${pointer} is out of bounds (array length ${arr.length})`);
|
|
49
|
+
return idx;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function get(root: unknown, pointer: string): unknown {
|
|
53
|
+
let current = root;
|
|
54
|
+
for (const token of parsePointer(pointer)) {
|
|
55
|
+
if (Array.isArray(current)) {
|
|
56
|
+
current = current[arrayIndex(current, token, pointer, false)];
|
|
57
|
+
} else if (isObject(current) && Object.prototype.hasOwnProperty.call(current, token)) {
|
|
58
|
+
current = current[token];
|
|
59
|
+
} else {
|
|
60
|
+
throw new Error(`path ${pointer} does not exist`);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return current;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** The container a pointer's last token addresses, and that token. */
|
|
67
|
+
function parentOf(root: unknown, pointer: string): { parent: Container; token: string } {
|
|
68
|
+
const tokens = parsePointer(pointer);
|
|
69
|
+
if (tokens.length === 0) throw new Error("the root cannot be addressed as a member");
|
|
70
|
+
const token = tokens.pop()!;
|
|
71
|
+
const parentPointer = tokens.length === 0 ? "" : "/" + tokens.map((t) => t.replace(/~/g, "~0").replace(/\//g, "~1")).join("/");
|
|
72
|
+
const parent = get(root, parentPointer);
|
|
73
|
+
if (!Array.isArray(parent) && !isObject(parent)) {
|
|
74
|
+
throw new Error(`path ${pointer} does not exist (its parent is not an object or array)`);
|
|
75
|
+
}
|
|
76
|
+
return { parent, token };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function add(root: unknown, pointer: string, value: unknown): unknown {
|
|
80
|
+
if (pointer === "") return value;
|
|
81
|
+
const { parent, token } = parentOf(root, pointer);
|
|
82
|
+
if (Array.isArray(parent)) {
|
|
83
|
+
if (token === "-") parent.push(value);
|
|
84
|
+
else parent.splice(arrayIndex(parent, token, pointer, true), 0, value);
|
|
85
|
+
} else {
|
|
86
|
+
parent[token] = value;
|
|
87
|
+
}
|
|
88
|
+
return root;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function remove(root: unknown, pointer: string): unknown {
|
|
92
|
+
if (pointer === "") throw new Error("the document root cannot be removed");
|
|
93
|
+
const { parent, token } = parentOf(root, pointer);
|
|
94
|
+
if (Array.isArray(parent)) {
|
|
95
|
+
parent.splice(arrayIndex(parent, token, pointer, false), 1);
|
|
96
|
+
} else {
|
|
97
|
+
if (!Object.prototype.hasOwnProperty.call(parent, token)) throw new Error(`path ${pointer} does not exist`);
|
|
98
|
+
delete parent[token];
|
|
99
|
+
}
|
|
100
|
+
return root;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function replace(root: unknown, pointer: string, value: unknown): unknown {
|
|
104
|
+
if (pointer === "") return value;
|
|
105
|
+
get(root, pointer); // must exist
|
|
106
|
+
const { parent, token } = parentOf(root, pointer);
|
|
107
|
+
if (Array.isArray(parent)) parent[arrayIndex(parent, token, pointer, false)] = value;
|
|
108
|
+
else parent[token] = value;
|
|
109
|
+
return root;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function deepEqual(a: unknown, b: unknown): boolean {
|
|
113
|
+
if (a === b) return true;
|
|
114
|
+
if (Array.isArray(a) && Array.isArray(b)) {
|
|
115
|
+
return a.length === b.length && a.every((v, i) => deepEqual(v, b[i]));
|
|
116
|
+
}
|
|
117
|
+
if (isObject(a) && isObject(b)) {
|
|
118
|
+
const ka = Object.keys(a);
|
|
119
|
+
const kb = Object.keys(b);
|
|
120
|
+
return ka.length === kb.length && ka.every((k) => Object.prototype.hasOwnProperty.call(b, k) && deepEqual(a[k], b[k]));
|
|
121
|
+
}
|
|
122
|
+
return false;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Apply an RFC 6902 patch. Operations apply in order; the first one that
|
|
127
|
+
* fails (a missing path, a failed `test`) throws with its index, and the
|
|
128
|
+
* input is left untouched.
|
|
129
|
+
*/
|
|
130
|
+
export function applyJsonPatch<T>(doc: T, operations: readonly JsonPatchOperation[]): T {
|
|
131
|
+
let root: unknown = clone(doc);
|
|
132
|
+
operations.forEach((operation, i) => {
|
|
133
|
+
try {
|
|
134
|
+
switch (operation.op) {
|
|
135
|
+
case "add":
|
|
136
|
+
root = add(root, operation.path, clone(operation.value));
|
|
137
|
+
break;
|
|
138
|
+
case "remove":
|
|
139
|
+
root = remove(root, operation.path);
|
|
140
|
+
break;
|
|
141
|
+
case "replace":
|
|
142
|
+
root = replace(root, operation.path, clone(operation.value));
|
|
143
|
+
break;
|
|
144
|
+
case "move": {
|
|
145
|
+
if (operation.path.startsWith(operation.from + "/")) {
|
|
146
|
+
throw new Error(`cannot move ${operation.from} into its own child ${operation.path}`);
|
|
147
|
+
}
|
|
148
|
+
const value = get(root, operation.from);
|
|
149
|
+
root = remove(root, operation.from);
|
|
150
|
+
root = add(root, operation.path, value);
|
|
151
|
+
break;
|
|
152
|
+
}
|
|
153
|
+
case "copy":
|
|
154
|
+
root = add(root, operation.path, clone(get(root, operation.from)));
|
|
155
|
+
break;
|
|
156
|
+
case "test": {
|
|
157
|
+
const actual = get(root, operation.path);
|
|
158
|
+
if (!deepEqual(actual, operation.value)) {
|
|
159
|
+
throw new Error(
|
|
160
|
+
`test failed at ${operation.path}: expected ${JSON.stringify(operation.value)}, found ${JSON.stringify(actual)}`,
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
break;
|
|
164
|
+
}
|
|
165
|
+
default:
|
|
166
|
+
throw new Error(`unknown op "${(operation as { op: unknown }).op}"`);
|
|
167
|
+
}
|
|
168
|
+
} catch (err) {
|
|
169
|
+
throw new Error(`operation ${i} (${operation.op}): ${err instanceof Error ? err.message : String(err)}`);
|
|
170
|
+
}
|
|
171
|
+
});
|
|
172
|
+
return root as T;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Apply an RFC 7386 merge patch: objects merge key by key, a `null` value
|
|
177
|
+
* deletes the key, and anything else (arrays included) replaces the target
|
|
178
|
+
* whole.
|
|
179
|
+
*/
|
|
180
|
+
export function applyMergePatch<T>(doc: T, patch: unknown): T {
|
|
181
|
+
if (!isObject(patch)) return clone(patch) as T;
|
|
182
|
+
const target: Record<string, unknown> = isObject(doc) ? clone(doc) : {};
|
|
183
|
+
for (const [key, value] of Object.entries(patch)) {
|
|
184
|
+
if (value === undefined) continue;
|
|
185
|
+
if (value === null) delete target[key];
|
|
186
|
+
else target[key] = applyMergePatch(target[key], value);
|
|
187
|
+
}
|
|
188
|
+
return target as T;
|
|
189
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { describe, test, expect, expectTypeOf } from "vitest";
|
|
2
|
+
import { applyRenderedPatches, renderedPatch, type MergePatchOf, type KindProps, type RenderedPatch } from "./rendered-patch";
|
|
3
|
+
|
|
4
|
+
const docs = (): Array<Record<string, unknown>> => [
|
|
5
|
+
{ apiVersion: "v1", kind: "ConfigMap", metadata: { name: "cfg", namespace: "a" }, data: { level: "info" } },
|
|
6
|
+
{ apiVersion: "v1", kind: "ConfigMap", metadata: { name: "cfg", namespace: "b" }, data: { level: "info" } },
|
|
7
|
+
{ apiVersion: "apps/v1", kind: "Deployment", metadata: { name: "web", namespace: "a" }, spec: { replicas: 1 } },
|
|
8
|
+
];
|
|
9
|
+
|
|
10
|
+
describe("applyRenderedPatches", () => {
|
|
11
|
+
test("no patches returns the documents unchanged", () => {
|
|
12
|
+
expect(applyRenderedPatches(docs(), undefined, "src")).toEqual(docs());
|
|
13
|
+
expect(applyRenderedPatches(docs(), [], "src")).toEqual(docs());
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
test("a namespaced selector patches only that document", () => {
|
|
17
|
+
const out = applyRenderedPatches(
|
|
18
|
+
docs(),
|
|
19
|
+
[{ kind: "ConfigMap", name: "cfg", namespace: "b", merge: { data: { level: "debug" } } }],
|
|
20
|
+
"src",
|
|
21
|
+
);
|
|
22
|
+
expect(out.map((d) => (d.data as { level?: string } | undefined)?.level)).toEqual(["info", "debug", undefined]);
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
test("without a namespace, every document of that kind and name matches", () => {
|
|
26
|
+
const out = applyRenderedPatches(
|
|
27
|
+
docs(),
|
|
28
|
+
[{ kind: "ConfigMap", name: "cfg", jsonPatch: [{ op: "replace", path: "/data/level", value: "warn" }] }],
|
|
29
|
+
"src",
|
|
30
|
+
);
|
|
31
|
+
expect(out.slice(0, 2).map((d) => (d.data as { level: string }).level)).toEqual(["warn", "warn"]);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
test("patches apply in order, each seeing the last one's result", () => {
|
|
35
|
+
const out = applyRenderedPatches(
|
|
36
|
+
docs(),
|
|
37
|
+
[
|
|
38
|
+
{ kind: "Deployment", name: "web", merge: { spec: { replicas: 3 } } },
|
|
39
|
+
{ kind: "Deployment", name: "web", jsonPatch: [{ op: "test", path: "/spec/replicas", value: 3 }] },
|
|
40
|
+
],
|
|
41
|
+
"src",
|
|
42
|
+
);
|
|
43
|
+
expect((out[2].spec as { replicas: number }).replicas).toBe(3);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
test("a selector matching nothing is an error naming the source and the documents of that kind", () => {
|
|
47
|
+
expect(() =>
|
|
48
|
+
applyRenderedPatches(docs(), [{ kind: "Deployment", name: "api", merge: { spec: { replicas: 2 } } }], 'HelmRender "x"'),
|
|
49
|
+
).toThrow(/HelmRender "x": patch 0 \(kind Deployment, name api\) matched no document\. Deployment documents present: a\/web\./);
|
|
50
|
+
expect(() =>
|
|
51
|
+
applyRenderedPatches(docs(), [{ kind: "Service", name: "web", merge: {} }], "src"),
|
|
52
|
+
).toThrow(/There are no Service documents/);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
test("apiVersion narrows the selector", () => {
|
|
56
|
+
expect(() =>
|
|
57
|
+
applyRenderedPatches(docs(), [{ kind: "Deployment", name: "web", apiVersion: "apps/v1beta1", merge: {} }], "src"),
|
|
58
|
+
).toThrow(/matched no document/);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
test("a failed operation names the source and the patch", () => {
|
|
62
|
+
expect(() =>
|
|
63
|
+
applyRenderedPatches(
|
|
64
|
+
docs(),
|
|
65
|
+
[{ kind: "Deployment", name: "web", jsonPatch: [{ op: "test", path: "/spec/replicas", value: 2 }] }],
|
|
66
|
+
"file.yaml",
|
|
67
|
+
),
|
|
68
|
+
).toThrow(/file\.yaml: patch 0 \(kind Deployment, name web\): operation 0 \(test\): test failed/);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
test("both or neither of jsonPatch and merge is refused", () => {
|
|
72
|
+
const both = { kind: "Deployment", name: "web", jsonPatch: [], merge: {} } as unknown as RenderedPatch;
|
|
73
|
+
const neither = { kind: "Deployment", name: "web" } as unknown as RenderedPatch;
|
|
74
|
+
expect(() => applyRenderedPatches(docs(), [both], "src")).toThrow(/exactly one of jsonPatch and merge/);
|
|
75
|
+
expect(() => applyRenderedPatches(docs(), [neither], "src")).toThrow(/exactly one of jsonPatch and merge/);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
test("a patch that removes kind is refused", () => {
|
|
79
|
+
expect(() =>
|
|
80
|
+
applyRenderedPatches(docs(), [{ kind: "Deployment", name: "web", jsonPatch: [{ op: "remove", path: "/kind" }] }], "src"),
|
|
81
|
+
).toThrow(/left a document without a string apiVersion and kind/);
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
test("renderedPatch infers the kind and returns the patch unchanged", () => {
|
|
85
|
+
const patch = renderedPatch({ kind: "Deployment", name: "web", merge: { spec: { replicas: 5 } } });
|
|
86
|
+
expect(patch).toEqual({ kind: "Deployment", name: "web", merge: { spec: { replicas: 5 } } });
|
|
87
|
+
const out = applyRenderedPatches(docs(), [patch], "src");
|
|
88
|
+
expect((out[2].spec as { replicas: number }).replicas).toBe(5);
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
test("the input documents are not mutated", () => {
|
|
92
|
+
const input = docs();
|
|
93
|
+
applyRenderedPatches(input, [{ kind: "Deployment", name: "web", merge: { spec: { replicas: 9 } } }], "src");
|
|
94
|
+
expect(input).toEqual(docs());
|
|
95
|
+
});
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
describe("renderedPatch types merge against the generated props", () => {
|
|
99
|
+
test("a well-typed Deployment merge compiles, with null deleting a field", () => {
|
|
100
|
+
const patch = renderedPatch({
|
|
101
|
+
kind: "Deployment",
|
|
102
|
+
name: "web",
|
|
103
|
+
merge: { spec: { replicas: 3, paused: null, template: { spec: { enableServiceLinks: false } } } },
|
|
104
|
+
});
|
|
105
|
+
expect(patch.kind).toBe("Deployment");
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
test("wrong-typed or unknown fields are rejected by the compiler", () => {
|
|
109
|
+
renderedPatch({
|
|
110
|
+
kind: "Deployment",
|
|
111
|
+
name: "web",
|
|
112
|
+
// @ts-expect-error replicas is a number
|
|
113
|
+
merge: { spec: { replicas: "three" } },
|
|
114
|
+
});
|
|
115
|
+
renderedPatch({
|
|
116
|
+
kind: "Deployment",
|
|
117
|
+
name: "web",
|
|
118
|
+
// @ts-expect-error not a Deployment field
|
|
119
|
+
merge: { spek: { replicas: 3 } },
|
|
120
|
+
});
|
|
121
|
+
renderedPatch({
|
|
122
|
+
kind: "Deployment",
|
|
123
|
+
name: "web",
|
|
124
|
+
merge: {
|
|
125
|
+
spec: {
|
|
126
|
+
template: {
|
|
127
|
+
spec: {
|
|
128
|
+
// @ts-expect-error a container in a replacing array must be complete and well-typed
|
|
129
|
+
containers: [{ name: "c", livenessProbe: { grpc: { port: "x" } } }],
|
|
130
|
+
},
|
|
131
|
+
},
|
|
132
|
+
},
|
|
133
|
+
},
|
|
134
|
+
});
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
test("a kind with no generated class takes an open record", () => {
|
|
138
|
+
renderedPatch({ kind: "SomeVendorThing", name: "x", merge: { anything: { goes: 1 } } });
|
|
139
|
+
expectTypeOf<KindProps<"SomeVendorThing">>().toEqualTypeOf<Record<string, unknown>>();
|
|
140
|
+
expectTypeOf<{ spec: { replicas: number } }>().toMatchTypeOf<MergePatchOf<KindProps<"Deployment">>>();
|
|
141
|
+
expectTypeOf<{ spec: { replicas: string } }>().not.toMatchTypeOf<MergePatchOf<KindProps<"Deployment">>>();
|
|
142
|
+
});
|
|
143
|
+
});
|