kopi 0.2.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
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
use std::env;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use std::time::{Duration, Instant};

use kopi::indicator::factory::ProgressFactory;
use kopi::indicator::status::StatusReporter;
use kopi::indicator::{ProgressConfig, ProgressIndicator, ProgressStyle, SilentProgress};
use serial_test::serial;

mod common;
use common::progress_capture::TestProgressCapture;
use common::test_home::TestHomeGuard;

#[test]
fn test_progress_factory_terminal_detection() {
    // Test that factory correctly detects terminal/non-terminal environments
    // With no_progress flag - should return silent progress
    let mut progress = ProgressFactory::create(true);

    // Silent progress should handle all operations without panicking
    let config = ProgressConfig::new(ProgressStyle::Count).with_total(100);
    progress.start(config);
    progress.update(50, None);
    progress.complete(None);

    // Without no_progress flag - behavior depends on terminal detection
    let mut progress = ProgressFactory::create(false);
    let config = ProgressConfig::new(ProgressStyle::Count).with_total(100);
    progress.start(config);
    progress.update(50, None);
    progress.complete(None);
}

#[test]
fn test_progress_indicator_with_install_simulation() {
    let test_home = TestHomeGuard::new();

    // Simulate install operation with progress
    let mut progress = ProgressFactory::create(false);

    let config = ProgressConfig::new(ProgressStyle::Bytes).with_total(150_000_000); // 150MB

    progress.start(config);

    // Simulate download progress
    for i in 0..10 {
        progress.update(i as u64 * 15_000_000, None);
        thread::sleep(Duration::from_millis(10));
    }

    progress.complete(Some("Installation complete".to_string()));

    // Verify no panic and progress completes
    assert!(test_home.path().exists());
}

#[test]
fn test_progress_indicator_with_cache_operations() {
    let _test_home = TestHomeGuard::new();

    let mut progress = ProgressFactory::create(false);

    let config = ProgressConfig::new(ProgressStyle::Count);

    progress.start(config);

    // Simulate cache refresh with message updates
    for i in 0..5 {
        progress.set_message(format!("Processing item {}/5", i + 1));
        thread::sleep(Duration::from_millis(10));
    }

    progress.set_message("Processing distributions...".to_string());
    thread::sleep(Duration::from_millis(10));

    progress.complete(None);
}

#[test]
fn test_progress_indicator_batch_operations() {
    let _test_home = TestHomeGuard::new();

    let mut progress = ProgressFactory::create(false);

    let config = ProgressConfig::new(ProgressStyle::Count).with_total(5);

    progress.start(config);

    // Simulate batch uninstall
    for i in 0..5 {
        progress.set_message(format!("Removing JDK {}/5", i + 1));
        progress.update(i as u64 + 1, None);
        thread::sleep(Duration::from_millis(10));
    }

    progress.complete(Some("All JDKs uninstalled".to_string()));
}

#[test]
fn test_no_progress_mode_across_commands() {
    let _test_home = TestHomeGuard::new();

    // Test with no_progress = true (silent mode)
    let mut progress = ProgressFactory::create(true);

    // All operations should be silent
    let config = ProgressConfig::new(ProgressStyle::Bytes).with_total(100);

    progress.start(config);
    progress.update(50, None);
    progress.set_message("This should not be visible".to_string());
    progress.complete(None);

    // Silent progress handles all operations without output
}

#[test]
#[serial]
fn test_progress_in_ci_environment() {
    // Save original CI env var
    let original_ci = env::var("CI").ok();

    // Test in CI environment
    unsafe {
        env::set_var("CI", "true");
    }

    let mut progress = ProgressFactory::create(false);

    // In CI, should use simple progress (not indicatif with fancy bars)
    let config = ProgressConfig::new(ProgressStyle::Count).with_total(100);

    progress.start(config);
    progress.update(100, None);
    progress.complete(None);

    // Restore original CI env var
    unsafe {
        match original_ci {
            Some(val) => env::set_var("CI", val),
            None => env::remove_var("CI"),
        }
    }
}

#[test]
#[serial]
fn test_progress_with_dumb_terminal() {
    // Save original TERM env var
    let original_term = env::var("TERM").ok();

    // Test with TERM=dumb
    unsafe {
        env::set_var("TERM", "dumb");
    }

    let mut progress = ProgressFactory::create(false);

    // Should use simple progress for dumb terminals
    let config = ProgressConfig::new(ProgressStyle::Bytes).with_total(50);

    progress.start(config);
    progress.update(25, None);
    progress.complete(None);

    // Restore original TERM env var
    unsafe {
        match original_term {
            Some(val) => env::set_var("TERM", val),
            None => env::remove_var("TERM"),
        }
    }
}

#[test]
fn test_progress_indicator_error_handling() {
    let _test_home = TestHomeGuard::new();

    let mut progress = ProgressFactory::create(false);

    let config = ProgressConfig::new(ProgressStyle::Count).with_total(100);

    progress.start(config);
    progress.update(50, None);

    // Simulate error
    progress.error("Simulated error occurred".to_string());

    // Progress should handle error gracefully
    progress.complete(None);
}

#[test]
fn test_progress_indicator_concurrent_operations() {
    let _test_home = TestHomeGuard::new();

    let finished = Arc::new(AtomicBool::new(false));

    let mut handles = vec![];

    // Spawn multiple threads with progress indicators
    for _i in 0..3 {
        let finished = Arc::clone(&finished);

        let handle = thread::spawn(move || {
            let mut progress = ProgressFactory::create(false);

            let config = ProgressConfig::new(ProgressStyle::Count).with_total(50);

            progress.start(config);

            for j in 0..50 {
                if finished.load(Ordering::Relaxed) {
                    break;
                }
                progress.update(j, None);
                thread::sleep(Duration::from_millis(5));
            }

            progress.complete(None);
        });

        handles.push(handle);
    }

    // Let threads run for a bit
    thread::sleep(Duration::from_millis(100));
    finished.store(true, Ordering::Relaxed);

    // Wait for all threads to complete
    for handle in handles {
        handle.join().expect("Thread should complete");
    }
}

#[test]
fn test_status_reporter_silent_mode() {
    let _test_home = TestHomeGuard::new();

    // Test with silent mode
    let reporter = StatusReporter::new(true);

    // These should not output anything
    reporter.operation("Silent operation", "test context");
    reporter.step("Silent step");
    reporter.success("Silent success");

    // Error should still be shown even in silent mode
    reporter.error("This error should be visible");
}

#[test]
fn test_status_reporter_normal_mode() {
    let _test_home = TestHomeGuard::new();

    // Test without silent mode
    let reporter = StatusReporter::new(false);

    reporter.operation("Starting operation", "test context");
    reporter.step("Step 1: Preparing");
    reporter.step("Step 2: Processing");
    reporter.success("Operation completed successfully");
    reporter.error("Example error message");
}

#[test]
fn test_progress_styles() {
    let _test_home = TestHomeGuard::new();

    // Test Bytes style
    {
        let mut progress = ProgressFactory::create(false);
        let config = ProgressConfig::new(ProgressStyle::Bytes).with_total(1_000_000);

        progress.start(config);
        progress.update(500_000, None);
        progress.complete(None);
    }

    // Test Count style
    {
        let mut progress = ProgressFactory::create(false);
        let config = ProgressConfig::new(ProgressStyle::Count).with_total(100);

        progress.start(config);
        progress.update(50, None);
        progress.complete(None);
    }
}

#[test]
fn test_progress_with_message_updates() {
    let _test_home = TestHomeGuard::new();

    let mut progress = ProgressFactory::create(false);

    let config = ProgressConfig::new(ProgressStyle::Count);

    progress.start(config);

    let messages = vec![
        "Initializing...",
        "Connecting to server...",
        "Downloading metadata...",
        "Processing data...",
        "Finalizing...",
    ];

    for msg in messages {
        progress.set_message(msg.to_string());
        thread::sleep(Duration::from_millis(10));
    }

    progress.complete(None);
}

#[test]
fn test_progress_indicator_memory_usage() {
    let _test_home = TestHomeGuard::new();

    // Create and destroy many progress indicators to check for leaks
    for _ in 0..100 {
        let mut progress = ProgressFactory::create(false);

        let config = ProgressConfig::new(ProgressStyle::Count).with_total(10);

        progress.start(config);
        progress.update(5, None);
        progress.complete(None);
    }

    // If we get here without issues, memory management is working
}

#[test]
fn test_progress_indicator_performance() {
    let _test_home = TestHomeGuard::new();

    let mut progress = ProgressFactory::create(true); // Use silent mode for consistent timing

    let config = ProgressConfig::new(ProgressStyle::Count).with_total(1_000_000);

    let start = Instant::now();

    progress.start(config);

    // Perform many updates
    for i in 0..1_000_000 {
        if i % 10_000 == 0 {
            progress.update(i, None);
        }
    }

    progress.complete(None);

    let elapsed = start.elapsed();

    // Verify minimal overhead (should complete in less than 1 second)
    assert!(
        elapsed < Duration::from_secs(1),
        "Progress indicator overhead too high: {elapsed:?}"
    );
}

#[test]
fn test_progress_with_long_operations() {
    let _test_home = TestHomeGuard::new();

    let mut progress = ProgressFactory::create(false);

    // Simulate a long-running operation
    let config = ProgressConfig::new(ProgressStyle::Bytes).with_total(1_000_000_000); // 1GB

    progress.start(config);

    // Simulate progress in chunks
    let chunk_size = 100_000_000; // 100MB chunks
    for i in 0..10 {
        progress.update(i * chunk_size, None);
        thread::sleep(Duration::from_millis(5));
    }

    progress.complete(None);
}

#[test]
fn test_progress_indicator_state_transitions() {
    let _test_home = TestHomeGuard::new();

    let mut progress = ProgressFactory::create(false);

    // Test state transitions: not started -> started -> completed
    let config = ProgressConfig::new(ProgressStyle::Count).with_total(100);

    // Start
    progress.start(config.clone());

    // Update multiple times
    progress.update(25, None);
    progress.update(50, None);
    progress.update(75, None);

    // Complete
    progress.complete(None);

    // Starting again should work
    progress.start(config);
    progress.update(100, None);
    progress.complete(None);
}

#[test]
fn test_progress_indicator_zero_total() {
    let _test_home = TestHomeGuard::new();

    let mut progress = ProgressFactory::create(false);

    // Test with zero total (should handle gracefully)
    let config = ProgressConfig::new(ProgressStyle::Count).with_total(0);

    progress.start(config);
    progress.update(0, None);
    progress.complete(None);
}

#[test]
fn test_progress_indicator_overflow_protection() {
    let _test_home = TestHomeGuard::new();

    let mut progress = ProgressFactory::create(false);

    let config = ProgressConfig::new(ProgressStyle::Count).with_total(100);

    progress.start(config);

    // Try to update beyond total (should handle gracefully)
    progress.update(150, None);
    progress.update(200, None);

    progress.complete(None);
}

#[test]
#[serial]
fn test_metadata_fetch_progress_messages() {
    use kopi::cache::fetch_and_cache_metadata_with_progress;
    use kopi::config::new_kopi_config;

    let test_home = TestHomeGuard::new();
    let test_home = test_home.setup_kopi_structure();

    // Override KOPI_HOME for testing
    unsafe {
        std::env::set_var("KOPI_HOME", test_home.kopi_home().to_str().unwrap());
    }

    let config = new_kopi_config().unwrap();
    let mut capture = TestProgressCapture::new();
    let mut current_step = 0;

    // Mock test - just verify that progress is being updated
    // The actual network call might fail in test environment
    let _ = fetch_and_cache_metadata_with_progress(&config, &mut capture, &mut current_step);

    // Check that progress messages were captured
    let messages = capture.get_messages();
    if !messages.is_empty() {
        // At least some progress messages should be captured
        assert!(capture.message_count() > 0, "Should have progress messages");

        // Check for expected message patterns
        let has_relevant_message = messages.iter().any(|m| {
            m.message.contains("metadata")
                || m.message.contains("Fetch")
                || m.message.contains("source")
                || m.message.contains("cache")
                || m.message.contains("Processing")
        });
        assert!(
            has_relevant_message,
            "Should have relevant progress messages"
        );
    }
}

#[test]
fn test_metadata_progress_step_counting() {
    let mut capture = TestProgressCapture::new();

    // Simulate metadata fetch with step tracking
    capture.with_total(10);

    // Step 1: Initialize
    capture.set_position(1);
    capture.set_message("Initializing metadata provider".to_string());

    // Step 2-6: Sources
    for i in 2..=6 {
        capture.set_position(i);
        capture.set_message(format!("Fetching from source {}", i - 1));
    }

    // Step 7: Process metadata
    capture.set_position(7);
    capture.set_message("Processing metadata".to_string());

    // Step 8: Group distributions
    capture.set_position(8);
    capture.set_message("Grouping distributions".to_string());

    // Step 9: Save cache
    capture.set_position(9);
    capture.set_message("Saving to cache".to_string());

    // Step 10: Complete
    capture.set_position(10);
    capture.finish_with_message("Cache refresh complete");

    // Verify step progression
    assert_eq!(capture.get_position(), 10);
    assert_eq!(capture.get_total(), Some(10));
    assert_eq!(capture.message_count(), 10);
    assert!(capture.contains_message("Fetching from source"));
    assert!(capture.contains_message("Cache refresh complete"));
}

#[test]
fn test_metadata_progress_error_handling() {
    let mut capture = TestProgressCapture::new();

    capture.set_message("Starting metadata fetch".to_string());
    capture.set_message("Connecting to API".to_string());

    // Simulate an error
    capture.error("Failed to connect to metadata source".to_string());

    // Verify error was captured
    assert!(capture.contains_message("[ERROR]"));
    assert!(capture.contains_message("Failed to connect"));
}

#[test]
fn test_silent_progress_with_metadata() {
    use kopi::cache::fetch_and_cache_metadata_with_progress;
    use kopi::config::new_kopi_config;

    let test_home = TestHomeGuard::new();
    let test_home = test_home.setup_kopi_structure();

    // Override KOPI_HOME for testing
    unsafe {
        std::env::set_var("KOPI_HOME", test_home.kopi_home().to_str().unwrap());
    }

    let config = new_kopi_config().unwrap();
    let mut progress = SilentProgress;
    let mut current_step = 0;

    // SilentProgress should handle all operations without output
    let _ = fetch_and_cache_metadata_with_progress(&config, &mut progress, &mut current_step);

    // Test passes if no panic occurs
}

#[test]
fn test_distribution_fetch_progress() {
    let mut capture = TestProgressCapture::new();

    // Simulate distribution-specific fetch
    capture.set_message("Fetching distribution: temurin".to_string());
    capture.set_message("Querying API for temurin packages".to_string());
    capture.set_message("Processing 25 packages".to_string());
    capture.set_message("Updating cache with temurin data".to_string());
    capture.finish_with_message("Distribution fetch complete");

    assert_eq!(capture.message_count(), 5);
    assert!(capture.contains_message("temurin"));
    assert!(capture.contains_message("25 packages"));
}