nyl 0.4.1

Kubernetes manifest generator with Helm integration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
/// Component resource definition
///
/// A Component is a lightweight wrapper that references a Helm chart in the
/// configured `components/` directory.  The `kind` field encodes the relative
/// path to the chart directory (e.g. `myapiversion/v1/MyComponent`), and the
/// `spec` is forwarded directly as Helm values.
use serde::{Deserialize, Serialize};

use crate::constants::API_VERSION_COMPONENTS;
use crate::resources::{ChartRef, ObjectMetadata};

fn default_spec() -> serde_json::Value {
    serde_json::Value::Object(serde_json::Map::new())
}

/// Component resource
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NylComponent {
    #[serde(rename = "apiVersion")]
    pub api_version: String,

    /// Relative path under `components/` that identifies the Helm chart
    pub kind: String,

    pub metadata: ObjectMetadata,

    /// Helm values — defaults to an empty object when omitted
    #[serde(default = "default_spec")]
    pub spec: serde_json::Value,
}

/// Return `true` when the manifest's `apiVersion` matches the Component API version.
///
/// The `kind` field is intentionally NOT checked here because it is dynamic —
/// it encodes a filesystem path rather than a fixed resource type.
pub fn is_nyl_component(manifest: &serde_json::Value) -> bool {
    manifest.get("apiVersion").and_then(|v| v.as_str()) == Some(API_VERSION_COMPONENTS)
}

/// Parsed result from parsing a component kind shortcut
#[derive(Debug, Clone, PartialEq)]
pub struct ComponentKindParsed {
    /// The base part (repository URL or local path)
    pub base: String,
    /// The chart name (after '#'), if present
    pub name: Option<String>,
    /// The version (after '@'), if present
    pub version: Option<String>,
}

/// Check if a string is a remote repository URL
///
/// Remote repositories are identified by these prefixes:
/// - `http://` or `https://` - Traditional Helm repositories or HTTP URLs
/// - `git+` - Git repositories
/// - `oci://` - OCI registries
fn is_remote_repository(s: &str) -> bool {
    s.starts_with("http://") || s.starts_with("https://") || s.starts_with("git+") || s.starts_with("oci://")
}

/// Parse a component kind string into its components
///
/// The format is: `<base>[#<name>][@<version>]`
/// - `base`: Repository URL (if remote) or local path/name
/// - `name`: Chart name (optional, after '#')
/// - `version`: Version or Git ref (optional, after '@')
///
/// **Parsing behavior:** The parser searches from right to left:
/// 1. First finds the rightmost '#' to identify the name boundary
/// 2. Then finds the rightmost '@' *after* that '#' (if any) for the version
///
/// This ensures Git SSH URLs like `git+git@github.com:org/repo#charts/app` are parsed correctly,
/// where the `@` in `git@github.com` is part of the base URL, not a version separator.
///
/// - Valid: `http://repo.com#chart@v1.0` → base=`http://repo.com`, name=`chart`, version=`v1.0`
/// - Valid: `git+git@github.com:user/repo#charts/app@main` → base=`git+git@github.com:user/repo`, name=`charts/app`, version=`main`
/// - Valid: `git+git@github.com:user/repo#charts/app` → base=`git+git@github.com:user/repo`, name=`charts/app`, version=None
///
/// Examples:
/// - `http://my-repo.org#my-chart@1.0.0` → repository URL with name and version
/// - `https://charts.example.com#nginx` → repository URL with name only
/// - `oci://ghcr.io/owner/chart@v1.0.0` → OCI registry with version only
/// - `my-chart` → local path/name
/// - `path/to/chart` → local path
pub fn parse_component_kind(kind: &str) -> ComponentKindParsed {
    // First, find the '#' for name (rightmost '#')
    // This helps distinguish between '@' in the base (like git@github.com) and '@' for version
    if let Some(hash_pos) = kind.rfind('#') {
        let base = kind[..hash_pos].to_string();
        let after_hash = &kind[hash_pos + 1..];

        // Now look for '@' in the part after '#' for version
        if let Some(at_pos) = after_hash.rfind('@') {
            let name = after_hash[..at_pos].to_string();
            let version = after_hash[at_pos + 1..].to_string();
            ComponentKindParsed {
                base,
                name: Some(name),
                version: Some(version),
            }
        } else {
            // No '@' after '#', so no version
            ComponentKindParsed {
                base,
                name: Some(after_hash.to_string()),
                version: None,
            }
        }
    } else {
        // No '#', so check for '@' for version only (no name)
        if let Some(at_pos) = kind.rfind('@') {
            ComponentKindParsed {
                base: kind[..at_pos].to_string(),
                name: None,
                version: Some(kind[at_pos + 1..].to_string()),
            }
        } else {
            // No '#' and no '@', entire string is the base
            ComponentKindParsed {
                base: kind.to_string(),
                name: None,
                version: None,
            }
        }
    }
}

/// Check if a component kind uses the shortcut format for remote Helm charts
///
/// Returns `true` if the kind appears to be a remote repository URL rather than
/// a local component path.
pub fn is_remote_helm_chart_shortcut(kind: &str) -> bool {
    // Extract the base part (before '#' and '@')
    let parsed = parse_component_kind(kind);
    is_remote_repository(&parsed.base)
}

/// Convert a parsed component kind to a ChartRef
///
/// This maps the shortcut format to the HelmChart's ChartRef structure:
/// - For remote repositories: Sets repository, name, and version fields
/// - For local paths: Sets only the name field (as local path)
pub fn component_kind_to_chart_ref(parsed: &ComponentKindParsed) -> ChartRef {
    if is_remote_repository(&parsed.base) {
        // Remote repository: use repository field
        ChartRef {
            repository: Some(parsed.base.clone()),
            name: parsed.name.clone(),
            version: parsed.version.clone(),
        }
    } else {
        // Local path: use name field only
        ChartRef {
            repository: None,
            name: Some(parsed.base.clone()),
            version: None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    // --- detection --------------------------------------------------------

    #[test]
    fn test_is_nyl_component_positive() {
        let manifest = json!({
            "apiVersion": "components.nyl.niklasrosenstein.github.com/v1",
            "kind": "example/v1/Nginx",
            "metadata": { "name": "my-nginx", "namespace": "default" },
            "spec": { "replicas": 3 }
        });
        assert!(is_nyl_component(&manifest));
    }

    #[test]
    fn test_is_nyl_component_negative_wrong_api_version() {
        let manifest = json!({
            "apiVersion": "nyl.niklasrosenstein.github.com/v1",
            "kind": "example/v1/Nginx",
            "metadata": { "name": "my-nginx" }
        });
        assert!(!is_nyl_component(&manifest));
    }

    #[test]
    fn test_is_nyl_component_negative_missing_api_version() {
        let manifest = json!({
            "kind": "example/v1/Nginx",
            "metadata": { "name": "my-nginx" }
        });
        assert!(!is_nyl_component(&manifest));
    }

    // --- deserialization / round-trip --------------------------------------

    #[test]
    fn test_deserialize_full() {
        let manifest = json!({
            "apiVersion": "components.nyl.niklasrosenstein.github.com/v1",
            "kind": "example/v1/Nginx",
            "metadata": { "name": "my-nginx", "namespace": "default" },
            "spec": { "replicas": 3, "image": "nginx:latest" }
        });

        let component: NylComponent = serde_json::from_value(manifest).unwrap();
        assert_eq!(component.api_version, "components.nyl.niklasrosenstein.github.com/v1");
        assert_eq!(component.kind, "example/v1/Nginx");
        assert_eq!(component.metadata.name, "my-nginx");
        assert_eq!(component.metadata.namespace, Some("default".to_string()));
        assert_eq!(component.spec["replicas"], 3);
        assert_eq!(component.spec["image"], "nginx:latest");
    }

    #[test]
    fn test_round_trip() {
        let manifest = json!({
            "apiVersion": "components.nyl.niklasrosenstein.github.com/v1",
            "kind": "libs/v2/Redis",
            "metadata": { "name": "my-redis", "namespace": "infra" },
            "spec": { "port": 6379 }
        });

        let component: NylComponent = serde_json::from_value(manifest).unwrap();
        let serialized = serde_json::to_value(&component).unwrap();
        let round_tripped: NylComponent = serde_json::from_value(serialized).unwrap();

        assert_eq!(round_tripped.kind, "libs/v2/Redis");
        assert_eq!(round_tripped.metadata.name, "my-redis");
        assert_eq!(round_tripped.spec["port"], 6379);
    }

    // --- spec defaulting --------------------------------------------------

    #[test]
    fn test_spec_defaults_to_empty_object_when_omitted() {
        let manifest = json!({
            "apiVersion": "components.nyl.niklasrosenstein.github.com/v1",
            "kind": "example/v1/Nginx",
            "metadata": { "name": "no-spec" }
        });

        let component: NylComponent = serde_json::from_value(manifest).unwrap();
        assert!(component.spec.is_object());
        assert!(component.spec.as_object().unwrap().is_empty());
    }

    // --- shortcut parsing tests -------------------------------------------

    #[test]
    fn test_is_remote_repository() {
        assert!(is_remote_repository("http://example.com"));
        assert!(is_remote_repository("https://example.com"));
        assert!(is_remote_repository("git+https://github.com/user/repo"));
        assert!(is_remote_repository("oci://ghcr.io/owner/chart"));

        assert!(!is_remote_repository("my-chart"));
        assert!(!is_remote_repository("path/to/chart"));
        assert!(!is_remote_repository("./charts/app"));
    }

    #[test]
    fn test_parse_component_kind_full_format() {
        let parsed = parse_component_kind("http://my-repo.org#my-chart@1.0.0");
        assert_eq!(parsed.base, "http://my-repo.org");
        assert_eq!(parsed.name, Some("my-chart".to_string()));
        assert_eq!(parsed.version, Some("1.0.0".to_string()));
    }

    #[test]
    fn test_parse_component_kind_no_version() {
        let parsed = parse_component_kind("https://charts.example.com#nginx");
        assert_eq!(parsed.base, "https://charts.example.com");
        assert_eq!(parsed.name, Some("nginx".to_string()));
        assert_eq!(parsed.version, None);
    }

    #[test]
    fn test_parse_component_kind_no_name() {
        let parsed = parse_component_kind("oci://ghcr.io/owner/chart@v1.0.0");
        assert_eq!(parsed.base, "oci://ghcr.io/owner/chart");
        assert_eq!(parsed.name, None);
        assert_eq!(parsed.version, Some("v1.0.0".to_string()));
    }

    #[test]
    fn test_parse_component_kind_only_base() {
        let parsed = parse_component_kind("http://my-chart-repo.org");
        assert_eq!(parsed.base, "http://my-chart-repo.org");
        assert_eq!(parsed.name, None);
        assert_eq!(parsed.version, None);
    }

    #[test]
    fn test_parse_component_kind_local_path() {
        let parsed = parse_component_kind("my-chart");
        assert_eq!(parsed.base, "my-chart");
        assert_eq!(parsed.name, None);
        assert_eq!(parsed.version, None);
    }

    #[test]
    fn test_parse_component_kind_local_path_with_slashes() {
        let parsed = parse_component_kind("path/to/my-chart");
        assert_eq!(parsed.base, "path/to/my-chart");
        assert_eq!(parsed.name, None);
        assert_eq!(parsed.version, None);
    }

    #[test]
    fn test_parse_component_kind_git_format() {
        let parsed = parse_component_kind("git+https://github.com/user/repo#charts/app@main");
        assert_eq!(parsed.base, "git+https://github.com/user/repo");
        assert_eq!(parsed.name, Some("charts/app".to_string()));
        assert_eq!(parsed.version, Some("main".to_string()));
    }

    #[test]
    fn test_parse_component_kind_git_ssh_with_at() {
        // Git SSH URLs have @ in the base (git@github.com), should not be confused with version
        let parsed = parse_component_kind("git+git@github.com:user/repo#charts/app");
        assert_eq!(parsed.base, "git+git@github.com:user/repo");
        assert_eq!(parsed.name, Some("charts/app".to_string()));
        assert_eq!(parsed.version, None);
    }

    #[test]
    fn test_parse_component_kind_git_ssh_with_version() {
        let parsed = parse_component_kind("git+git@github.com:user/repo#charts/app@v1.0");
        assert_eq!(parsed.base, "git+git@github.com:user/repo");
        assert_eq!(parsed.name, Some("charts/app".to_string()));
        assert_eq!(parsed.version, Some("v1.0".to_string()));
    }

    #[test]
    fn test_is_remote_helm_chart_shortcut_remote() {
        assert!(is_remote_helm_chart_shortcut("http://my-repo.org#chart@1.0.0"));
        assert!(is_remote_helm_chart_shortcut("https://charts.example.com#nginx"));
        assert!(is_remote_helm_chart_shortcut("oci://ghcr.io/chart@v1.0.0"));
        assert!(is_remote_helm_chart_shortcut("git+https://github.com/user/repo"));
    }

    #[test]
    fn test_is_remote_helm_chart_shortcut_local() {
        assert!(!is_remote_helm_chart_shortcut("my-chart"));
        assert!(!is_remote_helm_chart_shortcut("path/to/chart"));
        assert!(!is_remote_helm_chart_shortcut("example/v1/Nginx"));
    }

    #[test]
    fn test_component_kind_to_chart_ref_remote_full() {
        let parsed = parse_component_kind("http://my-repo.org#my-chart@1.0.0");
        let chart_ref = component_kind_to_chart_ref(&parsed);

        assert_eq!(chart_ref.repository, Some("http://my-repo.org".to_string()));
        assert_eq!(chart_ref.name, Some("my-chart".to_string()));
        assert_eq!(chart_ref.version, Some("1.0.0".to_string()));
    }

    #[test]
    fn test_component_kind_to_chart_ref_remote_no_version() {
        let parsed = parse_component_kind("https://charts.example.com#nginx");
        let chart_ref = component_kind_to_chart_ref(&parsed);

        assert_eq!(chart_ref.repository, Some("https://charts.example.com".to_string()));
        assert_eq!(chart_ref.name, Some("nginx".to_string()));
        assert_eq!(chart_ref.version, None);
    }

    #[test]
    fn test_component_kind_to_chart_ref_local() {
        let parsed = parse_component_kind("my-chart");
        let chart_ref = component_kind_to_chart_ref(&parsed);

        assert_eq!(chart_ref.repository, None);
        assert_eq!(chart_ref.name, Some("my-chart".to_string()));
        assert_eq!(chart_ref.version, None);
    }

    #[test]
    fn test_component_kind_to_chart_ref_local_path() {
        let parsed = parse_component_kind("path/to/my-chart");
        let chart_ref = component_kind_to_chart_ref(&parsed);

        assert_eq!(chart_ref.repository, None);
        assert_eq!(chart_ref.name, Some("path/to/my-chart".to_string()));
        assert_eq!(chart_ref.version, None);
    }

    #[test]
    fn test_nyl_component_rejects_unknown_fields() {
        let yaml = r"
apiVersion: components.nyl.niklasrosenstein.github.com/v1
kind: MyComponent
metadata:
  name: test
spec:
  key: value
unknownField: should-fail
";
        let result: std::result::Result<NylComponent, _> = serde_norway::from_str(yaml);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("unknown field"));
    }
}