kopi 0.2.3

Kopi is a JDK version management tool
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
// Copyright 2025 dentsusoken
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Integration tests for JDK bundle structure handling on macOS.
//! Tests the complete workflow from installation through execution.

use kopi::archive::{JdkStructureType, detect_jdk_root};
use kopi::config::KopiConfig;
use kopi::paths::install;
use kopi::storage::{InstalledJdk, JdkLister};
use kopi::version::Version;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::str::FromStr;
use tempfile::TempDir;

mod common;
use common::TestHomeGuard;

fn run_kopi_with_home(home: &TestHomeGuard, args: &[&str]) -> (String, String, bool) {
    let mut cmd = Command::new(env!("CARGO_BIN_EXE_kopi"));
    cmd.args(args);
    cmd.env("KOPI_HOME", home.kopi_home());
    cmd.env("HOME", home.path());
    cmd.current_dir(home.path()); // Set working directory to test home

    let output = cmd.output().expect("Failed to execute kopi");

    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();

    (stdout, stderr, output.status.success())
}

fn create_mock_jdk_structure(base_path: &Path, structure_type: &str) -> PathBuf {
    let java_binary = if cfg!(windows) { "java.exe" } else { "java" };
    let javac_binary = if cfg!(windows) { "javac.exe" } else { "javac" };

    match structure_type {
        "direct" => {
            // Direct structure: bin/ at root
            let bin_dir = base_path.join("bin");
            fs::create_dir_all(&bin_dir).unwrap();
            fs::write(bin_dir.join(java_binary), "#!/bin/sh\necho \"Mock Java\"").unwrap();
            fs::write(bin_dir.join(javac_binary), "#!/bin/sh\necho \"Mock Javac\"").unwrap();
            base_path.to_path_buf()
        }
        "bundle" => {
            // Bundle structure: Contents/Home/bin/
            let home_dir = install::bundle_java_home(base_path);
            let bin_dir = home_dir.join("bin");
            fs::create_dir_all(&bin_dir).unwrap();
            fs::write(bin_dir.join(java_binary), "#!/bin/sh\necho \"Mock Java\"").unwrap();
            fs::write(bin_dir.join(javac_binary), "#!/bin/sh\necho \"Mock Javac\"").unwrap();
            base_path.to_path_buf()
        }
        "hybrid" => {
            // Hybrid structure: symlinks at root pointing to bundle
            // Create a Zulu-style nested bundle structure
            let jdk_dir = base_path.join("zulu-21.jdk");
            let home_dir = install::bundle_java_home(&jdk_dir);
            let bin_dir = home_dir.join("bin");
            fs::create_dir_all(&bin_dir).unwrap();
            fs::write(bin_dir.join(java_binary), "#!/bin/sh\necho \"Mock Java\"").unwrap();
            fs::write(bin_dir.join(javac_binary), "#!/bin/sh\necho \"Mock Javac\"").unwrap();

            // Create symlinks at root using relative paths like Zulu does
            #[cfg(unix)]
            {
                use std::os::unix::fs::symlink;
                symlink("zulu-21.jdk/Contents/Home/bin", base_path.join("bin")).unwrap();
            }
            #[cfg(windows)]
            {
                use std::os::windows::fs::symlink_dir;
                symlink_dir(&bin_dir, base_path.join("bin")).unwrap();
            }

            base_path.to_path_buf()
        }
        _ => panic!("Unknown structure type: {structure_type}"),
    }
}

#[test]
fn test_structure_detection_integration() {
    let temp_dir = TempDir::new().unwrap();

    // Test direct structure
    let direct_jdk = temp_dir.path().join("direct-jdk");
    create_mock_jdk_structure(&direct_jdk, "direct");
    let info = detect_jdk_root(&direct_jdk).unwrap();
    assert_eq!(info.jdk_root, direct_jdk);
    assert_eq!(info.java_home_suffix, "");
    assert!(matches!(info.structure_type, JdkStructureType::Direct));

    // Test bundle structure on macOS
    #[cfg(target_os = "macos")]
    {
        let bundle_jdk = temp_dir.path().join("bundle-jdk");
        create_mock_jdk_structure(&bundle_jdk, "bundle");
        let info = detect_jdk_root(&bundle_jdk).unwrap();
        assert_eq!(info.jdk_root, install::bundle_java_home(&bundle_jdk));
        assert_eq!(info.java_home_suffix, "Contents/Home");
        assert!(matches!(info.structure_type, JdkStructureType::Bundle));

        // Test hybrid structure
        let hybrid_jdk = temp_dir.path().join("hybrid-jdk");
        create_mock_jdk_structure(&hybrid_jdk, "hybrid");
        let info = detect_jdk_root(&hybrid_jdk).unwrap();
        // For hybrid structures, the root is where the symlinks are
        assert_eq!(info.jdk_root, hybrid_jdk);
        // Hybrid structures now properly detect the java_home_suffix
        assert_eq!(info.java_home_suffix, "zulu-21.jdk/Contents/Home");
        assert!(matches!(info.structure_type, JdkStructureType::Hybrid));
    }
}

#[test]
fn test_installed_jdk_path_resolution() {
    let guard = TestHomeGuard::new();
    let test_home = guard.setup_kopi_structure();
    let config = KopiConfig::new(test_home.kopi_home()).unwrap();
    let jdks_dir = config.jdks_dir().unwrap();

    // Create mock JDK installations
    let direct_jdk_path = jdks_dir.join("liberica-21");
    create_mock_jdk_structure(&direct_jdk_path, "direct");

    #[cfg(target_os = "macos")]
    let bundle_jdk_path = jdks_dir.join("temurin-21");
    #[cfg(target_os = "macos")]
    create_mock_jdk_structure(&bundle_jdk_path, "bundle");

    // Test InstalledJdk path resolution
    let direct_jdk = InstalledJdk::new(
        "liberica".to_string(),
        Version::from_str("21.0.0").unwrap(),
        direct_jdk_path.clone(),
        false,
    );

    // Test resolve_java_home
    let java_home = direct_jdk.resolve_java_home();
    assert_eq!(java_home, direct_jdk_path);

    // Test resolve_bin_path
    let bin_path = direct_jdk.resolve_bin_path().unwrap();
    assert_eq!(bin_path, direct_jdk_path.join("bin"));
    assert!(bin_path.exists());

    #[cfg(target_os = "macos")]
    {
        let bundle_jdk = InstalledJdk::new(
            "temurin".to_string(),
            Version::from_str("21.0.0").unwrap(),
            bundle_jdk_path.clone(),
            false,
        );

        // Test resolve_java_home for bundle structure
        let java_home = bundle_jdk.resolve_java_home();
        assert_eq!(java_home, install::bundle_java_home(&bundle_jdk_path));

        // Test resolve_bin_path for bundle structure
        let bin_path = bundle_jdk.resolve_bin_path().unwrap();
        assert_eq!(
            bin_path,
            install::bin_directory(&install::bundle_java_home(&bundle_jdk_path))
        );
        assert!(bin_path.exists());
    }
}

#[test]
fn test_version_switching_workflow() {
    let guard = TestHomeGuard::new();
    let test_home = guard.setup_kopi_structure();
    let config = KopiConfig::new(test_home.kopi_home()).unwrap();
    let jdks_dir = config.jdks_dir().unwrap();

    // Create two mock JDKs with different structures
    let liberica_path = jdks_dir.join("liberica-17");
    create_mock_jdk_structure(&liberica_path, "direct");

    #[cfg(target_os = "macos")]
    let temurin_path = jdks_dir.join("temurin-21");
    #[cfg(target_os = "macos")]
    create_mock_jdk_structure(&temurin_path, "bundle");

    // Create .kopi-version files for testing
    fs::write(test_home.path().join(".kopi-version"), "liberica@17").unwrap();

    // Test listing installed JDKs
    let jdks = JdkLister::list_installed_jdks(&jdks_dir).unwrap();
    assert!(
        jdks.iter()
            .any(|j| j.distribution == "liberica" && j.version.to_string() == "17")
    );

    #[cfg(target_os = "macos")]
    {
        assert!(
            jdks.iter()
                .any(|j| j.distribution == "temurin" && j.version.to_string() == "21")
        );

        // Test switching to bundle structure JDK
        fs::write(test_home.path().join(".kopi-version"), "temurin@21").unwrap();

        // Verify the correct JDK would be selected
        let selected_jdk = jdks
            .iter()
            .find(|j| j.distribution == "temurin" && j.version.to_string() == "21")
            .unwrap();

        // Verify path resolution works correctly
        let java_home = selected_jdk.resolve_java_home();
        assert!(java_home.join("bin").join("java").exists());
    }
}

#[test]
fn test_env_command_with_different_structures() {
    let guard = TestHomeGuard::new();
    let test_home = guard.setup_kopi_structure();
    let config = KopiConfig::new(test_home.kopi_home()).unwrap();
    let jdks_dir = config.jdks_dir().unwrap();

    // Create a direct structure JDK
    let liberica_path = jdks_dir.join("liberica-17");
    create_mock_jdk_structure(&liberica_path, "direct");
    fs::write(test_home.path().join(".kopi-version"), "liberica@17").unwrap();

    // Run env command
    let (stdout, stderr, success) = run_kopi_with_home(test_home, &["env"]);
    if !success {
        eprintln!("env command failed with stderr: {stderr}");
        eprintln!("stdout: {stdout}");
    }
    assert!(success);
    // Check that JAVA_HOME is set and contains the liberica path
    // The format varies by shell (Bash: JAVA_HOME="path", PowerShell: $env:JAVA_HOME = "path", etc.)
    assert!(
        stdout.contains("JAVA_HOME"),
        "Output should contain JAVA_HOME: {stdout}"
    );
    // On Windows, the backslashes in paths might be escaped in the output
    let liberica_path_str = liberica_path.to_string_lossy();
    let liberica_path_escaped = liberica_path_str.replace('\\', "\\\\");
    assert!(
        stdout.contains(liberica_path_str.as_ref()) || stdout.contains(&liberica_path_escaped),
        "Output should contain liberica path {} (or escaped version): {stdout}",
        liberica_path.display()
    );

    #[cfg(target_os = "macos")]
    {
        // Create a bundle structure JDK
        let temurin_path = jdks_dir.join("temurin-21");
        create_mock_jdk_structure(&temurin_path, "bundle");
        fs::write(test_home.path().join(".kopi-version"), "temurin@21").unwrap();

        // Run env command with bundle structure
        let (stdout, _, success) = run_kopi_with_home(test_home, &["env"]);
        assert!(success);
        let expected_java_home = install::bundle_java_home(&temurin_path);
        // Check that JAVA_HOME is set and contains the expected path
        // The format varies by shell
        assert!(
            stdout.contains("JAVA_HOME"),
            "Output should contain JAVA_HOME: {stdout}"
        );
        assert!(
            stdout.contains(&expected_java_home.to_string_lossy().to_string()),
            "Output should contain temurin path {}: {stdout}",
            expected_java_home.display()
        );
    }
}

#[test]
#[cfg(target_os = "macos")]
fn test_shim_execution_performance() {
    use std::time::Instant;

    let guard = TestHomeGuard::new();
    let test_home = guard.setup_kopi_structure();
    let config = KopiConfig::new(test_home.kopi_home()).unwrap();
    let jdks_dir = config.jdks_dir().unwrap();
    let shims_dir = config.bin_dir().unwrap();

    // Create a bundle structure JDK
    let temurin_path = jdks_dir.join("temurin-21");
    create_mock_jdk_structure(&temurin_path, "bundle");

    // Make the mock java executable
    let java_path = install::bin_directory(&install::bundle_java_home(&temurin_path)).join("java");
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = fs::metadata(&java_path).unwrap().permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&java_path, perms).unwrap();
    }

    // Copy the actual shim binary to the test environment
    let shim_src = env!("CARGO_BIN_EXE_kopi-shim");
    let shim_dst = shims_dir.join("java");
    fs::copy(shim_src, &shim_dst).unwrap();

    // Make shim executable
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = fs::metadata(&shim_dst).unwrap().permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&shim_dst, perms).unwrap();
    }

    // Set up version file
    fs::write(test_home.path().join(".kopi-version"), "temurin@21").unwrap();

    // Measure shim execution time
    let mut total_time = std::time::Duration::ZERO;
    let iterations = 5;

    for _ in 0..iterations {
        let start = Instant::now();

        let mut cmd = Command::new(&shim_dst);
        cmd.env("KOPI_HOME", test_home.kopi_home());
        cmd.env("HOME", test_home.path());
        cmd.arg("--version");

        let output = cmd.output().expect("Failed to execute shim");
        let elapsed = start.elapsed();

        if output.status.success() {
            total_time += elapsed;
        }
    }

    let avg_time = total_time / iterations as u32;
    println!("Average shim execution time: {avg_time:?}");

    // Assert that average execution time is less than 50ms
    assert!(
        avg_time.as_millis() < 50,
        "Shim execution time {avg_time:?} exceeds 50ms threshold"
    );
}

#[test]
fn test_error_handling_invalid_structure() {
    let temp_dir = TempDir::new().unwrap();
    let invalid_jdk = temp_dir.path().join("invalid-jdk");
    fs::create_dir_all(&invalid_jdk).unwrap();

    // Create an invalid structure (no bin directory)
    fs::write(invalid_jdk.join("README.txt"), "This is not a JDK").unwrap();

    // Test that detection fails appropriately
    let result = detect_jdk_root(&invalid_jdk);
    assert!(result.is_err());
}

#[test]
fn test_concurrent_access() {
    use std::sync::Arc;
    use std::thread;

    let guard = TestHomeGuard::new();
    let test_home_guard = guard.setup_kopi_structure();
    let test_home = Arc::new(test_home_guard.path().to_path_buf());
    let kopi_home = test_home.join(".kopi");
    let config = Arc::new(KopiConfig::new(kopi_home).unwrap());
    let jdks_dir = config.jdks_dir().unwrap();

    // Create multiple JDKs
    for i in 0..3 {
        let jdk_path = jdks_dir.join(format!("test-jdk-{i}"));
        create_mock_jdk_structure(&jdk_path, "direct");
    }

    // Spawn multiple threads to access JDKs concurrently
    let mut handles = vec![];

    for i in 0..5 {
        let config_clone = Arc::clone(&config);
        let handle = thread::spawn(move || {
            // Each thread lists JDKs multiple times
            for _ in 0..10 {
                let jdks_dir = config_clone.jdks_dir().unwrap();
                let jdks = JdkLister::list_installed_jdks(&jdks_dir).unwrap();
                assert!(jdks.len() >= 3);

                // Resolve paths for each JDK
                for jdk in &jdks {
                    let _java_home = jdk.resolve_java_home();
                    let _bin_path = jdk.resolve_bin_path();
                }
            }
            println!("Thread {i} completed");
        });
        handles.push(handle);
    }

    // Wait for all threads to complete
    for handle in handles {
        handle.join().unwrap();
    }
}