kopi 0.1.2

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
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
// 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::KopiConfig;
use crate::doctor::{CheckCategory, CheckResult, CheckStatus, DiagnosticCheck};
use crate::platform::shell::{detect_shell, is_in_path};
use crate::platform::{executable_extension, kopi_binary_name, path_separator};
use std::fs;
use std::path::Path;
use std::process::Command;
use std::time::Instant;
use which::which;

/// Check if kopi binary is installed and in PATH
pub struct KopiBinaryCheck;

impl DiagnosticCheck for KopiBinaryCheck {
    fn name(&self) -> &str {
        "Kopi Binary in PATH"
    }

    fn run(&self, start: Instant, category: CheckCategory) -> CheckResult {
        let binary_name = kopi_binary_name();

        match which(binary_name) {
            Ok(path) => {
                // Check if the binary is executable using platform-specific logic
                match crate::platform::file_ops::is_executable(&path) {
                    Ok(is_exec) => {
                        if !is_exec {
                            return CheckResult::new(
                                self.name(),
                                category,
                                CheckStatus::Fail,
                                "Kopi binary found but not executable",
                                start.elapsed(),
                            )
                            .with_suggestion(if cfg!(unix) {
                                format!("Run: chmod +x {}", path.display())
                            } else {
                                "Ensure the file has .exe extension".to_string()
                            });
                        }

                        CheckResult::new(
                            self.name(),
                            category,
                            CheckStatus::Pass,
                            format!("Kopi binary found at {}", path.display()),
                            start.elapsed(),
                        )
                    }
                    Err(e) => CheckResult::new(
                        self.name(),
                        category,
                        CheckStatus::Warning,
                        format!("Kopi binary found but cannot check permissions: {e}"),
                        start.elapsed(),
                    ),
                }
            }
            Err(_) => CheckResult::new(
                self.name(),
                category,
                CheckStatus::Fail,
                "Kopi binary not found in PATH",
                start.elapsed(),
            )
            .with_suggestion("Add kopi installation directory to your PATH environment variable"),
        }
    }
}

/// Check kopi version (compare with latest if network available)
pub struct VersionCheck;

impl DiagnosticCheck for VersionCheck {
    fn name(&self) -> &str {
        "Kopi Version"
    }

    fn run(&self, start: Instant, category: CheckCategory) -> CheckResult {
        let binary_name = kopi_binary_name();

        // First check if kopi is available
        let kopi_path = match which(binary_name) {
            Ok(path) => path,
            Err(_) => {
                return CheckResult::new(
                    self.name(),
                    category,
                    CheckStatus::Skip,
                    "Cannot check version - kopi not found in PATH",
                    start.elapsed(),
                );
            }
        };

        // Get current version
        match Command::new(&kopi_path).arg("--version").output() {
            Ok(output) => {
                if output.status.success() {
                    let version_str = String::from_utf8_lossy(&output.stdout).trim().to_string();

                    // TODO: In the future, we could check against the latest version from GitHub
                    // For now, just report the current version
                    CheckResult::new(
                        self.name(),
                        category,
                        CheckStatus::Pass,
                        format!("Kopi version: {version_str}"),
                        start.elapsed(),
                    )
                } else {
                    CheckResult::new(
                        self.name(),
                        category,
                        CheckStatus::Warning,
                        "Could not determine kopi version",
                        start.elapsed(),
                    )
                    .with_details(String::from_utf8_lossy(&output.stderr).to_string())
                }
            }
            Err(e) => CheckResult::new(
                self.name(),
                category,
                CheckStatus::Warning,
                format!("Failed to execute kopi --version: {e}"),
                start.elapsed(),
            ),
        }
    }
}

/// Check if installation directory exists and has proper structure
pub struct InstallationDirectoryCheck<'a> {
    config: &'a KopiConfig,
}

impl<'a> InstallationDirectoryCheck<'a> {
    pub fn new(config: &'a KopiConfig) -> Self {
        Self { config }
    }
}

impl DiagnosticCheck for InstallationDirectoryCheck<'_> {
    fn name(&self) -> &str {
        "Installation Directory Structure"
    }

    fn run(&self, start: Instant, category: CheckCategory) -> CheckResult {
        let kopi_home = self.config.kopi_home();

        // Check if kopi home exists
        if !kopi_home.exists() {
            return CheckResult::new(
                self.name(),
                category,
                CheckStatus::Fail,
                format!("Kopi home directory not found: {}", kopi_home.display()),
                start.elapsed(),
            )
            .with_suggestion("Run kopi installer or create the directory manually");
        }

        // Check subdirectories
        let mut missing_dirs = Vec::new();
        let subdirs = [
            ("jdks", self.config.jdks_dir()),
            ("shims", self.config.shims_dir()),
            ("cache", self.config.cache_dir()),
        ];

        for (name, dir_result) in subdirs {
            match dir_result {
                Ok(dir) => {
                    if !dir.exists() {
                        missing_dirs.push(name);
                    }
                }
                Err(e) => {
                    return CheckResult::new(
                        self.name(),
                        category,
                        CheckStatus::Fail,
                        format!("Cannot determine {name} directory"),
                        start.elapsed(),
                    )
                    .with_details(e.to_string());
                }
            }
        }

        if missing_dirs.is_empty() {
            CheckResult::new(
                self.name(),
                category,
                CheckStatus::Pass,
                format!(
                    "Installation directory structure is valid: {}",
                    kopi_home.display()
                ),
                start.elapsed(),
            )
        } else {
            CheckResult::new(
                self.name(),
                category,
                CheckStatus::Warning,
                format!("Missing subdirectories: {}", missing_dirs.join(", ")),
                start.elapsed(),
            )
            .with_suggestion("These directories will be created automatically when needed")
        }
    }
}

/// Check if config file is valid
pub struct ConfigFileCheck<'a> {
    config: &'a KopiConfig,
}

impl<'a> ConfigFileCheck<'a> {
    pub fn new(config: &'a KopiConfig) -> Self {
        Self { config }
    }
}

impl DiagnosticCheck for ConfigFileCheck<'_> {
    fn name(&self) -> &str {
        "Configuration File"
    }

    fn run(&self, start: Instant, category: CheckCategory) -> CheckResult {
        let config_path = self.config.config_path();

        if !config_path.exists() {
            // Config file is optional
            return CheckResult::new(
                self.name(),
                category,
                CheckStatus::Pass,
                "No config file found (using defaults)",
                start.elapsed(),
            )
            .with_details(format!("Expected location: {}", config_path.display()));
        }

        // Try to parse the config file
        match fs::read_to_string(&config_path) {
            Ok(contents) => match toml::from_str::<toml::Value>(&contents) {
                Ok(_) => CheckResult::new(
                    self.name(),
                    category,
                    CheckStatus::Pass,
                    format!("Config file is valid: {}", config_path.display()),
                    start.elapsed(),
                ),
                Err(e) => CheckResult::new(
                    self.name(),
                    category,
                    CheckStatus::Fail,
                    "Config file has invalid TOML syntax",
                    start.elapsed(),
                )
                .with_details(e.to_string())
                .with_suggestion(format!(
                    "Fix the syntax errors in {}",
                    config_path.display()
                )),
            },
            Err(e) => CheckResult::new(
                self.name(),
                category,
                CheckStatus::Warning,
                "Cannot read config file",
                start.elapsed(),
            )
            .with_details(e.to_string()),
        }
    }
}

/// Check if shims directory is in PATH
pub struct ShimsInPathCheck<'a> {
    config: &'a KopiConfig,
}

impl<'a> ShimsInPathCheck<'a> {
    pub fn new(config: &'a KopiConfig) -> Self {
        Self { config }
    }
}

impl DiagnosticCheck for ShimsInPathCheck<'_> {
    fn name(&self) -> &str {
        "Shims Directory in PATH"
    }

    fn run(&self, start: Instant, category: CheckCategory) -> CheckResult {
        let shims_dir = match self.config.shims_dir() {
            Ok(dir) => dir,
            Err(e) => {
                return CheckResult::new(
                    self.name(),
                    category,
                    CheckStatus::Fail,
                    "Cannot determine shims directory",
                    start.elapsed(),
                )
                .with_details(e.to_string());
            }
        };

        if is_in_path(&shims_dir) {
            // Check PATH priority - shims should come before system Java
            let path_var = std::env::var("PATH").unwrap_or_default();
            let paths: Vec<&str> = path_var.split(path_separator()).collect();

            let shims_index = paths.iter().position(|p| Path::new(p) == shims_dir);
            let java_indices: Vec<usize> = paths
                .iter()
                .enumerate()
                .filter_map(|(i, p)| {
                    let java_path = Path::new(p)
                        .join("java")
                        .with_extension(executable_extension());
                    if java_path.exists() && shims_index != Some(i) {
                        Some(i)
                    } else {
                        None
                    }
                })
                .collect();

            if let Some(shims_idx) = shims_index
                && let Some(&first_java_idx) = java_indices.first()
                && shims_idx > first_java_idx
            {
                return CheckResult::new(
                    self.name(),
                    category,
                    CheckStatus::Warning,
                    "Shims directory is in PATH but appears after system Java",
                    start.elapsed(),
                )
                .with_details(format!(
                    "Shims at position {}, system Java at position {}",
                    shims_idx + 1,
                    first_java_idx + 1
                ))
                .with_suggestion("Move shims directory earlier in PATH to take precedence");
            }

            CheckResult::new(
                self.name(),
                category,
                CheckStatus::Pass,
                "Shims directory is in PATH with correct priority",
                start.elapsed(),
            )
        } else {
            let shell_result = detect_shell();
            let suggestion = match shell_result {
                Ok((shell, _)) => match shell {
                    crate::platform::shell::Shell::Bash => {
                        format!(
                            "Add to ~/.bashrc:\nexport PATH=\"{}:$PATH\"",
                            shims_dir.display()
                        )
                    }
                    crate::platform::shell::Shell::Zsh => {
                        format!(
                            "Add to ~/.zshrc:\nexport PATH=\"{}:$PATH\"",
                            shims_dir.display()
                        )
                    }
                    crate::platform::shell::Shell::Fish => {
                        format!(
                            "Add to ~/.config/fish/config.fish:\nset -gx PATH {} $PATH",
                            shims_dir.display()
                        )
                    }
                    crate::platform::shell::Shell::PowerShell => {
                        format!(
                            "Add to $PROFILE:\n$env:Path = \"{};$env:Path\"",
                            shims_dir.display()
                        )
                    }
                    _ => format!(
                        "Add {} to your PATH environment variable",
                        shims_dir.display()
                    ),
                },
                Err(_) => format!(
                    "Add {} to your PATH environment variable",
                    shims_dir.display()
                ),
            };

            CheckResult::new(
                self.name(),
                category,
                CheckStatus::Fail,
                "Shims directory not found in PATH",
                start.elapsed(),
            )
            .with_details(format!("Expected: {}", shims_dir.display()))
            .with_suggestion(suggestion)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::env;
    use tempfile::TempDir;

    #[test]
    fn test_kopi_binary_check_not_in_path() {
        // Save original PATH
        let original_path = env::var("PATH").unwrap_or_default();

        // Set PATH to exclude kopi
        unsafe {
            env::set_var("PATH", "/usr/bin:/bin");
        }

        let check = KopiBinaryCheck;
        let start = Instant::now();
        let result = check.run(start, CheckCategory::Installation);

        assert_eq!(result.status, CheckStatus::Fail);
        assert!(result.message.contains("not found in PATH"));
        assert!(result.suggestion.is_some());

        // Restore original PATH
        unsafe {
            env::set_var("PATH", original_path);
        }
    }

    #[test]
    fn test_version_check_skip_when_not_found() {
        // Save original PATH
        let original_path = env::var("PATH").unwrap_or_default();

        // Set PATH to exclude kopi
        unsafe {
            env::set_var("PATH", "/usr/bin:/bin");
        }

        let check = VersionCheck;
        let start = Instant::now();
        let result = check.run(start, CheckCategory::Installation);

        assert_eq!(result.status, CheckStatus::Skip);
        assert!(result.message.contains("kopi not found"));

        // Restore original PATH
        unsafe {
            env::set_var("PATH", original_path);
        }
    }

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

        // Override kopi_home to use temp directory
        unsafe {
            env::set_var("KOPI_HOME", temp_dir.path());
        }
        let config = crate::config::new_kopi_config().unwrap();

        let check = InstallationDirectoryCheck::new(&config);
        let start = Instant::now();
        let result = check.run(start, CheckCategory::Installation);

        // Directory and subdirs exist because config creation creates them
        assert_eq!(result.status, CheckStatus::Pass);
        assert!(
            result
                .message
                .contains("Installation directory structure is valid")
        );

        unsafe {
            env::remove_var("KOPI_HOME");
        }
    }

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

        // Override kopi_home to use temp directory
        unsafe {
            env::set_var("KOPI_HOME", temp_dir.path());
        }
        let config = crate::config::new_kopi_config().unwrap();

        let check = ConfigFileCheck::new(&config);
        let start = Instant::now();
        let result = check.run(start, CheckCategory::Installation);

        // Missing config file is OK (uses defaults)
        assert_eq!(result.status, CheckStatus::Pass);
        assert!(result.message.contains("using defaults"));

        unsafe {
            env::remove_var("KOPI_HOME");
        }
    }

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

        // First create a valid config
        unsafe {
            env::set_var("KOPI_HOME", temp_dir.path());
            // Clear any problematic environment variables
            env::remove_var("KOPI_STORAGE_MIN_DISK_SPACE_MB");
            env::remove_var("KOPI_AUTO_INSTALL_TIMEOUT_SECS");
            env::remove_var("KOPI_AUTO_INSTALL_ENABLED");
            env::remove_var("KOPI_CACHE_TTL_HOURS");
        }
        let config = crate::config::new_kopi_config().unwrap();
        let config_path = config.config_path();

        // Now write invalid TOML to the config file
        fs::write(&config_path, "invalid = toml content [").unwrap();

        let check = ConfigFileCheck::new(&config);
        let start = Instant::now();
        let result = check.run(start, CheckCategory::Installation);

        assert_eq!(result.status, CheckStatus::Fail);
        assert!(result.message.contains("invalid TOML syntax"));
        assert!(result.suggestion.is_some());

        unsafe {
            env::remove_var("KOPI_HOME");
        }
    }

    #[test]
    fn test_shims_in_path_check() {
        let temp_dir = TempDir::new().unwrap();
        let shims_dir = temp_dir.path().join("shims");
        fs::create_dir(&shims_dir).unwrap();

        unsafe {
            env::set_var("KOPI_HOME", temp_dir.path());
        }
        let config = crate::config::new_kopi_config().unwrap();

        // Save original PATH
        let original_path = env::var("PATH").unwrap_or_default();

        // Test when shims not in PATH
        unsafe {
            env::set_var(
                "PATH",
                if cfg!(windows) {
                    "C:\\Windows;C:\\Windows\\System32"
                } else {
                    "/usr/bin:/bin"
                },
            );
        }
        let check = ShimsInPathCheck::new(&config);
        let start = Instant::now();
        let result = check.run(start, CheckCategory::Installation);
        assert_eq!(result.status, CheckStatus::Fail);
        assert!(result.suggestion.is_some());

        // Test when shims in PATH
        unsafe {
            env::set_var(
                "PATH",
                if cfg!(windows) {
                    format!("{};C:\\Windows", shims_dir.display())
                } else {
                    format!("{}:/usr/bin", shims_dir.display())
                },
            );
        }
        let check = ShimsInPathCheck::new(&config);
        let start = Instant::now();
        let result = check.run(start, CheckCategory::Installation);
        assert_eq!(result.status, CheckStatus::Pass);

        // Restore
        unsafe {
            env::set_var("PATH", original_path);
        }
        unsafe {
            env::remove_var("KOPI_HOME");
        }
    }
}