r2x 0.0.30

A framework plugin manager for the r2x power systems modeling ecosystem.
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
use crate::common::GlobalOpts;
use crate::plugins::install::get_package_info;
use clap::Subcommand;
use colored::Colorize;
use r2x_config::Config;
use r2x_logger as logger;
use r2x_python::python_bridge::configure_python_venv;
use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::process::Command;

#[derive(Subcommand, Debug, Clone)]
pub enum ConfigAction {
    /// Display the current configuration values.
    Show,
    /// Update a configuration key (e.g. `r2x config set default-python-version 3.13`).
    Set { key: String, value: String },
    /// Show the config path or set it when `new_path` is provided.
    Path {
        /// Optional new config path to set
        new_path: Option<String>,
    },
    /// Reset configuration back to defaults.
    Reset {
        /// Skip confirmation prompt
        #[arg(short = 'y', long = "yes")]
        yes: bool,
    },
    /// Python version management
    #[command(subcommand)]
    Python(PythonAction),
    /// Virtual environment management
    #[command(subcommand)]
    Venv(VenvAction),
    /// Cache management
    #[command(subcommand)]
    Cache(CacheAction),
}

#[derive(Subcommand, Debug, Clone)]
pub enum PythonAction {
    /// Install a different Python version
    Install {
        /// Python version to install (e.g., 3.13, 3.12.1)
        version: Option<String>,
    },
    /// Get the Python executable path in the configured venv
    Path,
    /// Show the configured Python version and venv information
    Show,
}

#[derive(Subcommand, Debug, Clone)]
pub enum VenvAction {
    /// Create or recreate the virtual environment
    Create {
        /// Skip confirmation prompt
        #[arg(short = 'y', long = "yes")]
        yes: bool,
    },
    /// Get or set the venv path
    Path {
        /// Optional new venv path to set
        new_path: Option<String>,
    },
}

#[derive(Subcommand, Debug, Clone)]
pub enum CacheAction {
    /// Clean the cache folder
    Clean,
    /// Get or set cache path
    Path {
        /// Optional new cache path to set
        new_path: Option<String>,
    },
}

pub fn handle_config(action: Option<ConfigAction>, opts: GlobalOpts) {
    let action = if let Some(action) = action {
        action
    } else {
        println!(
            "{}",
            "Tip: run `r2x config show` to inspect settings or `r2x config set <key> <value>` to update them."
                .dimmed()
        );
        return;
    };

    match action {
        ConfigAction::Show => match Config::load() {
            Ok(config) => {
                println!("{}", "Configuration:".bold().green());

                // Show Python version (explicit or default)
                let python_version = config.python_version.as_deref().unwrap_or("3.12");
                let python_suffix = if config.python_version.is_none() {
                    " (default)"
                } else {
                    ""
                };
                println!(
                    "  {}: {}{}",
                    "python-version".cyan(),
                    python_version,
                    python_suffix.dimmed()
                );

                // Show venv path (computed)
                let venv_path = config.get_venv_path();
                let venv_suffix = if config.venv_path.is_some() {
                    ""
                } else {
                    " (default)"
                };
                println!(
                    "  {}: {}{}",
                    "venv-path".cyan(),
                    venv_path,
                    venv_suffix.dimmed()
                );

                // Show cache path (computed)
                let cache_path = config.get_cache_path();
                let cache_suffix = if config.cache_path.is_some() {
                    ""
                } else {
                    " (default)"
                };
                println!(
                    "  {}: {}{}",
                    "cache-path".cyan(),
                    cache_path,
                    cache_suffix.dimmed()
                );

                // Show log file location
                if let Some(log_path) = r2x_logger::get_log_path() {
                    println!("  {}: {}", "log-file".cyan(), log_path.display());
                }

                // Show other explicit config values
                if let Some(ref uv) = config.uv_path {
                    println!("  {}: {}", "uv-path".cyan(), uv);
                }
                if let Some(ref core_ver) = config.r2x_core_version {
                    println!("  {}: {}", "r2x-core-version".cyan(), core_ver);
                }
                if let Some(log_python) = config.log_python {
                    println!("  {}: {}", "log-python".cyan(), log_python);
                }
                if let Some(no_stdout) = config.no_stdout {
                    println!("  {}: {}", "no-stdout".cyan(), no_stdout);
                }
                if let Some(ref log_path) = config.log_path {
                    println!("  {}: {}", "log-path".cyan(), log_path);
                }
                if let Some(log_max_size) = config.log_max_size {
                    println!("  {}: {}", "log-max-size".cyan(), log_max_size);
                }

                // Show installed r2x-core version
                let python_path = config.get_venv_python_path();
                if PathBuf::from(&python_path).exists() {
                    // Try to get uv_path from config, or use "uv" from PATH
                    let uv_path = config.uv_path.as_deref().unwrap_or("uv");
                    match get_package_info(uv_path, &python_path, "r2x-core") {
                        Ok((Some(version), _)) => {
                            println!("  {}: {}", "r2x-core-version".cyan(), version);
                        }
                        Ok((None, _)) => {
                            println!("  {}: {}", "r2x-core-version".cyan(), "not found".dimmed());
                        }
                        Err(_) => {
                            logger::debug("Could not query r2x-core package info");
                        }
                    }
                } else {
                    logger::debug("Venv does not exist, skipping r2x-core version check");
                }
            }
            Err(e) => {
                logger::error(&format!("Failed to load config: {}", e));
            }
        },
        ConfigAction::Set { key, value } => match Config::load() {
            Ok(mut config) => {
                if config.get(&key).is_some()
                    || matches!(
                        key.as_str(),
                        "cache-path"
                            | "verbosity"
                            | "python-version"
                            | "venv-path"
                            | "r2x-core-version"
                            | "log-python"
                            | "no-stdout"
                            | "log-path"
                            | "log-max-size"
                    )
                {
                    config.set(&key, value.clone());
                    match config.save() {
                        Ok(()) => {
                            logger::success(&format!("Set {} = {}", key, value));
                        }
                        Err(e) => {
                            logger::error(&format!("Failed to save config: {}", e));
                        }
                    }
                    println!(
                        "{}",
                        "Tip: run `r2x config show` to confirm the updated value.".dimmed()
                    );
                } else {
                    logger::error(&format!(
                        "Unknown config key: {}. Currently supported keys: cache-path, verbosity, python-version, venv-path, r2x-core-version, log-python, no-stdout, log-path, log-max-size",
                        key
                    ));
                }
            }
            Err(e) => {
                logger::error(&format!("Failed to load config: {}", e));
            }
        },
        ConfigAction::Path { new_path } => {
            // Show or set the configuration file path.
            // When `new_path` is provided, write it to a pointer file next to the default config dir.
            // When omitted, print the current resolved config path.
            let config_path = Config::path();
            logger::debug(&format!("Reading config from: {}", config_path.display()));

            if let Some(p) = new_path {
                // Pointer file path: same directory as default config, file named `.r2x_config_path`
                let pointer_path = config_path
                    .parent()
                    .unwrap_or_else(|| std::path::Path::new("."))
                    .join(".r2x_config_path");

                // Ensure pointer directory exists
                if let Some(parent) = pointer_path.parent() {
                    if let Err(e) = std::fs::create_dir_all(parent) {
                        logger::error(&format!("Failed to set config path: {}", e));
                        return;
                    }
                }

                if let Err(e) = std::fs::write(&pointer_path, p.as_bytes()) {
                    logger::error(&format!("Failed to set config path: {}", e));
                    return;
                }

                logger::success(&format!("Config path set to {}", p));
            } else {
                // Print the resolved config path
                println!("{}", config_path.display());

                // If pointer file exists, also show the override
                let pointer_path = config_path
                    .parent()
                    .unwrap_or_else(|| std::path::Path::new("."))
                    .join(".r2x_config_path");
                if pointer_path.exists() {
                    if let Ok(contents) = std::fs::read_to_string(&pointer_path) {
                        let trimmed = contents.trim();
                        if !trimmed.is_empty() {
                            println!("{} {}", "overridden-by".cyan(), trimmed);
                        }
                    }
                }
            }
        }
        ConfigAction::Reset { yes } => {
            let config_path = Config::path();
            if !yes {
                print!(
                    "{} Reset R2X configuration at `{}` to default settings? {} ",
                    "?".bold().cyan(),
                    config_path.display(),
                    "[y/n] ›".dimmed()
                );
                if let Err(e) = io::stdout().flush() {
                    logger::error(&format!("Failed to flush stdout: {}", e));
                    return;
                }
                let mut input = String::new();
                match io::stdin().read_line(&mut input) {
                    Ok(_) => {
                        let response = input.trim().to_lowercase();
                        if response != "y" && response != "yes" {
                            println!("{}", "Reset cancelled.".yellow());
                            return;
                        }
                    }
                    Err(e) => {
                        logger::error(&format!("Failed to read confirmation: {}", e));
                        return;
                    }
                }
            }

            if opts.verbosity_level() > 0 {
                logger::step("Resetting configuration to defaults");
            }
            match Config::reset() {
                Ok(()) => {
                    println!(
                        "{} configuration {} has been reset to default settings.",
                        "\u{2714}".green().bold(),
                        config_path.display()
                    );
                }
                Err(e) => {
                    logger::error(&format!("Failed to reset config: {}", e));
                }
            }
        }
        ConfigAction::Python(python_action) => {
            handle_python(python_action, opts);
        }
        ConfigAction::Venv(venv_action) => {
            handle_venv(venv_action, opts);
        }
        ConfigAction::Cache(cache_action) => {
            handle_cache(cache_action, opts);
        }
    }
}

/// Handle Python version management
pub fn handle_python(action: PythonAction, opts: GlobalOpts) {
    match action {
        PythonAction::Show => {
            handle_python_show(opts);
        }
        PythonAction::Path => {
            handle_python_path(opts);
        }
        PythonAction::Install { version } => {
            handle_python_install(version, opts);
        }
    }
}

/// Handle virtual environment management
fn handle_venv(action: VenvAction, opts: GlobalOpts) {
    match action {
        VenvAction::Create { yes } => {
            handle_venv_create(yes);
        }
        VenvAction::Path { new_path } => {
            handle_venv_path(new_path, opts);
        }
    }
}

/// Handle cache management
fn handle_cache(action: CacheAction, opts: GlobalOpts) {
    match action {
        CacheAction::Clean => {
            clean_cache(opts);
        }
        CacheAction::Path { new_path } => {
            handle_cache_path(new_path, opts);
        }
    }
}

/// Install a specific Python version
fn handle_python_install(version: Option<String>, _opts: GlobalOpts) {
    logger::debug("Handling Python install command");
    match Config::load() {
        Ok(mut config) => {
            let version_str = version
                .or_else(|| config.python_version.clone())
                .unwrap_or_else(|| "3.12".to_string());

            config.python_version = Some(version_str.clone());
            if let Err(e) = config.save() {
                logger::error(&format!("Failed to save config: {}", e));
                return;
            }

            let venv_path = config.get_venv_path();
            logger::step(&format!(
                "Installing Python {} and creating venv...",
                version_str
            ));
            if let Err(e) = remove_existing_venv(&venv_path) {
                logger::error(&e);
                return;
            }

            match configure_python_venv() {
                Ok(python_env) => {
                    logger::info(&format!(
                        "Configuration saved with Python version {}",
                        version_str
                    ));
                    if let Some(actual_version) = verify_python_version(&python_env.interpreter) {
                        logger::success(&format!(
                            "Python {} installed (reported {}). Venv ready at {}",
                            version_str,
                            actual_version,
                            PathBuf::from(&venv_path).display()
                        ));
                    } else {
                        logger::success(&format!(
                            "Python {} installed and venv created at {}",
                            version_str, venv_path
                        ));
                    }
                }
                Err(e) => {
                    logger::error(&format!("Failed to configure Python environment: {}", e));
                }
            }
        }
        Err(e) => {
            logger::error(&format!("Failed to load config: {}", e));
        }
    }
}

/// Output the Python executable path
fn handle_python_path(_opts: GlobalOpts) {
    logger::debug("Handling python path command");
    match Config::load() {
        Ok(config) => {
            println!("{}", config.get_venv_python_path());
        }
        Err(e) => {
            logger::error(&format!("Failed to load config: {}", e));
        }
    }
}

fn handle_venv_create(skip_confirmation: bool) {
    logger::debug(&format!(
        "Handling venv create command (skip_confirmation: {})",
        skip_confirmation
    ));
    match Config::load() {
        Ok(config) => {
            let venv_path = config.get_venv_path();
            let venv_dir = PathBuf::from(&venv_path);

            if venv_dir.exists() {
                let should_skip = skip_confirmation || std::env::var("R2X_VENV_YES").is_ok();

                if should_skip {
                    logger::debug("Skipping confirmation (--yes flag or R2X_VENV_YES set)");
                } else {
                    print!(
                        "{} A virtual environment already exists at `{}`. Do you want to replace it? {} ",
                        "?".bold().cyan(),
                        venv_path,
                        "[y/n] ›".dimmed()
                    );
                    let _ = io::stdout().flush();
                    logger::debug("Prompting user for venv replacement confirmation");

                    let mut response = String::new();
                    if io::stdin().read_line(&mut response).is_ok() {
                        let response = response.trim().to_lowercase();
                        if response != "y" && response != "yes" {
                            logger::info("Operation cancelled by user");
                            println!("Operation cancelled.");
                            return;
                        }
                        logger::debug("User confirmed venv replacement");
                    } else {
                        logger::error("Failed to read input");
                        return;
                    }
                }

                if let Err(e) = remove_existing_venv(&venv_path) {
                    logger::error(&e);
                    return;
                }
            }

            match configure_python_venv() {
                Ok(python_env) => {
                    logger::success(&format!(
                        "Virtual environment ready at {} (python {})",
                        venv_path,
                        python_env.interpreter.display()
                    ));
                }
                Err(e) => logger::error(&format!("Failed to configure venv: {}", e)),
            }

            if !skip_confirmation && std::env::var("R2X_VENV_YES").is_err() {
                println!(
                    "\n{} Use the `{}` flag or set `{}` to skip this prompt",
                    "hint:".dimmed(),
                    "-y/--yes".bold(),
                    "R2X_VENV_YES=1".bold()
                );
            }
        }
        Err(e) => {
            logger::error(&format!("Failed to load config: {}", e));
        }
    }
}

fn handle_venv_path(new_path: Option<String>, _opts: GlobalOpts) {
    logger::debug("Handling venv path command");
    match Config::load() {
        Ok(mut config) => {
            // Ensure uv is installed first
            if let Err(e) = config.ensure_uv_path() {
                logger::error(&format!("Failed to setup uv: {}", e));
                return;
            }

            if let Some(path) = new_path {
                logger::debug(&format!("Setting venv path to: {}", path));
                let venv_path = PathBuf::from(&path);

                if !venv_path.exists() {
                    logger::error(&format!("Path does not exist: {}", path));
                    return;
                }

                if !is_valid_venv(&venv_path) {
                    logger::error(&format!("Path is not a valid venv: {}", path));
                    return;
                }

                config.venv_path = Some(path.clone());
                if let Err(e) = config.save() {
                    logger::error(&format!("Failed to save config: {}", e));
                    return;
                }

                logger::success(&format!("Venv path set to {}", path));
            } else {
                let venv_path = config.get_venv_path();
                logger::debug(&format!("Current venv path: {}", venv_path));

                if !PathBuf::from(&venv_path).exists() {
                    logger::error(&format!("Venv path does not exist: {}", venv_path));
                    return;
                }

                if !is_valid_venv(&PathBuf::from(&venv_path)) {
                    logger::error(&format!("Venv path is not a valid venv: {}", venv_path));
                    return;
                }

                println!("{}", venv_path);
            }
        }
        Err(e) => {
            logger::error(&format!("Failed to load config: {}", e));
        }
    }
}

// Simple check to avoid people setting virtual environments to not executable folders.
fn is_valid_venv(path: &Path) -> bool {
    logger::debug(&format!("Validating venv at: {}", path.display()));
    if !path.exists() || !path.is_dir() {
        logger::debug("Path does not exist or is not a directory");
        return false;
    }

    let bin_dir = if cfg!(windows) {
        path.join("Scripts")
    } else {
        path.join("bin")
    };

    bin_dir.exists() && bin_dir.is_dir()
}

fn remove_existing_venv(venv_path: &str) -> Result<(), String> {
    let venv_dir = PathBuf::from(venv_path);
    if venv_dir.exists() {
        logger::debug(&format!("Removing existing venv at {}", venv_path));
        fs::remove_dir_all(&venv_dir)
            .map_err(|e| format!("Failed to remove existing venv: {}", e))?;
    }
    Ok(())
}

fn verify_python_version(python_path: &Path) -> Option<String> {
    if !python_path.exists() {
        return None;
    }

    match Command::new(python_path).args(["--version"]).output() {
        Ok(output) if output.status.success() => {
            let raw = if output.stdout.is_empty() {
                output.stderr
            } else {
                output.stdout
            };
            Some(String::from_utf8_lossy(&raw).trim().to_string())
        }
        _ => None,
    }
}

fn handle_python_show(_opts: GlobalOpts) {
    logger::debug("Handling python show command");
    match Config::load() {
        Ok(config) => {
            let version = config.python_version.as_deref().unwrap_or("not configured");

            let venv_path = config.get_venv_path();
            let python_path = PathBuf::from(config.get_venv_python_path());
            let venv_exists = python_path.exists();

            let mut actual_version_str = String::new();
            let mut version_mismatch = false;
            if venv_exists {
                if let Some(actual_version) = verify_python_version(&python_path) {
                    actual_version_str.clone_from(&actual_version);

                    if let Some(version_num) = actual_version.split_whitespace().nth(1) {
                        let configured_short =
                            version.split('.').take(2).collect::<Vec<_>>().join(".");
                        let actual_short =
                            version_num.split('.').take(2).collect::<Vec<_>>().join(".");
                        if configured_short != actual_short && version != "not configured" {
                            version_mismatch = true;
                        }
                    }
                } else {
                    logger::debug("Could not determine actual Python version");
                }
            }

            // Show warning first if there's a version mismatch
            if version_mismatch {
                logger::warn(&format!(
                    "Version mismatch: config has {}, venv has {}. Run 'r2x config venv create --yes' to recreate.",
                    version, actual_version_str.trim()
                ));
            }

            println!("{}", "Python Configuration:".bold().green());
            println!("  version: {}", version);
            println!("  venv path: {}", venv_path);
            println!("  venv exists: {}", if venv_exists { "yes" } else { "no" });
            if !actual_version_str.is_empty() {
                println!("  Actual venv version: {}", actual_version_str.trim());
            }
        }
        Err(e) => {
            logger::error(&format!("Failed to load config: {}", e));
        }
    }
}

fn clean_cache(_opts: GlobalOpts) {
    match Config::load() {
        Ok(config) => {
            let cache_path = config.get_cache_path();
            let cache_dir = PathBuf::from(&cache_path);

            if !cache_dir.exists() {
                logger::debug("Cache folder already clean");
                return;
            }

            match fs::remove_dir_all(&cache_dir) {
                Ok(()) => {
                    logger::success("Cache folder cleaned");
                }
                Err(e) => {
                    logger::error(&format!("Failed to clean cache folder: {}", e));
                }
            }
        }
        Err(e) => {
            logger::error(&format!("Failed to load config: {}", e));
        }
    }
}

fn handle_cache_path(new_path: Option<String>, _opts: GlobalOpts) {
    match Config::load() {
        Ok(mut config) => {
            if let Some(path) = new_path {
                let cache_path = PathBuf::from(&path);

                if let Err(e) = fs::create_dir_all(&cache_path) {
                    logger::error(&format!("Failed to create cache directory: {}", e));
                    return;
                }

                config.cache_path = Some(path.clone());
                if let Err(e) = config.save() {
                    logger::error(&format!("Failed to save config: {}", e));
                    return;
                }

                logger::success(&format!("Cache path set to {}", path));
            } else {
                let cache_path = config.get_cache_path();
                println!("{}", cache_path);
            }
        }
        Err(e) => {
            logger::error(&format!("Failed to load config: {}", e));
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::commands::config::*;

    /// Serialize env-mutating tests to avoid races on R2X_CONFIG.
    static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    /// Point R2X_CONFIG to a temp file so mutating tests don't touch the real config
    /// or create stray directories (e.g. "test-value/") in the working directory.
    fn with_temp_config(f: impl FnOnce()) {
        let _guard = ENV_LOCK.lock();
        let Ok(dir) = tempfile::tempdir() else {
            return;
        };
        let config_path = dir.path().join("config.toml");
        std::env::set_var("R2X_CONFIG", &config_path);
        f();
        std::env::remove_var("R2X_CONFIG");
    }

    fn quiet_opts() -> GlobalOpts {
        GlobalOpts {
            quiet: 1,
            verbose: 0,
            log_python: false,
            no_stdout: false,
        }
    }

    fn verbose_opts() -> GlobalOpts {
        GlobalOpts {
            quiet: 0,
            verbose: 1,
            log_python: false,
            no_stdout: false,
        }
    }

    fn normal_opts() -> GlobalOpts {
        GlobalOpts {
            quiet: 0,
            verbose: 0,
            log_python: false,
            no_stdout: false,
        }
    }

    #[test]
    fn test_config_show() {
        handle_config(Some(ConfigAction::Show), normal_opts());
    }

    #[test]
    fn test_config_set() {
        with_temp_config(|| {
            handle_config(
                Some(ConfigAction::Set {
                    key: "cache-path".to_string(),
                    value: "test-value".to_string(),
                }),
                normal_opts(),
            );
        });
    }

    #[test]
    fn test_config_set_quiet() {
        with_temp_config(|| {
            handle_config(
                Some(ConfigAction::Set {
                    key: "cache-path".to_string(),
                    value: "test-value".to_string(),
                }),
                quiet_opts(),
            );
        });
    }

    #[test]
    fn test_config_set_verbose() {
        with_temp_config(|| {
            handle_config(
                Some(ConfigAction::Set {
                    key: "cache-path".to_string(),
                    value: "test-value".to_string(),
                }),
                verbose_opts(),
            );
        });
    }

    #[test]
    fn test_config_reset() {
        with_temp_config(|| {
            handle_config(Some(ConfigAction::Reset { yes: true }), normal_opts());
        });
    }

    #[test]
    fn test_config_no_action_tip() {
        handle_config(None, normal_opts());
    }
}