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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
/// Integration tests for Git repository management
///
/// These tests verify the end-to-end flow of Git operations including:
/// - Cloning bare repositories
/// - Creating worktrees
/// - Resolving refs
/// - HelmChart Git integration
/// - ApplicationGenerator Git integration
use nyl::git::GitManager;
use std::env;
use std::fs;
use std::path::Path;
use std::process::Command;
use tempfile::TempDir;

/// Set up test environment to disable SSH and use only local operations
fn setup_test_env() {
    // Disable credential helpers and SSH prompts
    env::set_var("GIT_TERMINAL_PROMPT", "0");
    env::set_var("GIT_SSH_COMMAND", "echo 'SSH disabled in tests' && exit 1");
}

/// Convert a path to a file:// URL that works on both Unix and Windows
fn path_to_file_url(path: &Path) -> String {
    #[cfg(windows)]
    {
        // On Windows, convert backslashes to forward slashes and use three slashes
        // e.g., C:\Users\foo -> file:///C:/Users/foo
        let path_str = path.display().to_string().replace('\\', "/");
        format!("file:///{}", path_str)
    }
    #[cfg(not(windows))]
    {
        // On Unix, use two slashes (file:// + absolute path starting with /)
        format!("file://{}", path.display())
    }
}

/// Helper to create a test Git repository with commits
fn create_test_git_repo(repo_dir: &Path) {
    // Initialize repository with explicit branch name
    Command::new("git")
        .args(["init", "-b", "main"])
        .current_dir(repo_dir)
        .output()
        .expect("Failed to init git repo");

    // Configure user
    Command::new("git")
        .args(["config", "user.name", "Test User"])
        .current_dir(repo_dir)
        .output()
        .expect("Failed to set git user");

    Command::new("git")
        .args(["config", "user.email", "test@example.com"])
        .current_dir(repo_dir)
        .output()
        .expect("Failed to set git email");

    // Disable credential helpers and SSH for this repo
    Command::new("git")
        .args(["config", "credential.helper", ""])
        .current_dir(repo_dir)
        .output()
        .expect("Failed to disable credential helper");

    // Disable commit signing (prevents SSH agent prompts)
    Command::new("git")
        .args(["config", "commit.gpgsign", "false"])
        .current_dir(repo_dir)
        .output()
        .expect("Failed to disable commit signing");

    Command::new("git")
        .args(["config", "tag.gpgsign", "false"])
        .current_dir(repo_dir)
        .output()
        .expect("Failed to disable tag signing");

    // Create a test file
    fs::write(repo_dir.join("test.txt"), "Hello, World!").expect("Failed to create test file");

    // Create a subdirectory with a file
    fs::create_dir_all(repo_dir.join("subdir")).expect("Failed to create subdir");
    fs::write(repo_dir.join("subdir/chart.yaml"), "name: test-chart").expect("Failed to create chart.yaml");

    // Add and commit
    Command::new("git")
        .args(["add", "."])
        .current_dir(repo_dir)
        .output()
        .expect("Failed to git add");

    Command::new("git")
        .args(["commit", "-m", "Initial commit"])
        .current_dir(repo_dir)
        .output()
        .expect("Failed to git commit");

    // Create a branch
    Command::new("git")
        .args(["branch", "test-branch"])
        .current_dir(repo_dir)
        .output()
        .expect("Failed to create branch");

    // Create a tag
    Command::new("git")
        .args(["tag", "v1.0.0"])
        .current_dir(repo_dir)
        .output()
        .expect("Failed to create tag");

    // Create an annotated tag
    Command::new("git")
        .args(["tag", "-a", "v1.1.0", "-m", "Annotated release v1.1.0"])
        .current_dir(repo_dir)
        .output()
        .expect("Failed to create annotated tag");
}

#[test]
fn test_git_manager_resolve_ref_main_branch() {
    setup_test_env();

    // Create a test repository
    let temp_repo = TempDir::new().unwrap();
    create_test_git_repo(temp_repo.path());

    // Set up cache directory (use explicit path instead of env var to avoid race conditions)
    let cache_dir = TempDir::new().unwrap();

    // Clone and resolve main branch
    let mut manager = GitManager::with_cache_dir(cache_dir.path());
    let result = manager
        .resolve_ref(&path_to_file_url(temp_repo.path()), Some("main"), None)
        .unwrap();

    // Verify the worktree exists
    assert!(result.exists());
    assert!(result.join("test.txt").exists());

    // Verify content
    let content = fs::read_to_string(result.join("test.txt")).unwrap();
    assert_eq!(content, "Hello, World!");
}

#[test]
fn test_git_manager_resolve_ref_with_subpath() {
    setup_test_env();

    let temp_repo = TempDir::new().unwrap();
    create_test_git_repo(temp_repo.path());

    let cache_dir = TempDir::new().unwrap();

    let mut manager = GitManager::with_cache_dir(cache_dir.path());
    let result = manager
        .resolve_ref(&path_to_file_url(temp_repo.path()), Some("main"), Some("subdir"))
        .unwrap();

    // Verify we're in the subdirectory
    assert!(result.exists());
    assert!(result.join("chart.yaml").exists());

    let content = fs::read_to_string(result.join("chart.yaml")).unwrap();
    assert_eq!(content, "name: test-chart");
}

#[test]
fn test_git_manager_resolve_ref_branch() {
    setup_test_env();

    let temp_repo = TempDir::new().unwrap();
    create_test_git_repo(temp_repo.path());

    let cache_dir = TempDir::new().unwrap();

    let mut manager = GitManager::with_cache_dir(cache_dir.path());
    let result = manager
        .resolve_ref(&path_to_file_url(temp_repo.path()), Some("test-branch"), None)
        .unwrap();

    assert!(result.exists());
    assert!(result.join("test.txt").exists());
}

#[test]
fn test_git_manager_resolve_ref_tag() {
    setup_test_env();

    let temp_repo = TempDir::new().unwrap();
    create_test_git_repo(temp_repo.path());

    let cache_dir = TempDir::new().unwrap();

    let mut manager = GitManager::with_cache_dir(cache_dir.path());
    let result = manager
        .resolve_ref(&path_to_file_url(temp_repo.path()), Some("v1.0.0"), None)
        .unwrap();

    assert!(result.exists());
    assert!(result.join("test.txt").exists());
}

#[test]
fn test_git_manager_multiple_refs_same_repo() {
    setup_test_env();

    let temp_repo = TempDir::new().unwrap();
    create_test_git_repo(temp_repo.path());

    let cache_dir = TempDir::new().unwrap();

    let mut manager = GitManager::with_cache_dir(cache_dir.path());

    // Resolve main branch
    let main_result = manager
        .resolve_ref(&path_to_file_url(temp_repo.path()), Some("main"), None)
        .unwrap();

    // Resolve test-branch
    let branch_result = manager
        .resolve_ref(&path_to_file_url(temp_repo.path()), Some("test-branch"), None)
        .unwrap();

    // Both should exist and be different paths (different worktrees)
    assert!(main_result.exists());
    assert!(branch_result.exists());
    assert_ne!(main_result, branch_result);

    // Both should have the test file
    assert!(main_result.join("test.txt").exists());
    assert!(branch_result.join("test.txt").exists());
}

#[test]
fn test_git_manager_cache_reuse() {
    setup_test_env();

    let temp_repo = TempDir::new().unwrap();
    create_test_git_repo(temp_repo.path());

    let cache_dir = TempDir::new().unwrap();
    let cache_path = cache_dir.path().to_path_buf();

    // First resolution
    {
        let mut manager = GitManager::with_cache_dir(&cache_path);
        let _result = manager
            .resolve_ref(&path_to_file_url(temp_repo.path()), Some("main"), None)
            .unwrap();
    }

    // Second resolution (should reuse cache)
    {
        let mut manager = GitManager::with_cache_dir(&cache_path);
        let result = manager
            .resolve_ref(&path_to_file_url(temp_repo.path()), Some("main"), None)
            .unwrap();

        assert!(result.exists());
        assert!(result.join("test.txt").exists());
    }
}

#[test]
fn test_git_manager_cache_reuse_annotated_tag() {
    setup_test_env();

    let temp_repo = TempDir::new().unwrap();
    create_test_git_repo(temp_repo.path());

    let cache_dir = TempDir::new().unwrap();
    let cache_path = cache_dir.path().to_path_buf();
    let repo_url = path_to_file_url(temp_repo.path());

    {
        let mut manager = GitManager::with_cache_dir(&cache_path);
        let result = manager.resolve_ref(&repo_url, Some("v1.1.0"), None).unwrap();
        assert!(result.exists());
        assert!(result.join("test.txt").exists());
    }

    {
        let mut manager = GitManager::with_cache_dir(&cache_path);
        let result = manager.resolve_ref(&repo_url, Some("v1.1.0"), None).unwrap();
        assert!(result.exists());
        assert!(result.join("test.txt").exists());
    }
}

#[test]
fn test_cache_directory_structure() {
    setup_test_env();

    let temp_repo = TempDir::new().unwrap();
    create_test_git_repo(temp_repo.path());

    let cache_dir = TempDir::new().unwrap();

    let mut manager = GitManager::with_cache_dir(cache_dir.path());
    let _result = manager
        .resolve_ref(&path_to_file_url(temp_repo.path()), Some("main"), None)
        .unwrap();

    // Verify cache structure
    let git_cache = cache_dir.path().join("git");
    assert!(git_cache.exists());

    let bare_dir = git_cache.join("bare");
    assert!(bare_dir.exists());

    let worktrees_dir = git_cache.join("worktrees");
    assert!(worktrees_dir.exists());

    // Should have one bare repo
    let bare_repos: Vec<_> = fs::read_dir(&bare_dir).unwrap().filter_map(|e| e.ok()).collect();
    assert_eq!(bare_repos.len(), 1);

    // Should have one worktree
    let worktrees: Vec<_> = fs::read_dir(&worktrees_dir).unwrap().filter_map(|e| e.ok()).collect();
    assert_eq!(worktrees.len(), 1);
}

/// Helper to create a test Git repository with a Helm chart
fn create_test_helm_chart_repo(repo_dir: &Path) {
    // Initialize repository with explicit branch name
    Command::new("git")
        .args(["init", "-b", "main"])
        .current_dir(repo_dir)
        .output()
        .expect("Failed to init git repo");

    // Configure user
    Command::new("git")
        .args(["config", "user.name", "Test User"])
        .current_dir(repo_dir)
        .output()
        .expect("Failed to set git user");

    Command::new("git")
        .args(["config", "user.email", "test@example.com"])
        .current_dir(repo_dir)
        .output()
        .expect("Failed to set git email");

    // Disable signing
    Command::new("git")
        .args(["config", "commit.gpgsign", "false"])
        .current_dir(repo_dir)
        .output()
        .expect("Failed to disable commit signing");

    // Create a Helm chart at the root
    fs::write(
        repo_dir.join("Chart.yaml"),
        "apiVersion: v2\nname: root-chart\nversion: 1.0.0\n",
    )
    .expect("Failed to create Chart.yaml");
    fs::write(repo_dir.join("values.yaml"), "key: value\n").expect("Failed to create values.yaml");

    // Create a Helm chart in a subdirectory
    fs::create_dir_all(repo_dir.join("charts/subchart")).expect("Failed to create charts/subchart");
    fs::write(
        repo_dir.join("charts/subchart/Chart.yaml"),
        "apiVersion: v2\nname: subchart\nversion: 2.0.0\n",
    )
    .expect("Failed to create subchart Chart.yaml");

    // Add and commit
    Command::new("git")
        .args(["add", "."])
        .current_dir(repo_dir)
        .output()
        .expect("Failed to git add");

    Command::new("git")
        .args(["commit", "-m", "Add Helm charts"])
        .current_dir(repo_dir)
        .output()
        .expect("Failed to git commit");

    // Create a tag
    Command::new("git")
        .args(["tag", "v1.0.0"])
        .current_dir(repo_dir)
        .output()
        .expect("Failed to create tag");
}

#[test]
fn test_git_chart_with_https_protocol_prefix() {
    setup_test_env();

    use nyl::helm::HelmChartResolver;
    use nyl::resources::ChartRef;

    let temp_repo = TempDir::new().unwrap();
    create_test_helm_chart_repo(temp_repo.path());

    let cache_dir = TempDir::new().unwrap();

    let resolver = HelmChartResolver::with_cache_dir(
        vec![],
        temp_repo.path().to_path_buf(),
        Some(cache_dir.path().to_path_buf()),
    );

    let chart_ref = ChartRef {
        repository: Some(format!("git+{}", path_to_file_url(temp_repo.path()))),
        version: Some("main".to_string()),
        name: None, // Chart at root
    };

    let resolved = resolver.resolve_chart(&chart_ref).unwrap();
    assert!(resolved.path.exists());
    assert!(resolved.path.join("Chart.yaml").exists());

    let content = fs::read_to_string(resolved.path.join("Chart.yaml")).unwrap();
    assert!(content.contains("name: root-chart"));
}

#[test]
fn test_git_chart_with_subpath() {
    setup_test_env();

    use nyl::helm::HelmChartResolver;
    use nyl::resources::ChartRef;

    let temp_repo = TempDir::new().unwrap();
    create_test_helm_chart_repo(temp_repo.path());

    let cache_dir = TempDir::new().unwrap();

    let resolver = HelmChartResolver::with_cache_dir(
        vec![],
        temp_repo.path().to_path_buf(),
        Some(cache_dir.path().to_path_buf()),
    );

    let chart_ref = ChartRef {
        repository: Some(format!("git+{}", path_to_file_url(temp_repo.path()))),
        version: Some("main".to_string()),
        name: Some("charts/subchart".to_string()), // Subpath in repo
    };

    let resolved = resolver.resolve_chart(&chart_ref).unwrap();
    assert!(resolved.path.exists());
    assert!(resolved.path.join("Chart.yaml").exists());

    let content = fs::read_to_string(resolved.path.join("Chart.yaml")).unwrap();
    assert!(content.contains("name: subchart"));
}

#[test]
fn test_git_chart_with_tag_version() {
    setup_test_env();

    use nyl::helm::HelmChartResolver;
    use nyl::resources::ChartRef;

    let temp_repo = TempDir::new().unwrap();
    create_test_helm_chart_repo(temp_repo.path());

    let cache_dir = TempDir::new().unwrap();

    let resolver = HelmChartResolver::with_cache_dir(
        vec![],
        temp_repo.path().to_path_buf(),
        Some(cache_dir.path().to_path_buf()),
    );

    let chart_ref = ChartRef {
        repository: Some(format!("git+{}", path_to_file_url(temp_repo.path()))),
        version: Some("v1.0.0".to_string()),
        name: None,
    };

    let resolved = resolver.resolve_chart(&chart_ref).unwrap();
    assert!(resolved.path.exists());
    assert!(resolved.path.join("Chart.yaml").exists());
}

/// Helper to create a test Git repository with a Helm chart that has dependencies
fn create_test_helm_chart_with_dependencies_repo(repo_dir: &Path) {
    // Initialize repository with explicit branch name
    Command::new("git")
        .args(["init", "-b", "main"])
        .current_dir(repo_dir)
        .output()
        .expect("Failed to init git repo");

    // Configure user
    Command::new("git")
        .args(["config", "user.name", "Test User"])
        .current_dir(repo_dir)
        .output()
        .expect("Failed to set git user");

    Command::new("git")
        .args(["config", "user.email", "test@example.com"])
        .current_dir(repo_dir)
        .output()
        .expect("Failed to set git email");

    // Disable signing
    Command::new("git")
        .args(["config", "commit.gpgsign", "false"])
        .current_dir(repo_dir)
        .output()
        .expect("Failed to disable commit signing");

    // Create a Helm chart with dependencies
    let chart_yaml_content = r#"apiVersion: v2
name: chart-with-deps
version: 1.0.0
dependencies:
  - name: common
    version: "^1.0"
    repository: "oci://registry-1.docker.io/bitnamicharts"
"#;
    fs::write(repo_dir.join("Chart.yaml"), chart_yaml_content).expect("Failed to create Chart.yaml");
    fs::write(repo_dir.join("values.yaml"), "key: value\n").expect("Failed to create values.yaml");

    // Create templates directory
    fs::create_dir_all(repo_dir.join("templates")).expect("Failed to create templates dir");
    fs::write(
        repo_dir.join("templates/configmap.yaml"),
        "apiVersion: v1\nkind: ConfigMap\nmetadata:\n  name: test\n",
    )
    .expect("Failed to create template");

    // Add and commit
    Command::new("git")
        .args(["add", "."])
        .current_dir(repo_dir)
        .output()
        .expect("Failed to git add");

    Command::new("git")
        .args(["commit", "-m", "Add Helm chart with dependencies"])
        .current_dir(repo_dir)
        .output()
        .expect("Failed to git commit");

    // Create a tag
    Command::new("git")
        .args(["tag", "v1.0.0"])
        .current_dir(repo_dir)
        .output()
        .expect("Failed to create tag");
}

#[test]
fn test_git_chart_with_dependencies() {
    setup_test_env();

    use nyl::helm::HelmChartResolver;
    use nyl::resources::ChartRef;

    let temp_repo = TempDir::new().unwrap();
    create_test_helm_chart_with_dependencies_repo(temp_repo.path());

    let cache_dir = TempDir::new().unwrap();

    let resolver = HelmChartResolver::with_cache_dir(
        vec![],
        temp_repo.path().to_path_buf(),
        Some(cache_dir.path().to_path_buf()),
    );

    let chart_ref = ChartRef {
        repository: Some(format!("git+{}", path_to_file_url(temp_repo.path()))),
        version: Some("main".to_string()),
        name: None,
    };

    // This should resolve the chart and run helm dependency build.
    // In restricted environments (e.g. sandboxed CI without DNS/network),
    // dependency download can fail; skip in that case.
    let resolved = match resolver.resolve_chart(&chart_ref) {
        Ok(resolved) => resolved,
        Err(err) => {
            let msg = err.to_string();
            if msg.contains("operation not permitted")
                || msg.contains("could not retrieve list of tags")
                || msg.contains("Temporary failure in name resolution")
            {
                eprintln!("Skipping network-dependent dependency build assertion: {msg}");
                return;
            }
            panic!("Unexpected resolve_chart error: {msg}");
        }
    };
    assert!(resolved.path.exists());
    assert!(resolved.path.join("Chart.yaml").exists());

    // Verify that dependencies were built (charts directory should exist)
    assert!(resolved.path.join("charts").exists());
    assert!(resolved.path.join("Chart.lock").exists());
}

#[test]
fn test_git_chart_without_dependencies() {
    setup_test_env();

    use nyl::helm::HelmChartResolver;
    use nyl::resources::ChartRef;

    let temp_repo = TempDir::new().unwrap();
    create_test_helm_chart_repo(temp_repo.path());

    let cache_dir = TempDir::new().unwrap();

    let resolver = HelmChartResolver::with_cache_dir(
        vec![],
        temp_repo.path().to_path_buf(),
        Some(cache_dir.path().to_path_buf()),
    );

    let chart_ref = ChartRef {
        repository: Some(format!("git+{}", path_to_file_url(temp_repo.path()))),
        version: Some("main".to_string()),
        name: None,
    };

    // This should resolve the chart without running helm dependency build
    let resolved = resolver.resolve_chart(&chart_ref).unwrap();
    assert!(resolved.path.exists());
    assert!(resolved.path.join("Chart.yaml").exists());

    // Verify that no charts directory exists (no dependencies)
    // Note: We can't assert !exists() because helm dependency build is idempotent
    // and won't fail if there are no dependencies
}

#[test]
fn test_git_manager_fetches_latest_version() {
    setup_test_env();

    // Create a test repository
    let temp_repo = TempDir::new().unwrap();
    create_test_git_repo(temp_repo.path());

    let cache_dir = TempDir::new().unwrap();

    // First resolution - this will cache the repository
    let mut manager = GitManager::with_cache_dir(cache_dir.path());
    let result1 = manager
        .resolve_ref(&path_to_file_url(temp_repo.path()), Some("main"), None)
        .unwrap();

    // Verify initial content
    let content1 = fs::read_to_string(result1.join("test.txt")).unwrap();
    assert_eq!(content1, "Hello, World!");

    // Now update the repository with a new commit on main branch
    fs::write(temp_repo.path().join("test.txt"), "Updated content!").expect("Failed to update file");
    let add_output = Command::new("git")
        .args(["add", "."])
        .current_dir(temp_repo.path())
        .output()
        .expect("Failed to launch git add");
    assert!(
        add_output.status.success(),
        "git add failed: {}",
        String::from_utf8_lossy(&add_output.stderr)
    );
    let commit_output = Command::new("git")
        .args(["commit", "-m", "Update content"])
        .current_dir(temp_repo.path())
        .output()
        .expect("Failed to launch git commit");
    assert!(
        commit_output.status.success(),
        "git commit failed: {}",
        String::from_utf8_lossy(&commit_output.stderr)
    );

    // Second resolution - should fetch and get the latest version
    // Reuse the same manager to simulate continuous usage
    let result2 = manager
        .resolve_ref(&path_to_file_url(temp_repo.path()), Some("main"), None)
        .unwrap();

    // Verify that we got the updated content
    let content2 = fs::read_to_string(result2.join("test.txt")).unwrap();
    assert_eq!(
        content2, "Updated content!",
        "Should fetch and checkout the latest version"
    );
}