kopi 0.1.1

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
// 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::error::{KopiError, Result};
use crate::platform::{executable_extension, with_executable_extension};
use crate::storage::{InstalledJdk, JdkRepository};
use crate::version::VersionRequest;
use crate::version::resolver::{VersionResolver, VersionSource};
use serde::Serialize;
use std::path::{Path, PathBuf};
use std::str::FromStr;

#[derive(Serialize)]
struct WhichOutput {
    distribution: String,
    version: String,
    tool: String,
    tool_path: String,
    jdk_home: String,
    source: String,
}

pub struct WhichCommand<'a> {
    config: &'a KopiConfig,
}

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

    pub fn execute(&self, version: Option<&str>, tool: &str, home: bool, json: bool) -> Result<()> {
        let repo = JdkRepository::new(self.config);

        // Resolve JDK spec
        let (version_request, source) = if let Some(version) = version {
            // Parse specified version
            let request = VersionRequest::from_str(version)?;
            (request, "specified".to_string())
        } else {
            // Use current version resolution
            let resolver = VersionResolver::new(self.config);
            let (version_request, version_source) = resolver.resolve_version()?;
            let source = format_source(&version_source);
            (version_request, source)
        };

        // Find installed JDK
        let matching_jdks = repo.find_matching_jdks(&version_request)?;
        let installation = if matching_jdks.is_empty() {
            return Err(KopiError::JdkNotInstalled {
                jdk_spec: version_request.to_string(),
                version: Some(version_request.version_pattern.clone()),
                distribution: version_request.distribution.clone(),
                auto_install_enabled: false,
                auto_install_failed: None,
                user_declined: false,
                install_in_progress: false,
            });
        } else if matching_jdks.len() == 1 {
            matching_jdks.into_iter().next().unwrap()
        } else {
            // Multiple matches - need disambiguation
            return Err(KopiError::ValidationError(format!(
                "Multiple JDKs match version '{}'\n\nFound:\n  {}\n\nPlease specify the full \
                 version or distribution",
                version_request.version_pattern,
                matching_jdks
                    .iter()
                    .map(|jdk| format!("{}@{}", jdk.distribution, jdk.version))
                    .collect::<Vec<_>>()
                    .join("\n  ")
            )));
        };

        // Determine output path
        let output_path = if home {
            installation.path.clone()
        } else {
            get_tool_path(&installation, tool)?
        };

        // Output result
        if json {
            output_json(&installation, tool, &output_path, &source)?;
        } else {
            println!("{}", output_path.display());
        }

        Ok(())
    }
}

fn format_source(source: &VersionSource) -> String {
    match source {
        VersionSource::Environment(_) => "environment".to_string(),
        VersionSource::ProjectFile(path) => {
            format!("project file: {}", path.display())
        }
        VersionSource::GlobalDefault(_) => "global default".to_string(),
    }
}

fn get_tool_path(installation: &InstalledJdk, tool: &str) -> Result<PathBuf> {
    let tool_name = with_executable_extension(tool);
    let tool_path = installation.path.join("bin").join(&tool_name);

    if !tool_path.exists() {
        // Get list of available tools in the bin directory
        let bin_dir = installation.path.join("bin");
        let mut available_tools = Vec::new();

        if let Ok(entries) = std::fs::read_dir(&bin_dir) {
            for entry in entries.flatten() {
                if let Ok(file_type) = entry.file_type()
                    && (file_type.is_file() || file_type.is_symlink())
                    && let Some(name) = entry.file_name().to_str()
                {
                    // Remove executable extension for cleaner listing
                    let tool_name = if !executable_extension().is_empty()
                        && name.ends_with(executable_extension())
                    {
                        &name[..name.len() - executable_extension().len()]
                    } else {
                        name
                    };
                    available_tools.push(tool_name.to_string());
                }
            }
        }

        available_tools.sort();

        return Err(KopiError::ToolNotFound {
            tool: tool.to_string(),
            jdk_path: installation.path.display().to_string(),
            available_tools,
        });
    }

    Ok(tool_path)
}

fn output_json(
    installation: &InstalledJdk,
    tool: &str,
    tool_path: &Path,
    source: &str,
) -> Result<()> {
    let output = WhichOutput {
        distribution: installation.distribution.clone(),
        version: installation.version.to_string(),
        tool: tool.to_string(),
        tool_path: tool_path.display().to_string(),
        jdk_home: installation.path.display().to_string(),
        source: source.to_string(),
    };

    println!("{}", serde_json::to_string_pretty(&output)?);
    Ok(())
}

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

    #[cfg(unix)]
    use std::os::unix::fs::PermissionsExt;

    fn create_test_jdk(temp_dir: &TempDir, distribution: &str, version: &str) -> PathBuf {
        let jdk_path = temp_dir
            .path()
            .join("jdks")
            .join(format!("{distribution}-{version}"));

        let bin_dir = jdk_path.join("bin");
        fs::create_dir_all(&bin_dir).unwrap();

        // Create test tools
        for tool in &["java", "javac", "jar", "jshell"] {
            let tool_path = bin_dir.join(with_executable_extension(tool));
            fs::write(&tool_path, "#!/bin/sh\necho test").unwrap();

            #[cfg(unix)]
            {
                let metadata = fs::metadata(&tool_path).unwrap();
                let mut perms = metadata.permissions();
                perms.set_mode(0o755);
                fs::set_permissions(&tool_path, perms).unwrap();
            }
        }

        jdk_path
    }

    fn setup_test_environment(temp_dir: &TempDir, distribution: &str, version: &str) -> KopiConfig {
        let jdk_path = create_test_jdk(temp_dir, distribution, version);

        // Create version metadata file
        let metadata = serde_json::json!({
            "distribution": distribution,
            "version": version,
        });
        let metadata_path = jdk_path.join("kopi-metadata.json");
        fs::write(&metadata_path, serde_json::to_string(&metadata).unwrap()).unwrap();

        KopiConfig::new(temp_dir.path().to_path_buf()).unwrap()
    }

    #[test]
    fn test_version_request_from_str() {
        // Test simple version
        let request = VersionRequest::from_str("21").unwrap();
        assert_eq!(request.version_pattern, "21");
        assert_eq!(request.distribution, None);

        // Test distribution@version format
        let request = VersionRequest::from_str("temurin@21.0.5").unwrap();
        assert_eq!(request.version_pattern, "21.0.5");
        assert_eq!(request.distribution, Some("temurin".to_string()));

        // Test package_type@version@distribution format (3 parts)
        let request = VersionRequest::from_str("jre@21@temurin").unwrap();
        assert_eq!(request.version_pattern, "21");
        assert_eq!(request.distribution, Some("temurin".to_string()));
        assert_eq!(
            request.package_type,
            Some(crate::models::package::PackageType::Jre)
        );
    }

    #[test]
    fn test_which_specific_version() {
        let temp_dir = TempDir::new().unwrap();
        let config = setup_test_environment(&temp_dir, "temurin", "21.0.5+11");

        let command = WhichCommand::new(&config).unwrap();
        let result = command.execute(Some("temurin@21"), "java", false, false);

        assert!(result.is_ok());
    }

    #[test]
    fn test_which_tool_not_found() {
        let temp_dir = TempDir::new().unwrap();
        let config = setup_test_environment(&temp_dir, "temurin", "21.0.5+11");

        let command = WhichCommand::new(&config).unwrap();
        let result = command.execute(Some("temurin@21"), "nonexistent-tool", false, false);

        match result {
            Err(KopiError::ToolNotFound { tool, .. }) => {
                assert_eq!(tool, "nonexistent-tool");
            }
            _ => panic!("Expected ToolNotFound error"),
        }
    }

    #[test]
    fn test_which_home_option() {
        let temp_dir = TempDir::new().unwrap();
        let config = setup_test_environment(&temp_dir, "temurin", "21.0.5+11");

        let command = WhichCommand::new(&config).unwrap();
        // Home option should return JDK home directory
        let result = command.execute(Some("temurin@21"), "java", true, false);

        assert!(result.is_ok());
    }

    #[test]
    fn test_which_json_output() {
        let temp_dir = TempDir::new().unwrap();
        let config = setup_test_environment(&temp_dir, "temurin", "21.0.5+11");

        let command = WhichCommand::new(&config).unwrap();

        // Capture stdout for JSON output test
        let result = std::panic::catch_unwind(|| {
            command
                .execute(Some("temurin@21"), "javac", false, true)
                .unwrap();
        });

        // JSON output would be printed to stdout
        assert!(result.is_ok());
    }

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

        // Create multiple JDKs with same major version
        let _jdk1 = create_test_jdk(&temp_dir, "temurin", "21.0.5+11");
        let _jdk2 = create_test_jdk(&temp_dir, "corretto", "21.0.7.6.1");

        // Create metadata for both
        let metadata1 = serde_json::json!({
            "distribution": "temurin",
            "version": "21.0.5+11",
        });
        let metadata2 = serde_json::json!({
            "distribution": "corretto",
            "version": "21.0.7.6.1",
        });

        fs::write(
            _jdk1.join("kopi-metadata.json"),
            serde_json::to_string(&metadata1).unwrap(),
        )
        .unwrap();
        fs::write(
            _jdk2.join("kopi-metadata.json"),
            serde_json::to_string(&metadata2).unwrap(),
        )
        .unwrap();

        let config = KopiConfig::new(temp_dir.path().to_path_buf()).unwrap();
        let command = WhichCommand::new(&config).unwrap();
        let result = command.execute(Some("21"), "java", false, false);

        match result {
            Err(KopiError::ValidationError(msg)) => {
                assert!(msg.contains("Multiple JDKs match"));
                assert!(msg.contains("temurin@21"));
                assert!(msg.contains("corretto@21"));
            }
            _ => panic!("Expected ValidationError for ambiguous version"),
        }
    }

    #[test]
    fn test_version_request_display() {
        let request = VersionRequest::new("21".to_string()).unwrap();
        assert_eq!(request.to_string(), "21");

        let request = VersionRequest::new("21".to_string())
            .unwrap()
            .with_distribution("temurin".to_string());
        assert_eq!(request.to_string(), "temurin@21");
    }

    #[test]
    fn test_get_tool_path() {
        let temp_dir = TempDir::new().unwrap();
        let jdk_path = create_test_jdk(&temp_dir, "temurin", "21.0.5");

        let jdk = InstalledJdk::new(
            "temurin".to_string(),
            crate::version::Version::from_str("21.0.5").unwrap(),
            jdk_path,
            false,
        );

        // Test existing tool
        let java_path = get_tool_path(&jdk, "java").unwrap();
        assert!(java_path.exists());
        assert!(java_path.ends_with(if cfg!(windows) { "java.exe" } else { "java" }));

        // Test non-existent tool
        let result = get_tool_path(&jdk, "nonexistent");
        assert!(result.is_err());
        if let Err(KopiError::ToolNotFound {
            tool,
            available_tools,
            ..
        }) = result
        {
            assert_eq!(tool, "nonexistent");
            assert!(available_tools.contains(&"java".to_string()));
            assert!(available_tools.contains(&"javac".to_string()));
        } else {
            panic!("Expected ToolNotFound error");
        }
    }

    #[test]
    fn test_get_tool_path_various_tools() {
        let temp_dir = TempDir::new().unwrap();
        let jdk_path = create_test_jdk(&temp_dir, "temurin", "21.0.5");

        let jdk = InstalledJdk::new(
            "temurin".to_string(),
            Version::from_str("21.0.5").unwrap(),
            jdk_path,
            false,
        );

        // Test various JDK tools that are created by create_test_jdk
        for tool_name in &["java", "javac", "jar", "jshell"] {
            let tool_path = get_tool_path(&jdk, tool_name).unwrap();
            assert!(tool_path.exists());
            let expected_suffix = with_executable_extension(tool_name);
            assert!(tool_path.ends_with(&expected_suffix));
        }
    }

    #[test]
    fn test_format_source() {
        assert_eq!(
            format_source(&VersionSource::Environment("temurin@21".to_string())),
            "environment"
        );

        let path = PathBuf::from("/project/.kopi-version");
        assert_eq!(
            format_source(&VersionSource::ProjectFile(path.clone())),
            format!("project file: {}", path.display())
        );

        let path = PathBuf::from("/home/user/.kopi/version");
        assert_eq!(
            format_source(&VersionSource::GlobalDefault(path)),
            "global default"
        );
    }

    #[test]
    fn test_which_not_installed() {
        let temp_dir = TempDir::new().unwrap();
        let config = KopiConfig::new(temp_dir.path().to_path_buf()).unwrap();
        let command = WhichCommand::new(&config).unwrap();

        let result = command.execute(Some("temurin@22"), "java", false, false);

        match result {
            Err(KopiError::JdkNotInstalled { jdk_spec, .. }) => {
                assert_eq!(jdk_spec, "temurin@22");
            }
            _ => panic!("Expected JdkNotInstalled error"),
        }
    }
}