Skip to content

Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.

feat(infra): a kustomize patch OVERRIDEs the objects it changes

Martin Vogel947d3a17040e
diff --git a/README.md b/README.md
index e2bf25918..93022fcf8 100644
--- a/README.md
+++ b/README.md
@@ -255,6 +255,7 @@ The install script placed beside the binary is **reported, not deleted** — uni
- `DEPLOYS` — what puts manifests, kustomizations or charts on a cluster, to what it puts there: a Flux Kustomization or Argo Application to the kustomizations / manifests / chart of its path, a Flux HelmRelease to its chart (`spec.chart` or `chartRef` → OCIRepository), a shell command or Make recipe (`kubectl apply -f/-k`, `kustomize build | kubectl apply`, `helm install/upgrade/template`), a Go installer loading a chart with the Helm SDK, a Terraform `helm_release`. A chart outside the repository is a shared external `Chart`; the edge says `via` (`flux`, `argo`, `helmrelease`, `kubectl`, `kustomize`, `helm`, `helm-sdk`, `terraform`, ...)
- `DEPENDS_ON` — a Helm chart to the charts it declares (the local chart for a resolvable `file://` repository, otherwise an external `Chart`; the edge keeps `repository`), and a `go.mod` / `requirements.txt` file to an external `Package`; a Dockerfile to the `Image`s it builds on (`via: from`, `copy-from`); an `Image` to the Dockerfile it is built from (`via: build`; `tool`: `skaffold`, `compose`, `docker-build` for `docker` / `podman` / `nerdctl` / `buildah` build commands in scripts, Make and CI); a compose service to the services its `depends_on` / `links` name
- `CONFIGURES` — code reading an environment variable to the shared `EnvVar` of that name (`strategy: env_access`); a Kubernetes container, compose service or Dockerfile (`ENV` of the image) setting one to that container's own `EnvVar` (`strategy: env_set`, with `source`: `value`, `configMapKeyRef`, `secretKeyRef`, `fieldRef`, ..., `compose`, `dockerfile` — values are never stored); and that container's `EnvVar` to the code reading the name inside the files its image is built from (`strategy: env_read`, with `dockerfile`) — the image's files are the sources its Dockerfile's `COPY` / `ADD` put into it, less the context's `.dockerignore`
+- `OVERRIDE` with `via: patch` — a Kustomize patch to each object of its kustomization's build it changes (child → base): a patch file's documents to the object of the same kind and name; an inline patch (from the kustomization) or a JSON6902 operation file to what its `target` selects (group, version, kind, name, namespace); a component's in the build of each kustomization including it. The edge keeps `kustomization`, `patch` and `line`; a patch file is an `IMPORTS` (`local_name: patches`) of its kustomization, never a member of the build
- `EMITS`, `LISTENS_ON` (channels)
- `DATA_FLOWS` with arg-to-param mapping + field access chains
- `SIMILAR_TO` (MinHash + LSH near-clone detection, Jaccard scored)
@@ -263,7 +264,7 @@ The install script placed beside the binary is **reported, not deleted** — uni
### Indexing pipeline
- **158 vendored tree-sitter grammars** compiled into the binary
- **Generic package / module resolution** — bare specifiers like `@myorg/pkg`, `github.com/foo/bar`, `use my_crate::foo` resolved via manifest scanning (`package.json`, `go.mod`, `Cargo.toml`, `pyproject.toml`, `composer.json`, `pubspec.yaml`, `pom.xml`, `build.gradle`, `mix.exs`, `*.gemspec`)
-- **Infrastructure-as-code indexing** — Dockerfiles (`Dockerfile.*`, `*.Dockerfile`, `Containerfile`: bases, what the container runs, `ENV`), container images (`Image`: the normalised repository, tag and digest on the edges; a repository built from several Dockerfiles, one per component tag, gets an `Image` per component), docker compose services (`Resource`), Kubernetes manifests (`Resource`), Kustomize overlays (`IMPORTS` to their entries), Helm charts (`Chart`, `DEPENDS_ON`), Terraform / OpenTofu (`.tf`, `.tofu`, `.tfvars`) as graph nodes. A Service walks to the code it runs: Service → workload → `Image` → Dockerfile → `main`
+- **Infrastructure-as-code indexing** — Dockerfiles (`Dockerfile.*`, `*.Dockerfile`, `Containerfile`: bases, what the container runs, `ENV`), container images (`Image`: the normalised repository, tag and digest on the edges; a repository built from several Dockerfiles, one per component tag, gets an `Image` per component), docker compose services (`Resource`), Kubernetes manifests (`Resource`, with `group`, `version`, `kind`, `namespace`), Kustomize overlays (`IMPORTS` to their entries and patch files, `OVERRIDE` from their patches), Helm charts (`Chart`, `DEPENDS_ON`), Terraform / OpenTofu (`.tf`, `.tofu`, `.tfvars`) as graph nodes. A Service walks to the code it runs: Service → workload → `Image` → Dockerfile → `main`
- **[Hybrid LSP semantic type resolution](#hybrid-lsp)** for Python, TypeScript / JavaScript / JSX / TSX, PHP, C#, Go, C, C++, Java, Kotlin, Rust, and Perl — a lightweight C implementation of language type-resolution algorithms, structurally inspired by and compatible with major language servers including tsserver / typescript-go, pyright, gopls, Roslyn, Eclipse JDT, and rust-analyzer (parameter binding, return-type inference, generic substitution, JSX component dispatch, JSDoc inference for plain JS files, namespace + trait + late-static-binding resolution for PHP, file-scoped namespaces + records + LINQ method syntax for C#, class-hierarchy + overload + lambda resolution for Java, extension-function + scope-function resolution for Kotlin, trait-method + UFCS resolution for Rust)
- **RAM-first pipeline**: LZ4 compression, in-memory SQLite, single dump at end. Memory released after.
diff --git a/internal/cbm/cbm.h b/internal/cbm/cbm.h
index 8bb004037..cf3343865 100644
--- a/internal/cbm/cbm.h
+++ b/internal/cbm/cbm.h
@@ -719,7 +719,14 @@ typedef struct {
* (NULL: unnamed) from image `name` (a literal reference); via "container".
* CBM_K8S_FACT_ENV: object def_index sets environment variable `name` in
* its container `container` (NULL: unnamed) at `line`; via = where the
- * value comes from ("value", or the valueFrom kind) -- never the value. */
+ * value comes from ("value", or the valueFrom kind) -- never the value.
+ * CBM_K8S_FACT_PATCH: a kustomization's `patches` entry at `line` patches
+ * the objects of its build named by kind / group / version / name / ns
+ * (any NULL: any) -- its `target`, else an inline patch document's own
+ * kind / group / name / ns; `path` is
+ * the patch file (as written, relative to the kustomization), NULL for an
+ * inline patch. kind and name both NULL: the patch file's documents name
+ * them. def_index -1: the kustomization itself is the source. */
typedef enum {
CBM_K8S_FACT_REF = 0,
CBM_K8S_FACT_CRD,
@@ -727,7 +734,8 @@ typedef enum {
CBM_K8S_FACT_ROUTE,
CBM_K8S_FACT_SOURCE,
CBM_K8S_FACT_IMAGE,
- CBM_K8S_FACT_ENV
+ CBM_K8S_FACT_ENV,
+ CBM_K8S_FACT_PATCH
} CBMK8sFactKind;
typedef struct {
CBMK8sFactKind fact;
@@ -739,7 +747,10 @@ typedef struct {
const char *edge;
const char *route;
const char *container;
- const char *key; /* CONNECTS_TO: the environment variable addressing it */
+ const char *key; /* CONNECTS_TO: the environment variable addressing it */
+ const char *group; /* PATCH: the API group named ("core"), NULL: any */
+ const char *version; /* PATCH: the API version named, NULL: any */
+ const char *path; /* PATCH: the patch file, NULL: inline */
int line;
} CBMK8sFact;
diff --git a/internal/cbm/extract_k8s.c b/internal/cbm/extract_k8s.c
index fe913845b..429e7e70e 100644
--- a/internal/cbm/extract_k8s.c
+++ b/internal/cbm/extract_k8s.c
@@ -15,6 +15,7 @@
#include "helpers.h"
#include "tree_sitter/api.h"
#include "foundation/constants.h"
+#include <ctype.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
@@ -22,6 +23,7 @@
/* Local constants. */
enum {
K8S_BUF_SIZE = 256,
+ K8S_PROPS_KV = 3, /* extra_props: one key, its value, the NULL end */
};
// ---------------------------------------------------------------------------
@@ -217,6 +219,240 @@ static TSNode unwrap_pair_value(TSNode pair) {
return val_node;
}
+// ---------------------------------------------------------------------------
+// Kustomize patches
+// ---------------------------------------------------------------------------
+
+// One `patches` entry of a kustomization (the kustomize v5 mapping form). The
+// patch file of `path` is an import (local name "patches"); what the entry
+// patches is a PATCH fact the K8s pass resolves in the kustomization's build:
+// its `target`, else each document of an inline `patch`; a path patch
+// without a target names the objects of its own documents, which the pass
+// reads from the patch file's Resources. A target the pass cannot evaluate
+// (a label or annotation selector) names nothing.
+
+typedef struct {
+ const char *kind;
+ const char *group;
+ const char *version;
+ const char *name;
+ const char *ns;
+ bool selector; /* labelSelector / annotationSelector */
+} kust_target_t;
+
+static void kust_target(CBMExtractCtx *ctx, TSNode map, kust_target_t *t) {
+ CBMArena *a = ctx->arena;
+ k8s_kids_t pairs = k8s_kids(map);
+ TSNode pair;
+ while (k8s_kid(&pairs, false, &pair)) {
+ if (strcmp(ts_node_type(pair), "block_mapping_pair") != 0) {
+ continue;
+ }
+ const char *key = get_scalar_text(a, ts_node_named_child(pair, 0), ctx->source);
+ TSNode v = unwrap_pair_value(pair);
+ const char *val = key && !ts_node_is_null(v) ? get_scalar_text(a, v, ctx->source) : NULL;
+ if (!val || !val[0]) {
+ continue;
+ }
+ if (strcmp(key, "kind") == 0) {
+ t->kind = val;
+ } else if (strcmp(key, "group") == 0) {
+ t->group = val;
+ } else if (strcmp(key, "version") == 0) {
+ t->version = val;
+ } else if (strcmp(key, "name") == 0) {
+ t->name = val;
+ } else if (strcmp(key, "namespace") == 0) {
+ t->ns = val;
+ } else if (strcmp(key, "labelSelector") == 0 || strcmp(key, "annotationSelector") == 0) {
+ t->selector = true;
+ }
+ }
+}
+
+// The block mapping a sequence item holds, null when it holds none (a
+// string entry, which emit_kustomize_sequence imports).
+static TSNode kust_item_mapping(TSNode item) {
+ TSNode v = first_content_child(item);
+ if (!ts_node_is_null(v) && strcmp(ts_node_type(v), "block_node") == 0) {
+ v = first_content_child(v);
+ }
+ if (ts_node_is_null(v) || strcmp(ts_node_type(v), "block_mapping") != 0) {
+ TSNode null_node = {0};
+ return null_node;
+ }
+ return v;
+}
+
+// The text of an inline patch: a block scalar's lines after its header line
+// (`|`, `|-`, `|2`...), or a one-line scalar.
+static const char *kust_inline_text(CBMExtractCtx *ctx, TSNode v) {
+ if (strcmp(ts_node_type(v), "block_scalar") == 0) {
+ const char *raw = cbm_node_text(ctx->arena, v, ctx->source);
+ const char *nl = raw ? strchr(raw, '\n') : NULL;
+ return nl ? nl + SKIP_ONE : NULL;
+ }
+ return get_scalar_text(ctx->arena, v, ctx->source);
+}
+
+// One line of an inline patch: its indent and `key: value` (the value
+// unquoted, a trailing comment dropped); false for a blank or comment line.
+static bool kust_line(const char *p, size_t len, int *indent, char *key, size_t ksz, char *val,
+ size_t vsz) {
+ size_t i = 0;
+ while (i < len && p[i] == ' ') {
+ i++;
+ }
+ if (i == len || p[i] == '#') {
+ return false;
+ }
+ *indent = (int)i;
+ size_t k = i;
+ while (k < len && p[k] != ':') {
+ k++;
+ }
+ snprintf(key, ksz, "%.*s", (int)(k - i), p + i);
+ val[0] = '\0';
+ size_t s = k < len ? k + SKIP_ONE : len;
+ while (s < len && p[s] == ' ') {
+ s++;
+ }
+ size_t e = s;
+ while (e < len && !(p[e] == '#' && p[e - SKIP_ONE] == ' ')) {
+ e++;
+ }
+ while (e > s && (p[e - SKIP_ONE] == ' ' || p[e - SKIP_ONE] == '\r')) {
+ e--;
+ }
+ if (e - s >= PAIR_LEN && (p[s] == '"' || p[s] == '\'') && p[e - SKIP_ONE] == p[s]) {
+ s++;
+ e--;
+ }
+ snprintf(val, vsz, "%.*s", (int)(e - s), p + s);
+ return true;
+}
+
+// Each document of an inline patch with a kind and a metadata.name: a PATCH
+// fact naming that object -- its kind, the group of its apiVersion ("core"
+// for the core group, as on a Resource), its name and namespace. A JSON6902
+// operation list names nothing.
+static const char KUST_DOC_END[] = "---";
+
+static void kust_inline_facts(CBMExtractCtx *ctx, const char *text, CBMK8sFact base) {
+ CBMArena *a = ctx->arena;
+ CBMK8sFact f = base;
+ int top = -1; /* indent of the document's keys */
+ int meta = -1; /* indent of metadata's keys, -1: not inside metadata */
+ bool in_meta = false;
+ for (const char *p = text; p;) {
+ const char *eol = strchr(p, '\n');
+ size_t len = eol ? (size_t)(eol - p) : strlen(p);
+ size_t b = strspn(p, " ");
+ bool doc_end = b + strlen(KUST_DOC_END) <= len &&
+ strncmp(p + b, KUST_DOC_END, strlen(KUST_DOC_END)) == 0;
+ int ind = 0;
+ char key[K8S_BUF_SIZE];
+ char val[K8S_BUF_SIZE];
+ if (!doc_end && kust_line(p, len, &ind, key, sizeof(key), val, sizeof(val))) {
+ if (top < 0) {
+ top = ind;
+ }
+ if (ind == top) {
+ in_meta = strcmp(key, "metadata") == 0 && !val[0];
+ meta = -1;
+ if (strcmp(key, "kind") == 0 && val[0]) {
+ f.kind = cbm_arena_strdup(a, val);
+ } else if (strcmp(key, "apiVersion") == 0 && val[0]) {
+ const char *slash = strchr(val, '/');
+ f.group = slash ? cbm_arena_strndup(a, val, (size_t)(slash - val)) : "core";
+ }
+ } else if (in_meta && ind > top) {
+ meta = meta < 0 ? ind : meta;
+ if (ind == meta && strcmp(key, "name") == 0 && val[0]) {
+ f.name = cbm_arena_strdup(a, val);
+ } else if (ind == meta && strcmp(key, "namespace") == 0 && val[0]) {
+ f.ns = cbm_arena_strdup(a, val);
+ }
+ }
+ }
+ if (doc_end || !eol) {
+ if (f.kind && f.name) {
+ cbm_k8sfact_push(&ctx->result->k8s_facts, a, f);
+ }
+ f = base;
+ top = -1;
+ in_meta = false;
+ }
+ p = eol ? eol + SKIP_ONE : NULL;
+ }
+}
+
+// The mapping entries of a kustomization's `patches` list.
+static void emit_kustomize_patches(CBMExtractCtx *ctx, TSNode seq) {
+ CBMArena *a = ctx->arena;
+ k8s_kids_t items = k8s_kids(seq);
+ TSNode item;
+ while (k8s_kid(&items, false, &item)) {
+ TSNode map = strcmp(ts_node_type(item), "block_sequence_item") == 0
+ ? kust_item_mapping(item)
+ : (TSNode){0};
+ if (ts_node_is_null(map)) {
+ continue;
+ }
+ const char *path = NULL;
+ const char *inline_text = NULL;
+ kust_target_t t = {0};
+ bool has_target = false;
+ k8s_kids_t pairs = k8s_kids(map);
+ TSNode pair;
+ while (k8s_kid(&pairs, false, &pair)) {
+ if (strcmp(ts_node_type(pair), "block_mapping_pair") != 0) {
+ continue;
+ }
+ const char *key = get_scalar_text(a, ts_node_named_child(pair, 0), ctx->source);
+ TSNode v = unwrap_pair_value(pair);
+ if (!key || ts_node_is_null(v)) {
+ continue;
+ }
+ if (strcmp(key, "path") == 0) {
+ path = get_scalar_text(a, v, ctx->source);
+ } else if (strcmp(key, "patch") == 0) {
+ inline_text = kust_inline_text(ctx, v);
+ } else if (strcmp(key, "target") == 0 &&
+ strcmp(ts_node_type(v), "block_mapping") == 0) {
+ kust_target(ctx, v, &t);
+ has_target = true;
+ }
+ }
+ if (path && path[0]) {
+ CBMImport imp = {.local_name = cbm_arena_strdup(a, "patches"),
+ .module_path = cbm_arena_strdup(a, path)};
+ cbm_imports_push(&ctx->result->imports, a, imp);
+ }
+ CBMK8sFact base = {.fact = CBM_K8S_FACT_PATCH,
+ .def_index = -1,
+ .via = "patch",
+ .edge = "OVERRIDE",
+ .path = path && path[0] ? path : NULL,
+ .line = (int)ts_node_start_point(item).row + TS_LINE_OFFSET};
+ if (has_target) {
+ if (!t.selector && (t.kind || t.name)) {
+ CBMK8sFact f = base;
+ f.kind = t.kind;
+ f.group = t.group;
+ f.version = t.version;
+ f.name = t.name;
+ f.ns = t.ns;
+ cbm_k8sfact_push(&ctx->result->k8s_facts, a, f);
+ }
+ } else if (inline_text) {
+ kust_inline_facts(ctx, inline_text, base);
+ } else if (base.path) {
+ cbm_k8sfact_push(&ctx->result->k8s_facts, a, base);
+ }
+ }
+}
+
// Process a single block_mapping_pair for kustomize list keys.
static void process_kustomize_pair(CBMExtractCtx *ctx, TSNode pair) {
if (strcmp(ts_node_type(pair), "block_mapping_pair") != 0) {
@@ -236,6 +472,9 @@ static void process_kustomize_pair(CBMExtractCtx *ctx, TSNode pair) {
return;
}
emit_kustomize_sequence(ctx, val_node, key_text);
+ if (strcmp(key_text, "patches") == 0) {
+ emit_kustomize_patches(ctx, val_node);
+ }
}
// Emit a "Class" def named after the document's `kind` scalar. A kustomization
@@ -1349,6 +1588,21 @@ static void extract_k8s_manifest(CBMExtractCtx *ctx) {
def.file_path = ctx->rel_path;
def.start_line = ts_node_start_point(mapping).row + TS_LINE_OFFSET;
def.end_line = ts_node_end_point(mapping).row + TS_LINE_OFFSET;
+ // The version of its apiVersion (`v1beta2` of cluster.x-k8s.io/v1beta2,
+ // `v1` of v1), which the QN leaves out (one object across versions); a
+ // bare group without one (`apiVersion: example.io`) has none.
+ const char *slash = strchr(id.api_version, '/');
+ const char *version = slash ? slash + SKIP_ONE : id.api_version;
+ bool versioned = slash || (version[0] == 'v' && isdigit((unsigned char)version[1]));
+ if (version[0] && versioned && id.api_version[0] != '<') {
+ const char **kv = (const char **)cbm_arena_alloc(a, K8S_PROPS_KV * sizeof(char *));
+ if (kv) {
+ kv[0] = "version";
+ kv[SKIP_ONE] = cbm_arena_strdup(a, version);
+ kv[PAIR_LEN] = NULL;
+ def.extra_props = kv;
+ }
+ }
cbm_defs_push(&ctx->result->defs, a, def);
k8s_emit_facts(ctx, mapping, group, id.kind, ctx->result->defs.count - SKIP_ONE);
}
diff --git a/src/pipeline/pass_k8s.c b/src/pipeline/pass_k8s.c
index 26972efe8..1a233aa90 100644
--- a/src/pipeline/pass_k8s.c
+++ b/src/pipeline/pass_k8s.c
@@ -551,9 +551,11 @@ static bool k8s_cluster_scoped(const char *kind) {
* "::": `<group>/<Kind>/<declared namespace or ->/<name>` (IDENTITY.md).
* `obj_key` is the logical identity: the namespace it lives in, `_` for a
* cluster-scoped kind, `?` when the deploy decides; `effective_ns` (when
- * not NULL) is the namespace a kustomize build gives it. NULL for a QN
- * without a well-formed key (the caller keeps the plain source tag). */
-static char *k8s_resource_props(const char *qn, const char *effective_ns) {
+ * not NULL) is the namespace a kustomize build gives it. `version` (NULL or
+ * "": none) is the version of its apiVersion, which the key leaves out. NULL
+ * for a QN without a well-formed key (the caller keeps the plain source
+ * tag). */
+static char *k8s_resource_props(const char *qn, const char *effective_ns, const char *version) {
enum { K8S_KEY_PARTS = 4, K8S_ESC = 6 * K8S_LABEL_LEN };
const char *key = qn ? strstr(qn, "::") : NULL;
if (!key) {
@@ -580,19 +582,23 @@ static char *k8s_resource_props(const char *qn, const char *effective_ns) {
: effective_ns ? effective_ns
: ns[0] ? ns
: "?";
- char esc[K8S_KEY_PARTS + SKIP_ONE][K8S_ESC];
+ char esc[K8S_KEY_PARTS + PAIR_LEN][K8S_ESC];
cbm_json_escape(esc[0], K8S_ESC, group);
cbm_json_escape(esc[1], K8S_ESC, kind);
cbm_json_escape(esc[2], K8S_ESC, ns);
cbm_json_escape(esc[3], K8S_ESC, name);
cbm_json_escape(esc[4], K8S_ESC, effective);
- size_t n = K8S_KEY_PARTS * K8S_ESC + K8S_ESC + CBM_SZ_256;
+ cbm_json_escape(esc[5], K8S_ESC, version ? version : "");
+ size_t n = K8S_KEY_PARTS * K8S_ESC + PAIR_LEN * K8S_ESC + CBM_SZ_256;
char *props = cbm_alloc(CBM_MEM_CLASS_OTHER, n);
if (!props) {
return NULL;
}
int w =
snprintf(props, n, "{\"source\":\"k8s\",\"group\":\"%s\",\"kind\":\"%s\"", esc[0], esc[1]);
+ if (esc[5][0]) {
+ w += snprintf(props + w, n - (size_t)w, ",\"version\":\"%s\"", esc[5]);
+ }
if (ns[0]) {
w += snprintf(props + w, n - (size_t)w, ",\"namespace\":\"%s\"", esc[2]);
}
@@ -601,6 +607,20 @@ static char *k8s_resource_props(const char *qn, const char *effective_ns) {
return props;
}
+/* The string property `key` of node `n` (as k8s_resource_props writes it:
+ * no escapes inside) into `out`, "" when it has none. */
+static void k8s_node_prop(const cbm_gbuf_node_t *n, const char *key, char *out, size_t out_sz) {
+ out[0] = '\0';
+ char head[CBM_SZ_64];
+ snprintf(head, sizeof(head), "\"%s\":\"", key);
+ const char *v = n->properties_json ? strstr(n->properties_json, head) : NULL;
+ if (v) {
+ v += strlen(head);
+ const char *e = strchr(v, '"');
+ snprintf(out, out_sz, "%.*s", e ? (int)(e - v) : 0, v);
+ }
+}
+
static void k8s_records_free(k8s_record_array_t *recs) {
for (int i = 0; i < recs->pair_count; i++) {
cbm_free(CBM_MEM_CLASS_OTHER, recs->pairs[i]);
@@ -677,6 +697,7 @@ typedef struct {
int file_n;
int file_cap;
bool referenced; /* included by another kustomization */
+ bool component; /* `kind: Component`: patches the build including it */
} k8s_kust_t;
typedef struct {
@@ -720,33 +741,47 @@ static bool k8s_grow(void **items, int *cap, int count, size_t elem) {
return true;
}
-/* The top-level `namespace:` of a kustomization, NULL when it sets none. */
-static char *k8s_kustomize_namespace(const char *source) {
- for (const char *p = source; p && *p;) {
+/* The value of a kustomization's top-level `key:` line into `val`; false
+ * when it has none, or an empty one. */
+static bool k8s_kustomize_top(const char *source, const char *key, char *val, size_t val_sz) {
+ char head[CBM_SZ_64];
+ int hl = snprintf(head, sizeof(head), "%s:", key);
+ for (const char *p = source; p && *p && hl > 0;) {
const char *eol = strchr(p, '\n');
size_t len = eol ? (size_t)(eol - p) : strlen(p);
- if (strncmp(p, "namespace:", K8S_SLEN("namespace:")) == 0) {
+ if (strncmp(p, head, (size_t)hl) == 0) {
char line[CBM_SZ_512];
snprintf(line, sizeof(line), "%.*s", (int)len, p);
- char key[64];
- char val[K8S_LABEL_LEN];
- if (k8s_split_kv(line, key, sizeof(key), val, sizeof(val)) && val[0]) {
- return cbm_mem_strdup(CBM_MEM_CLASS_OTHER, val);
- }
- return NULL;
+ char k[CBM_SZ_64];
+ return k8s_split_kv(line, k, sizeof(k), val, val_sz) && val[0];
}
p = eol ? eol + SKIP_ONE : NULL;
}
- return NULL;
+ return false;
+}
+
+/* The top-level `namespace:` of a kustomization, NULL when it sets none. */
+static char *k8s_kustomize_namespace(const char *source) {
+ char val[K8S_LABEL_LEN];
+ return k8s_kustomize_top(source, "namespace", val, sizeof(val))
+ ? cbm_mem_strdup(CBM_MEM_CLASS_OTHER, val)
+ : NULL;
+}
+
+/* A kustomize component (`kind: Component`), whose patches act on the build
+ * of each kustomization including it. */
+static bool k8s_kustomize_component(const char *source) {
+ char val[K8S_LABEL_LEN];
+ return k8s_kustomize_top(source, "kind", val, sizeof(val)) && strcmp(val, "Component") == 0;
}
-static void k8s_kusts_push(k8s_kusts_t *ks, const char *path, char *ns) {
+static void k8s_kusts_push(k8s_kusts_t *ks, const char *path, char *ns, bool component) {
if (!k8s_grow((void **)&ks->items, &ks->cap, ks->count, sizeof(*ks->items))) {
cbm_free(CBM_MEM_CLASS_OTHER, ns);
return;
}
- ks->items[ks->count++] =
- (k8s_kust_t){.path = cbm_mem_strdup(CBM_MEM_CLASS_OTHER, path), .ns = ns};
+ ks->items[ks->count++] = (k8s_kust_t){
+ .path = cbm_mem_strdup(CBM_MEM_CLASS_OTHER, path), .ns = ns, .component = component};
}
static void k8s_kusts_free(k8s_kusts_t *ks) {
@@ -820,6 +855,12 @@ static void k8s_kusts_wire(cbm_pipeline_ctx_t *ctx, k8s_kusts_t *ks, CBMHashTabl
continue;
}
k8s_kust_t *kust = &ks->items[k - SKIP_ONE];
+ /* a patch file (`patches`, `patchesStrategicMerge`) is no member of
+ * the build: its documents change objects, they are none */
+ const char *props = edges[i]->properties_json;
+ if (props && strstr(props, "\"local_name\":\"patches")) {
+ continue;
+ }
int kid = tgt->label && strcmp(tgt->label, "Folder") == 0
? k8s_kust_in_dir(by_path, tgt->file_path)
: k8s_kust_at(by_path, tgt->file_path);
@@ -1104,7 +1145,9 @@ static void k8s_apply_effective_namespaces(cbm_pipeline_ctx_t *ctx, k8s_bundles_
if (!any_set) {
continue; /* no build sets a namespace: the declared one stands */
}
- char *props = k8s_resource_props(n->qualified_name, agree ? eff : "?");
+ char version[K8S_LABEL_LEN];
+ k8s_node_prop(n, "version", version, sizeof(version));
+ char *props = k8s_resource_props(n->qualified_name, agree ? eff : "?", version);
if (props) {
(void)cbm_gbuf_node_set_properties_json((cbm_gbuf_node_t *)n, props);
cbm_free(CBM_MEM_CLASS_OTHER, props);
@@ -1170,6 +1213,19 @@ typedef struct {
char *container; /* NULL: unnamed */
} k8s_img_t;
+/* A patch a kustomization states (extract_k8s.c PATCH fact): what it names
+ * in the kustomization's build. */
+typedef struct {
+ char *kust; /* the kustomization file */
+ char *path; /* the patch file (repository path), NULL: inline */
+ char *kind; /* kind / group / version / name / ns named, NULL: any; */
+ char *group; /* kind and name both NULL: the documents of the */
+ char *version; /* patch file name them */
+ char *name;
+ char *ns;
+ int line;
+} k8s_patch_t;
+
typedef struct {
k8s_ref_t *refs;
int ref_n;
@@ -1192,6 +1248,9 @@ typedef struct {
k8s_env_t *envs;
int env_n;
int env_cap;
+ k8s_patch_t *patches;
+ int patch_n;
+ int patch_cap;
} k8s_facts_t;
static void k8s_facts_free(k8s_facts_t *f) {
@@ -1226,6 +1285,17 @@ static void k8s_facts_free(k8s_facts_t *f) {
cbm_free(CBM_MEM_CLASS_OTHER, f->envs[i].key);
cbm_free(CBM_MEM_CLASS_OTHER, f->envs[i].container);
}
+ for (int i = 0; i < f->patch_n; i++) {
+ k8s_patch_t *p = &f->patches[i];
+ cbm_free(CBM_MEM_CLASS_OTHER, p->kust);
+ cbm_free(CBM_MEM_CLASS_OTHER, p->path);
+ cbm_free(CBM_MEM_CLASS_OTHER, p->kind);
+ cbm_free(CBM_MEM_CLASS_OTHER, p->group);
+ cbm_free(CBM_MEM_CLASS_OTHER, p->version);
+ cbm_free(CBM_MEM_CLASS_OTHER, p->name);
+ cbm_free(CBM_MEM_CLASS_OTHER, p->ns);
+ }
+ cbm_free(CBM_MEM_CLASS_OTHER, f->patches);
cbm_free(CBM_MEM_CLASS_OTHER, f->envs);
cbm_free(CBM_MEM_CLASS_OTHER, f->hrs);
cbm_free(CBM_MEM_CLASS_OTHER, f->srcs);
@@ -2293,7 +2363,12 @@ static void handle_k8s_manifest(cbm_pipeline_ctx_t *ctx, const char *rel_path, c
continue;
}
- char *props = k8s_resource_props(def->qualified_name, NULL);
+ const char *version = NULL; /* extract_k8s.c: the one extra property */
+ if (def->extra_props && def->extra_props[0] && def->extra_props[SKIP_ONE] &&
+ strcmp(def->extra_props[0], "version") == 0) {
+ version = def->extra_props[SKIP_ONE];
+ }
+ char *props = k8s_resource_props(def->qualified_name, NULL, version);
int64_t node_id = cbm_gbuf_upsert_node(
ctx->gbuf, "Resource", def->name, def->qualified_name, rel_path, (int)def->start_line,
(int)def->end_line, props ? props : "{\"source\":\"k8s\"}");
@@ -2808,9 +2883,14 @@ static void k8s_prep_file(const k8s_prep_job_t *job, int i, k8s_prep_t *out) {
out->source = k8s_read_file(path, &out->src_len);
out->kind = out->source ? K8S_DEP : K8S_SKIP;
} else if (lang == CBM_LANG_KUSTOMIZE) {
- /* Its `namespace:` is the namespace of the objects it builds. */
+ /* Its `namespace:` is the namespace of the objects it builds; its
+ * patches (PATCH facts) change some of them. */
out->source = k8s_read_file(path, &out->src_len);
out->kind = out->source ? K8S_KUSTOMIZE : K8S_SKIP;
+ if (out->source) {
+ out->res = cbm_extract_file(out->source, out->src_len, CBM_LANG_KUSTOMIZE,
+ ctx->project_name, rel, CBM_EXTRACT_BUDGET, NULL, NULL);
+ }
} else if (lang == CBM_LANG_YAML || lang == CBM_LANG_K8S) {
/* Read source once to classify (and reuse for uncached extraction). */
out->source = k8s_read_file(path, &out->src_len);
@@ -3377,6 +3457,314 @@ static void k8s_link_envs(cbm_pipeline_ctx_t *ctx, const k8s_facts_t *f) {
}
}
+/* ── Kustomize patches (PHASE 5) ───────────────────────────────────── */
+
+static char *k8s_dup_opt(const char *s) {
+ return s ? cbm_mem_strdup(CBM_MEM_CLASS_OTHER, s) : NULL;
+}
+
+/* Keep a kustomization's PATCH facts, each patch file as a repository path
+ * (one that leaves the repository, or a URL, names no file of it). */
+static void k8s_patches_keep(k8s_facts_t *f, const char *kust, const CBMFileResult *res) {
+ char dir[CBM_SZ_1K];
+ k8s_dirname(kust, dir, sizeof(dir));
+ for (int i = 0; res && i < res->k8s_facts.count; i++) {
+ const CBMK8sFact *x = &res->k8s_facts.items[i];
+ char path[CBM_SZ_1K];
+ if (x->fact != CBM_K8S_FACT_PATCH) {
+ continue;
+ }
+ if (x->path) {
+ char joined[CBM_SZ_2K];
+ snprintf(joined, sizeof(joined), "%s%s%s", dir, dir[0] ? "/" : "", x->path);
+ if (!k8s_norm_dir(joined, path, sizeof(path))) {
+ continue;
+ }
+ }
+ if (!k8s_grow((void **)&f->patches, &f->patch_cap, f->patch_n, sizeof(*f->patches))) {
+ continue;
+ }
+ f->patches[f->patch_n++] =
+ (k8s_patch_t){.kust = cbm_mem_strdup(CBM_MEM_CLASS_OTHER, kust),
+ .path = x->path ? cbm_mem_strdup(CBM_MEM_CLASS_OTHER, path) : NULL,
+ .kind = k8s_dup_opt(x->kind),
+ .group = k8s_dup_opt(x->group),
+ .version = k8s_dup_opt(x->version),
+ .name = k8s_dup_opt(x->name),
+ .ns = k8s_dup_opt(x->ns),
+ .line = x->line};
+ }
+}
+
+static int k8s_cmp_patch(const void *a, const void *b) {
+ const k8s_patch_t *x = a;
+ const k8s_patch_t *y = b;
+ int c = strcmp(x->kust, y->kust);
+ return c ? c : (x->line > y->line) - (x->line < y->line);
+}
+
+/* A Resource's kind and name, from its node name "Kind/name". */
+static bool k8s_kind_name(const cbm_gbuf_node_t *n, char *kind, size_t kind_sz, const char **name) {
+ const char *slash = n->name ? strchr(n->name, '/') : NULL;
+ if (!slash) {
+ return false;
+ }
+ snprintf(kind, kind_sz, "%.*s", (int)(slash - n->name), n->name);
+ *name = slash + SKIP_ONE;
+ return true;
+}
+
+/* What a patch names: kind / group / version / name / ns (NULL: any). A
+ * name compares as text: a target's is a regular expression in kustomize,
+ * which an object name (DNS characters, `.` matching itself) meets as text
+ * alone -- a pattern (`web-.*`) names nothing here. */
+typedef struct {
+ const char *kind;
+ const char *group;
+ const char *version;
+ const char *name;
+ const char *ns;
+} k8s_want_t;
+
+/* Is Resource `t` what `w` names? A namespace meets the target's declared
+ * one or its effective one. */
+static bool k8s_patch_meets(const cbm_gbuf_node_t *t, const k8s_want_t *w) {
+ char tkind[K8S_LABEL_LEN];
+ const char *tname = NULL;
+ if (!t->label || strcmp(t->label, "Resource") != 0 ||
+ !k8s_kind_name(t, tkind, sizeof(tkind), &tname)) {
+ return false;
+ }
+ if (w->kind && strcmp(w->kind, tkind) != 0) {
+ return false;
+ }
+ if (w->name && strcmp(w->name, tname) != 0) {
+ return false;
+ }
+ char prop[K8S_LABEL_LEN];
+ if (w->group) {
+ k8s_node_prop(t, "group", prop, sizeof(prop));
+ if (strcmp(w->group, prop) != 0) {
+ return false;
+ }
+ }
+ if (w->version) {
+ k8s_node_prop(t, "version", prop, sizeof(prop));
+ if (strcmp(w->version, prop) != 0) {
+ return false;
+ }
+ }
+ if (w->ns) {
+ char decl[K8S_LABEL_LEN];
+ k8s_declared_ns(t->qualified_name, decl, sizeof(decl));
+ k8s_effective_ns(t, prop, sizeof(prop));
+ return strcmp(w->ns, decl) == 0 || strcmp(w->ns, prop) == 0;
+ }
+ return true;
+}
+
+static void k8s_patch_edge(cbm_pipeline_ctx_t *ctx, int64_t src, int64_t tgt,
+ const k8s_patch_t *p) {
+ if (src <= 0 || tgt <= 0 || src == tgt) {
+ return;
+ }
+ char ek[CBM_SZ_2K];
+ char ep[CBM_SZ_2K];
+ cbm_json_escape(ek, (int)sizeof(ek), p->kust);
+ cbm_json_escape(ep, (int)sizeof(ep), p->path ? p->path : "inline");
+ char props[CBM_SZ_4K + CBM_SZ_1K];
+ snprintf(props, sizeof(props),
+ "{\"via\":\"patch\",\"kustomization\":\"%s\",\"patch\":\"%s\",\"line\":%d}", ek, ep,
+ p->line);
+ cbm_gbuf_insert_edge(ctx->gbuf, src, tgt, "OVERRIDE", props);
+}
+
+/* The build a patch acts in: its manifests, their Resources by name
+ * (`names`: "Kind/name" -> ids, this build's only -- a repository-wide name
+ * would visit every copy of a name for every patch, quadratic in copies) and
+ * every Resource by file. */
+typedef struct {
+ cbm_pipeline_ctx_t *ctx;
+ const k8s_paths_t *files;
+ CBMHashTable *names;
+ CBMHashTable *by_file;
+} k8s_build_t;
+
+/* Draw `p` from `src` to each object of the build `w` names. A named kind
+ * is looked up by name, anything else walks the build. */
+static void k8s_patch_targets(const k8s_build_t *b, const k8s_patch_t *p, int64_t src,
+ const k8s_want_t *w) {
+ cbm_gbuf_t *gb = b->ctx->gbuf;
+ if (w->kind && w->name) {
+ char key[CBM_SZ_1K];
+ snprintf(key, sizeof(key), "%s/%s", w->kind, w->name);
+ const k8s_ids_t *ids = cbm_ht_get(b->names, key);
+ for (int i = 0; ids && i < ids->count; i++) {
+ const cbm_gbuf_node_t *t = cbm_gbuf_find_by_id(gb, ids->items[i]);
+ atomic_fetch_add_explicit(&g_k8s_candidates, SKIP_ONE, memory_order_relaxed);
+ if (t && k8s_patch_meets(t, w)) {
+ k8s_patch_edge(b->ctx, src, t->id, p);
+ }
+ }
+ return;
+ }
+ for (int f = 0; f < b->files->count; f++) {
+ const k8s_ids_t *objs = cbm_ht_get(b->by_file, b->files->items[f]);
+ for (int o = 0; objs && o < objs->count; o++) {
+ const cbm_gbuf_node_t *t = cbm_gbuf_find_by_id(gb, objs->items[o]);
+ atomic_fetch_add_explicit(&g_k8s_candidates, SKIP_ONE, memory_order_relaxed);
+ if (t && k8s_patch_meets(t, w)) {
+ k8s_patch_edge(b->ctx, src, t->id, p);
+ }
+ }
+ }
+}
+
+/* The File node of `path` (a kustomization, a patch file: the node kustomize
+ * IMPORTS leave from), 0 when none. */
+static int64_t k8s_file_of(cbm_pipeline_ctx_t *ctx, const char *path) {
+ const cbm_gbuf_node_t *n = cbm_pipeline_file_node(ctx->gbuf, ctx->project_name, path);
+ return n ? n->id : 0;
+}
+
+/* Patch `p` in build `b`: a path patch without a target -- each of its
+ * documents to the object of the same group, kind and name (and namespace,
+ * when it declares one); otherwise from its documents -- a file of none (a
+ * JSON6902 operation list): from its File; inline: from the kustomization's
+ * File `kust_file` -- to what it names. */
+static void k8s_patch_in_build(const k8s_build_t *b, const k8s_patch_t *p, int64_t kust_file) {
+ const k8s_ids_t *docs = p->path ? cbm_ht_get(b->by_file, p->path) : NULL;
+ if (!p->kind && !p->name) {
+ for (int d = 0; docs && d < docs->count; d++) {
+ const cbm_gbuf_node_t *doc = cbm_gbuf_find_by_id(b->ctx->gbuf, docs->items[d]);
+ char kind[K8S_LABEL_LEN];
+ char group[K8S_LABEL_LEN];
+ char ns[K8S_LABEL_LEN];
+ const char *name = NULL;
+ if (!doc || !k8s_kind_name(doc, kind, sizeof(kind), &name)) {
+ continue;
+ }
+ k8s_node_prop(doc, "group", group, sizeof(group));
+ k8s_declared_ns(doc->qualified_name, ns, sizeof(ns));
+ k8s_want_t w = {kind, group[0] ? group : NULL, NULL, name, ns[0] ? ns : NULL};
+ k8s_patch_targets(b, p, doc->id, &w);
+ }
+ return;
+ }
+ k8s_want_t w = {p->kind, p->group, p->version, p->name, p->ns};
+ if (docs && docs->count > 0) {
+ for (int d = 0; d < docs->count; d++) {
+ k8s_patch_targets(b, p, docs->items[d], &w);
+ }
+ } else {
+ k8s_patch_targets(b, p, p->path ? k8s_file_of(b->ctx, p->path) : kust_file, &w);
+ }
+}
+
+/* The builds the patches of kustomization `k` act in, into `out`: its own;
+ * a component's are those of each kustomization including it (`inc`: the
+ * includers of every kustomization, by index). */
+static void k8s_patch_builds(const k8s_kusts_t *ks, const k8s_ints_t *inc, int k, k8s_ints_t *out) {
+ out->count = 0;
+ if (!ks->items[k].component) {
+ if (k8s_grow((void **)&out->items, &out->cap, out->count, sizeof(int))) {
+ out->items[out->count++] = k;
+ }
+ return;
+ }
+ for (int i = 0; i < inc[k].count; i++) {
+ if (k8s_grow((void **)&out->items, &out->cap, out->count, sizeof(int))) {
+ out->items[out->count++] = inc[k].items[i];
+ }
+ }
+}
+
+/* Kustomize patches -> OVERRIDE {via: patch, kustomization, patch, line},
+ * child -> base: each patch against the build of the kustomization stating
+ * it, a component's against the build of each kustomization including it
+ * (the component's own resources are part of that build). */
+static void k8s_link_patches(cbm_pipeline_ctx_t *ctx, const k8s_kusts_t *ks, k8s_facts_t *f) {
+ if (f->patch_n == 0 || ks->count == 0) {
+ return;
+ }
+ CBMHashTable *by_path = cbm_ht_create(0);
+ CBMHashTable *by_file = cbm_ht_create(0);
+ int *seen = cbm_calloc(CBM_MEM_CLASS_OTHER, (size_t)ks->count * sizeof(int));
+ k8s_ints_t *inc = cbm_calloc(CBM_MEM_CLASS_OTHER, (size_t)ks->count * sizeof(*inc));
+ const cbm_gbuf_node_t **res = NULL;
+ int res_n = 0;
+ if (by_path && by_file && seen && inc &&
+ cbm_gbuf_find_by_label(ctx->gbuf, "Resource", &res, &res_n) == 0) {
+ for (int i = 0; i < res_n; i++) {
+ if (res[i]->file_path) {
+ k8s_index_add(by_file, res[i]->file_path, res[i]->id);
+ }
+ }
+ for (int i = 0; i < ks->count; i++) {
+ cbm_ht_set(by_path, ks->items[i].path, (void *)(intptr_t)(i + SKIP_ONE));
+ for (int c = 0; c < ks->items[i].kid_n; c++) {
+ k8s_ints_t *v = &inc[ks->items[i].kids[c]];
+ if (k8s_grow((void **)&v->items, &v->cap, v->count, sizeof(int))) {
+ v->items[v->count++] = i;
+ }
+ }
+ }
+ k8s_qsort(f->patches, (size_t)f->patch_n, sizeof(*f->patches), k8s_cmp_patch);
+ k8s_ints_t builds = {0};
+ int mark = 0;
+ for (int i = 0; i < f->patch_n;) {
+ int j = i;
+ while (j < f->patch_n && strcmp(f->patches[j].kust, f->patches[i].kust) == 0) {
+ j++;
+ }
+ int k = k8s_kust_at(by_path, f->patches[i].kust) - SKIP_ONE;
+ int64_t kust_file = 0;
+ if (k >= 0) {
+ k8s_patch_builds(ks, inc, k, &builds);
+ kust_file = k8s_file_of(ctx, ks->items[k].path);
+ }
+ for (int bi = 0; k >= 0 && bi < builds.count; bi++) {
+ k8s_paths_t files = {0};
+ k8s_kust_closure(ks, builds.items[bi], seen, ++mark, &files);
+ k8s_paths_sort_unique(&files);
+ CBMHashTable *names = cbm_ht_create(0);
+ for (int x = 0; names && x < files.count; x++) {
+ const k8s_ids_t *objs = cbm_ht_get(by_file, files.items[x]);
+ for (int o = 0; objs && o < objs->count; o++) {
+ const cbm_gbuf_node_t *n = cbm_gbuf_find_by_id(ctx->gbuf, objs->items[o]);
+ if (n && n->name) {
+ k8s_index_add(names, n->name, n->id);
+ }
+ }
+ }
+ k8s_build_t b = {ctx, &files, names, by_file};
+ for (int q = i; names && q < j; q++) {
+ k8s_patch_in_build(&b, &f->patches[q], kust_file);
+ }
+ if (names) {
+ cbm_ht_foreach(names, k8s_free_ids_entry, NULL);
+ cbm_ht_free(names);
+ }
+ cbm_free(CBM_MEM_CLASS_OTHER, (void *)files.items);
+ }
+ i = j;
+ }
+ cbm_free(CBM_MEM_CLASS_OTHER, builds.items);
+ }
+ for (int i = 0; inc && i < ks->count; i++) {
+ cbm_free(CBM_MEM_CLASS_OTHER, inc[i].items);
+ }
+ cbm_free(CBM_MEM_CLASS_OTHER, inc);
+ cbm_free(CBM_MEM_CLASS_OTHER, seen);
+ if (by_file) {
+ cbm_ht_foreach(by_file, k8s_free_ids_entry, NULL);
+ cbm_ht_free(by_file);
+ }
+ if (by_path) {
+ cbm_ht_free(by_path);
+ }
+}
+
static void k8s_link_deploys(cbm_pipeline_ctx_t *ctx, k8s_kusts_t *ks, k8s_bundles_t *b,
const k8s_facts_t *f) {
if (f->dep_n == 0 && f->hr_n == 0 && f->src_n == 0) {
@@ -3528,7 +3916,9 @@ int cbm_pipeline_pass_k8s(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *files,
helm_count++;
break;
case K8S_KUSTOMIZE:
- k8s_kusts_push(&kusts, rel, k8s_kustomize_namespace(p->source));
+ k8s_kusts_push(&kusts, rel, k8s_kustomize_namespace(p->source),
+ k8s_kustomize_component(p->source));
+ k8s_patches_keep(&facts, rel, p->res);
break;
case K8S_MANIFEST:
handle_k8s_manifest(ctx, rel, p->source, p->res, &recs, &facts);
@@ -3567,6 +3957,7 @@ int cbm_pipeline_pass_k8s(cbm_pipeline_ctx_t *ctx, const cbm_file_info_t *files,
k8s_link_deploys(ctx, &kusts, &bundles, &facts);
k8s_link_images(ctx, &facts);
k8s_link_envs(ctx, &facts);
+ k8s_link_patches(ctx, &kusts, &facts);
k8s_facts_free(&facts);
k8s_records_free(&recs);
/* Link `file://` chart dependencies now that every Chart.yaml is read,
diff --git a/src/pipeline/pipeline_internal.h b/src/pipeline/pipeline_internal.h
index d327026c5..e37bd7785 100644
--- a/src/pipeline/pipeline_internal.h
+++ b/src/pipeline/pipeline_internal.h
@@ -1495,8 +1495,10 @@ int cbm_pipeline_build_fresh_semantic_manifest(cbm_pipeline_t *p, const char *pr
* image_ignore). A workload or compose service CONNECTS_TO the Service
* its environment addresses (extract_k8s.c, pass_docker.c). A script's
* curl / wget HTTP_CALLS the Route of the URL it states (pass_shell.c).
- * An index built before holds none of them, so it rebuilds once on
- * upgrade. */
+ * A kustomize patch OVERRIDEs the objects of its build it changes, its
+ * file an IMPORTS of the kustomization; a Resource keeps the version of
+ * its apiVersion (extract_k8s.c, pass_k8s.c). An index built before
+ * holds none of them, so it rebuilds once on upgrade. */
enum { CBM_SEMANTIC_INDEX_VERSION = 9 };
typedef struct {
diff --git a/tests/fixtures/complexity/Kubernetes/kustomization.yaml b/tests/fixtures/complexity/Kubernetes/kustomization.yaml
index aea332b3f..c1ea5df8c 100644
--- a/tests/fixtures/complexity/Kubernetes/kustomization.yaml
+++ b/tests/fixtures/complexity/Kubernetes/kustomization.yaml
@@ -6,3 +6,19 @@ resources:
- crd.yaml
- ocirepository.yaml
- helmrelease.yaml
+patches:
+ - path: patch.yaml
+ - path: patch-more.yaml
+ - patch: |-
+ apiVersion: v1
+ kind: Service
+ metadata:
+ name: web
+ spec:
+ type: NodePort
+ - patch: |-
+ - op: add
+ path: /metadata/labels/tier
+ value: front
+ target:
+ kind: Deployment
diff --git a/tests/fixtures/complexity/Kubernetes/patch-more.yaml b/tests/fixtures/complexity/Kubernetes/patch-more.yaml
new file mode 100644
index 000000000..73e395b9b
--- /dev/null
+++ b/tests/fixtures/complexity/Kubernetes/patch-more.yaml
@@ -0,0 +1,27 @@
+apiVersion: v1
+kind: ConfigMap
+metadata:
+ name: web-config
+data:
+ mode: patched
+---
+apiVersion: v1
+kind: ServiceAccount
+metadata:
+ name: web
+ annotations:
+ patched: "true"
+---
+apiVersion: networking.k8s.io/v1
+kind: Ingress
+metadata:
+ name: web
+ annotations:
+ patched: "true"
+---
+apiVersion: autoscaling/v2
+kind: HorizontalPodAutoscaler
+metadata:
+ name: web
+spec:
+ maxReplicas: 9
diff --git a/tests/fixtures/complexity/Kubernetes/patch.yaml b/tests/fixtures/complexity/Kubernetes/patch.yaml
new file mode 100644
index 000000000..a3ed04101
--- /dev/null
+++ b/tests/fixtures/complexity/Kubernetes/patch.yaml
@@ -0,0 +1,6 @@
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+ name: web
+spec:
+ replicas: 3
diff --git a/tests/test_grammar_probe_f.c b/tests/test_grammar_probe_f.c
index 1056b3b66..98fa40119 100644
--- a/tests/test_grammar_probe_f.c
+++ b/tests/test_grammar_probe_f.c
@@ -2581,6 +2581,126 @@ TEST(probe_env_address_connects_to_its_service) {
PASS();
}
+/* Every kustomize patch edge as "<source file> <source label> -> <target>
+ * @<target file>", then "patch imports <n>" (IMPORTS of patch files), "maps
+ * into patches <n>" (INFRA_MAPS into a patch file's documents) and "version
+ * <v>" (base/deploy.yaml's Resource), "odd version <v>" (other/odd.yaml's:
+ * none without one, missing without the Resource). */
+static char *gpf_patches(const GpfFile *files, int nfiles) {
+ GpfProj lp;
+ cbm_store_t *store = gpf_index_files(&lp, files, nfiles);
+ char *out = NULL;
+ if (store) {
+ sqlite3_stmt *st = NULL;
+ const char *sql =
+ "SELECT coalesce((SELECT group_concat(x, char(10)) FROM (SELECT s.file_path || ' ' || "
+ "s.label || ' -> ' || t.name || ' @' || t.file_path AS x FROM edges e JOIN nodes s ON "
+ "s.id=e.source_id JOIN nodes t ON t.id=e.target_id WHERE e.project=?1 AND "
+ "e.type='OVERRIDE' AND json_extract(e.properties,'$.via')='patch' ORDER BY x)), '') "
+ "|| char(10) || 'patch imports ' || (SELECT COUNT(*) FROM edges e WHERE e.project=?1 "
+ "AND e.type='IMPORTS' AND json_extract(e.properties,'$.local_name')='patches') || "
+ "char(10) || 'maps into patches ' || (SELECT COUNT(*) FROM edges e JOIN nodes t ON "
+ "t.id=e.target_id WHERE e.project=?1 AND e.type='INFRA_MAPS' AND t.file_path LIKE "
+ "'overlays/%') || char(10) || 'version ' || coalesce((SELECT "
+ "json_extract(properties,'$.version') FROM nodes WHERE project=?1 AND "
+ "label='Resource' AND file_path='base/deploy.yaml'), '-') || char(10) || "
+ "'odd version ' || coalesce((SELECT coalesce(json_extract(properties,'$.version'), "
+ "'none') FROM nodes WHERE project=?1 AND label='Resource' AND "
+ "file_path='other/odd.yaml'), 'missing')";
+ if (sqlite3_prepare_v2(cbm_store_get_db(store), sql, -1, &st, NULL) == SQLITE_OK) {
+ sqlite3_bind_text(st, 1, lp.project, -1, SQLITE_STATIC);
+ if (sqlite3_step(st) == SQLITE_ROW) {
+ out = strdup((const char *)sqlite3_column_text(st, 0));
+ }
+ }
+ sqlite3_finalize(st);
+ }
+ gpf_cleanup(&lp, store);
+ return out;
+}
+
+/* A kustomization's patches OVERRIDE the objects of its build they change,
+ * child -> base: a patch file's documents the objects of the same kind and
+ * name; an inline patch (from the kustomization) the object its document
+ * names (a `${VAR}` name as written); a JSON6902 operation file (from the
+ * file) the objects its target selects -- group and version included; a
+ * component's the objects of the build including it; a kind alone every
+ * object of that kind. Never: an object outside the build, one the patch
+ * does not name (another name, group, version or namespace), a component
+ * nothing includes, a label selector (not evaluated). A patch file is an import of
+ * the kustomization, never a member of its build (a Service selects no patch
+ * document). A Resource keeps the version of its apiVersion; a bare group
+ * (`apiVersion: example.io`) has none. */
+TEST(probe_kustomize_patches_override_their_base) {
+ static const GpfFile files[] = {
+ {"base/kustomization.yaml", "resources:\n- deploy.yaml\n- svc.yaml\n- cm.yaml\n"},
+ {"base/cm.yaml",
+ "apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: ${APP}-config\n namespace: app\n"},
+ {"base/deploy.yaml",
+ "apiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: web\n namespace: app\nspec:\n"
+ " template:\n metadata:\n labels:\n app: web\n"},
+ {"base/svc.yaml", "apiVersion: v1\nkind: Service\nmetadata:\n name: web\n namespace: app\n"
+ "spec:\n selector:\n app: web\n"},
+ {"overlays/prod/kustomization.yaml",
+ "namespace: app\nresources:\n- ../../base\ncomponents:\n- ../../components/extra\n"
+ "patches:\n"
+ "- path: patch-deploy.yaml\n"
+ "- path: ns-patch.yaml\n"
+ "- path: all.yaml\n target:\n kind: Service\n"
+ "- patch: |-\n apiVersion: v1\n kind: Service\n metadata:\n name: web\n"
+ " spec:\n type: NodePort\n"
+ "- path: ops.yaml\n target:\n kind: Deployment\n name: web\n"
+ "- path: ops-v2.yaml\n target:\n group: apps\n version: v2\n kind: Deployment\n"
+ "- path: ops-batch.yaml\n target:\n group: batch\n kind: Deployment\n"
+ "- path: sel.yaml\n target:\n kind: Deployment\n labelSelector: tier=none\n"
+ "- path: cm-patch.yaml\n"
+ "- patch: |-\n apiVersion: apps/v1\n kind: Deployment\n metadata:\n"
+ " name: missing\n"},
+ {"overlays/prod/ops-batch.yaml", "- op: replace\n path: /spec/replicas\n value: 5\n"},
+ {"overlays/prod/ns-patch.yaml",
+ "apiVersion: v1\nkind: Service\nmetadata:\n name: web\n namespace: elsewhere\n"},
+ {"overlays/prod/all.yaml", "- op: add\n path: /metadata/labels/tier\n value: front\n"},
+ {"overlays/prod/sel.yaml", "- op: replace\n path: /spec/replicas\n value: 6\n"},
+ {"overlays/prod/cm-patch.yaml",
+ "apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: ${APP}-config\n namespace: app\n"
+ "data:\n k: v\n"},
+ {"overlays/prod/patch-deploy.yaml",
+ "apiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: web\n namespace: app\nspec:\n"
+ " template:\n metadata:\n labels:\n app: web\n"},
+ {"overlays/prod/ops.yaml", "- op: replace\n path: /spec/replicas\n value: 3\n"},
+ {"overlays/prod/ops-v2.yaml", "- op: replace\n path: /spec/replicas\n value: 4\n"},
+ {"components/extra/kustomization.yaml",
+ "apiVersion: kustomize.config.k8s.io/v1alpha1\nkind: Component\npatches:\n"
+ "- patch: |-\n apiVersion: apps/v1\n kind: Deployment\n metadata:\n"
+ " name: web\n namespace: app\n"},
+ {"components/unused/kustomization.yaml",
+ "apiVersion: kustomize.config.k8s.io/v1alpha1\nkind: Component\npatches:\n"
+ "- patch: |-\n apiVersion: v1\n kind: Service\n metadata:\n name: web\n"},
+ {"other/deploy.yaml",
+ "apiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: web\n namespace: app\n"},
+ {"other/odd.yaml", "apiVersion: example.io\nkind: Thing\nmetadata:\n name: odd\n"}};
+ int n = (int)(sizeof(files) / sizeof(files[0]));
+ char *got = gpf_patches(files, n);
+ static const char want[] =
+ "components/extra/kustomization.yaml File -> Deployment/web @base/deploy.yaml\n"
+ "overlays/prod/all.yaml File -> Service/web @base/svc.yaml\n"
+ "overlays/prod/cm-patch.yaml Resource -> ConfigMap/${APP}-config @base/cm.yaml\n"
+ "overlays/prod/kustomization.yaml File -> Service/web @base/svc.yaml\n"
+ "overlays/prod/ops.yaml File -> Deployment/web @base/deploy.yaml\n"
+ "overlays/prod/patch-deploy.yaml Resource -> Deployment/web @base/deploy.yaml\n"
+ "patch imports 8\n"
+ "maps into patches 0\n"
+ "version v1\n"
+ "odd version none";
+ if (!got || strcmp(got, want) != 0) {
+ fprintf(stderr, "patches got:\n%s\nwant:\n%s\n", got ? got : "(null)", want);
+ free(got);
+ FAIL("kustomize patch edges");
+ }
+ free(got);
+ PASS();
+}
+
/* Every script HTTP_CALLS edge as "<source file> <route QN>", then a line
* "edgeless routes <n>": the Route nodes no edge touches. */
static char *gpf_script_http(const GpfFile *files, int nfiles) {
@@ -5016,6 +5136,7 @@ SUITE(grammar_probe_f) {
RUN_TEST(probe_container_env_joins_its_own_image_readers);
RUN_TEST(probe_env_address_connects_to_its_service);
RUN_TEST(probe_script_http_request_calls_its_route);
+ RUN_TEST(probe_kustomize_patches_override_their_base);
RUN_TEST(probe_image_hub_splits_by_component);
RUN_TEST(probe_gitops_objects_deploy_their_units);
RUN_TEST(probe_shell_kubectl_deploys_what_it_applies);