kopi 0.0.6

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
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
// 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.

use crate::config::new_kopi_config;
use crate::error::{KopiError, Result};
use crate::models::distribution::Distribution;
use crate::storage::JdkRepository;
use crate::version::VersionRequest;
use std::env;
use std::ffi::OsString;
use std::io::IsTerminal;
use std::path::{Path, PathBuf};
use std::str::FromStr;

pub mod discovery;
pub mod installer;
pub mod security;
pub mod tools;
use crate::error::format_error_with_color;
use crate::installation::AutoInstaller;
use crate::version::resolver::VersionResolver;
use security::SecurityValidator;

/// Run the shim with the provided arguments
/// Returns the exit code
pub fn run(_args: Vec<String>) -> Result<i32> {
    // The shim implementation doesn't need the args vector since it reads from env::args_os()
    run_shim()?;
    Ok(0)
}

pub fn run_shim() -> Result<()> {
    let start = std::time::Instant::now();

    // Load configuration once
    let config = new_kopi_config()?;
    let security_validator = SecurityValidator::new(&config);

    // Get tool name from argv[0]
    let tool_name = get_tool_name()?;
    log::debug!("Shim invoked as: {tool_name}");

    // Validate tool name
    security_validator.validate_tool(&tool_name)?;

    // Resolve JDK version
    let resolver = VersionResolver::new(&config);
    let (version_request, version_source) = match resolver.resolve_version() {
        Ok((req, source)) => (req, source),
        Err(e @ KopiError::NoLocalVersion { .. }) => {
            eprintln!(
                "{}",
                format_error_with_color(&e, std::io::stderr().is_terminal())
            );
            std::process::exit(crate::error::get_exit_code(&e));
        }
        Err(e) => return Err(e),
    };
    log::debug!("Resolved version: {version_request:?} from {version_source:?}");

    // Validate version string
    security_validator.validate_version(&version_request.version_pattern)?;
    if let Some(dist) = &version_request.distribution {
        security_validator.validate_version(dist)?;
    }

    // Find JDK installation
    let repository = JdkRepository::new(&config);
    let jdk_path = match find_jdk_installation(&repository, &version_request) {
        Ok(path) => path,
        Err(mut err) => {
            if let KopiError::JdkNotInstalled {
                jdk_spec,
                auto_install_enabled: enabled,
                ..
            } = &mut err
            {
                // Check if auto-install is enabled
                let auto_installer = AutoInstaller::new(&config);
                let auto_install_enabled = auto_installer.should_auto_install();
                *enabled = auto_install_enabled;

                if auto_install_enabled {
                    // Check if we should prompt the user
                    let version_spec = if let Some(dist) = &version_request.distribution {
                        format!("{}@{}", dist, version_request.version_pattern)
                    } else {
                        version_request.version_pattern.clone()
                    };

                    let should_install = match auto_installer.prompt_user(&version_spec) {
                        Ok(approved) => approved,
                        Err(e) => {
                            eprintln!(
                                "{}",
                                format_error_with_color(&e, std::io::stderr().is_terminal())
                            );
                            false
                        }
                    };

                    if should_install {
                        // Try to install the JDK
                        match auto_installer.install_jdk(&version_request) {
                            Ok(()) => {
                                // Retry finding the JDK after installation
                                match find_jdk_installation(&repository, &version_request) {
                                    Ok(path) => path,
                                    Err(_) => {
                                        // Still not found after installation attempt
                                        let error = KopiError::JdkNotInstalled {
                                            jdk_spec: jdk_spec.clone(),
                                            version: Some(version_request.version_pattern.clone()),
                                            distribution: version_request.distribution.clone(),
                                            auto_install_enabled,
                                            auto_install_failed: Some(
                                                "Installation succeeded but JDK still not found"
                                                    .to_string(),
                                            ),
                                            user_declined: false,
                                            install_in_progress: false,
                                        };
                                        eprintln!(
                                            "{}",
                                            format_error_with_color(
                                                &error,
                                                std::io::stderr().is_terminal()
                                            )
                                        );
                                        std::process::exit(crate::error::get_exit_code(&error));
                                    }
                                }
                            }
                            Err(e) => {
                                // Check if it's specifically a kopi not found error
                                if let KopiError::KopiNotFound { .. } = &e {
                                    eprintln!(
                                        "{}",
                                        format_error_with_color(
                                            &e,
                                            std::io::stderr().is_terminal()
                                        )
                                    );
                                    std::process::exit(crate::error::get_exit_code(&e));
                                }

                                // Auto-install failed for other reasons
                                let error = KopiError::JdkNotInstalled {
                                    jdk_spec: jdk_spec.clone(),
                                    version: Some(version_request.version_pattern.clone()),
                                    distribution: version_request.distribution.clone(),
                                    auto_install_enabled,
                                    auto_install_failed: Some(e.to_string()),
                                    user_declined: false,
                                    install_in_progress: false,
                                };
                                eprintln!(
                                    "{}",
                                    format_error_with_color(
                                        &error,
                                        std::io::stderr().is_terminal()
                                    )
                                );
                                std::process::exit(crate::error::get_exit_code(&error));
                            }
                        }
                    } else {
                        // User declined installation
                        let error = KopiError::JdkNotInstalled {
                            jdk_spec: jdk_spec.clone(),
                            version: Some(version_request.version_pattern.clone()),
                            distribution: version_request.distribution.clone(),
                            auto_install_enabled,
                            auto_install_failed: None,
                            user_declined: true,
                            install_in_progress: false,
                        };
                        eprintln!(
                            "{}",
                            format_error_with_color(&error, std::io::stderr().is_terminal())
                        );
                        std::process::exit(crate::error::get_exit_code(&error));
                    }
                } else {
                    eprintln!(
                        "{}",
                        format_error_with_color(&err, std::io::stderr().is_terminal())
                    );
                    std::process::exit(crate::error::get_exit_code(&err));
                }
            } else {
                return Err(err);
            }
        }
    };
    log::debug!("JDK path: {jdk_path:?}");

    // Build tool path
    let tool_path = build_tool_path(&jdk_path, &tool_name)?;
    log::debug!("Tool path: {tool_path:?}");

    // Collect arguments (skip argv[0])
    let args: Vec<OsString> = env::args_os().skip(1).collect();

    // Validate tool path and permissions before execution
    security_validator.validate_path(&tool_path)?;
    security_validator.check_permissions(&tool_path)?;

    // Log performance
    let elapsed = start.elapsed();
    log::debug!("Shim resolution completed in {elapsed:?}");

    // Execute the tool
    let err = crate::platform::process::exec_replace(&tool_path, args);

    // exec_replace only returns on error
    Err(KopiError::SystemError(format!(
        "Failed to execute {tool_path:?}: {err}"
    )))
}

fn get_tool_name() -> Result<String> {
    let arg0 = env::args_os()
        .next()
        .ok_or_else(|| KopiError::SystemError("No argv[0] found".to_string()))?;

    let path = PathBuf::from(arg0);
    let tool_name = path
        .file_stem()
        .and_then(|s| s.to_str())
        .ok_or_else(|| KopiError::SystemError("Invalid tool name in argv[0]".to_string()))?;

    Ok(tool_name.to_string())
}

fn find_jdk_installation(
    repository: &JdkRepository,
    version_request: &VersionRequest,
) -> Result<PathBuf> {
    log::debug!("Finding JDK for version request: {version_request:?}");

    // Parse distribution from version request
    let distribution = if let Some(dist_name) = &version_request.distribution {
        Distribution::from_str(dist_name)?
    } else {
        // Use default distribution from config or fall back to temurin
        Distribution::Temurin
    };
    log::debug!("Using distribution: {}", distribution.id());

    // List installed JDKs
    let installed_jdks = repository.list_installed_jdks()?;
    log::debug!("Found {} installed JDKs", installed_jdks.len());

    // Find matching JDK
    for jdk in installed_jdks {
        log::debug!(
            "Checking JDK: distribution={}, version={} against request: distribution={}, \
             version={}",
            jdk.distribution,
            jdk.version,
            distribution.id(),
            version_request.version_pattern
        );

        if jdk.distribution.to_lowercase() == distribution.id() {
            // Check if the installed JDK version matches the requested pattern
            let matches = jdk
                .version
                .matches_pattern(&version_request.version_pattern);
            log::debug!(
                "Version matching: installed {} matches pattern {}? {}",
                jdk.version,
                version_request.version_pattern,
                matches
            );
            if matches {
                return Ok(jdk.path);
            }
        }
    }

    // No matching JDK found
    Err(KopiError::JdkNotInstalled {
        jdk_spec: format!("{}@{}", distribution.id(), version_request.version_pattern),
        version: Some(version_request.version_pattern.clone()),
        distribution: Some(distribution.id().to_string()),
        auto_install_enabled: false, // Will be updated by caller
        auto_install_failed: None,
        user_declined: false,
        install_in_progress: false,
    })
}

fn build_tool_path(jdk_path: &Path, tool_name: &str) -> Result<PathBuf> {
    let bin_dir = jdk_path.join("bin");

    let tool_filename = if crate::platform::executable_extension().is_empty() {
        tool_name.to_string()
    } else {
        format!("{}{}", tool_name, crate::platform::executable_extension())
    };

    let tool_path = bin_dir.join(tool_filename);

    // Verify the tool exists
    if !tool_path.exists() {
        // Only exit in production code, not during tests
        #[cfg(not(test))]
        {
            // List available tools in the JDK bin directory
            let mut available_tools = Vec::new();

            if bin_dir.exists() {
                if let Ok(entries) = std::fs::read_dir(&bin_dir) {
                    for entry in entries.flatten() {
                        if let Some(name) = entry.file_name().to_str() {
                            // Remove .exe extension on Windows
                            let tool_name_clean = if cfg!(windows) && name.ends_with(".exe") {
                                &name[..name.len() - 4]
                            } else {
                                name
                            };

                            // Only include executable files
                            if entry.metadata().map(|m| m.is_file()).unwrap_or(false) {
                                available_tools.push(tool_name_clean.to_string());
                            }
                        }
                    }
                }
            }

            available_tools.sort();

            let error = KopiError::ToolNotFound {
                tool: tool_name.to_string(),
                jdk_path: jdk_path.to_str().unwrap_or("<invalid path>").to_string(),
                available_tools,
            };
            eprintln!(
                "{}",
                format_error_with_color(&error, std::io::stderr().is_terminal())
            );
            std::process::exit(crate::error::get_exit_code(&error));
        }

        #[cfg(test)]
        return Err(KopiError::SystemError(format!(
            "Tool '{tool_name}' not found in JDK at {jdk_path:?}"
        )));
    }

    Ok(tool_path)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::KopiConfig;
    use crate::version::Version;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn test_get_tool_name() {
        // We can't easily test get_tool_name() since it reads from env::args_os()
        // This would require integration tests
    }

    #[test]
    fn test_build_tool_path_unix() {
        #[cfg(not(target_os = "windows"))]
        {
            let temp_dir = TempDir::new().unwrap();
            let jdk_path = temp_dir.path();
            let bin_dir = jdk_path.join("bin");
            fs::create_dir_all(&bin_dir).unwrap();

            let java_path = bin_dir.join("java");
            fs::write(&java_path, "").unwrap();

            let result = build_tool_path(jdk_path, "java").unwrap();
            assert_eq!(result, java_path);
        }
    }

    #[test]
    fn test_build_tool_path_windows() {
        #[cfg(target_os = "windows")]
        {
            let temp_dir = TempDir::new().unwrap();
            let jdk_path = temp_dir.path();
            let bin_dir = jdk_path.join("bin");
            fs::create_dir_all(&bin_dir).unwrap();

            let java_path = bin_dir.join("java.exe");
            fs::write(&java_path, "").unwrap();

            let result = build_tool_path(jdk_path, "java").unwrap();
            assert_eq!(result, java_path);
        }
    }

    #[test]
    fn test_build_tool_path_not_found() {
        let temp_dir = TempDir::new().unwrap();
        let jdk_path = temp_dir.path();
        let bin_dir = jdk_path.join("bin");
        fs::create_dir_all(&bin_dir).unwrap();

        let result = build_tool_path(jdk_path, "nonexistent");
        assert!(result.is_err());
    }

    #[test]
    fn test_find_jdk_installation_found() {
        let temp_dir = TempDir::new().unwrap();
        // Repository setup removed - not needed for this test

        // Create a mock installed JDK structure
        let jdk_path = temp_dir.path().join("jdks").join("temurin-21.0.1");
        fs::create_dir_all(&jdk_path).unwrap();

        // Create version request
        let _version_request = VersionRequest::new("21".to_string())
            .unwrap()
            .with_distribution("temurin".to_string());

        // Since we can't easily mock list_installed_jdks, we test with actual filesystem
        // This demonstrates the need for better abstraction in future phases
    }

    #[test]
    fn test_find_jdk_installation_not_found() {
        // Clear any leftover environment variables
        unsafe {
            std::env::remove_var("KOPI_AUTO_INSTALL");
            std::env::remove_var("KOPI_AUTO_INSTALL__ENABLED");
            std::env::remove_var("KOPI_AUTO_INSTALL__PROMPT");
            std::env::remove_var("KOPI_AUTO_INSTALL__TIMEOUT_SECS");
        }

        let temp_dir = TempDir::new().unwrap();
        let config = KopiConfig::new(temp_dir.path().to_path_buf()).unwrap();
        let repository = JdkRepository::new(&config);

        let version_request = VersionRequest::new("99".to_string())
            .unwrap()
            .with_distribution("nonexistent".to_string());

        let result = find_jdk_installation(&repository, &version_request);
        assert!(result.is_err());
        assert!(matches!(result, Err(KopiError::JdkNotInstalled { .. })));
    }

    #[test]
    fn test_version_matching_logic() {
        // Test that version matching works correctly
        // Scenario: User has .kopi-version with "17", JDK installed as "17.0.15"

        // The correct way: installed version matches requested pattern
        let installed = Version::from_str("17.0.15").unwrap();
        let requested = Version::from_str("17").unwrap();
        assert!(installed.matches_pattern(&requested.to_string()));

        // More test cases
        assert!(Version::from_str("21.0.1").unwrap().matches_pattern("21"));
        assert!(
            Version::from_str("11.0.21+9")
                .unwrap()
                .matches_pattern("11")
        );
        assert!(
            Version::from_str("17.0.15")
                .unwrap()
                .matches_pattern("17.0")
        );

        // Negative cases
        assert!(!Version::from_str("17.0.15").unwrap().matches_pattern("18"));
        assert!(
            !Version::from_str("17.0.15")
                .unwrap()
                .matches_pattern("17.0.16")
        );
    }
}