pmpx 0.1.0

One command surface for a project's package managers. Detects the project type, routes the verb, and spawns the real tool (cargo, pnpm, ...).
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
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
//! Subcommand handling.
//!
//! This layer only does "read the context -> do the work -> print"; the decision logic lives
//! in [`crate::app`] and below.

use std::collections::BTreeMap;
use std::ffi::OsString;
use std::path::{Path, PathBuf};

use anyhow::{Context as _, Result};
use clap::CommandFactory;
use pmpx_plugin::Family;

use crate::app::{self, Session};
use crate::cli::{Cli, Command, ConfigCommand, PluginCommand};
use crate::config::ProjectConfig;
use crate::detect::{self, FamilyScore, ScoredPlugin};
use crate::error::{PmpxError, EXIT_OK};
use crate::plugins::InstalledPlugin;
use crate::runtime::Backend;
use crate::style;

/// Dispatch by argv.
pub fn dispatch(args: &Cli) -> crate::error::Result<u8> {
    let Some(command) = &args.command else {
        return show_detection(args);
    };

    match command {
        Command::Install { packages } => {
            run_verb(args, pmpx_plugin::Verb::Install, packages.clone(), false)
        }
        Command::Remove { packages } => {
            run_verb(args, pmpx_plugin::Verb::Remove, packages.clone(), false)
        }
        Command::Update { packages } => {
            run_verb(args, pmpx_plugin::Verb::Update, packages.clone(), false)
        }
        Command::Build { args: rest } => {
            run_verb(args, pmpx_plugin::Verb::Build, rest.clone(), false)
        }
        Command::Test { args: rest } => {
            run_verb(args, pmpx_plugin::Verb::Test, rest.clone(), false)
        }

        Command::Run { target, args: rest } => {
            // `pmpx run <target> -- <args>`: the target and what follows `--` go to the
            // plugin together; how to arrange them is up to the plugin (cargo, for example,
            // uses `cargo run -- ...`).
            let argv: Vec<OsString> = target.iter().cloned().chain(rest.iter().cloned()).collect();
            run_verb(args, pmpx_plugin::Verb::Run, argv, false)
        }

        // `exec` is the only verb allowed to degrade
        Command::Exec { command } => run_verb(args, pmpx_plugin::Verb::Exec, command.clone(), true),

        Command::Info => info(args),

        Command::Plugin(sub) => plugin_cmd(args, sub),
        Command::Config(sub) => config_cmd(sub),
        Command::Completion { shell } => completion(*shell),
    }
}

/// The shared verb entry point: open a session and hand over to [`app::run_verb`].
fn run_verb(
    args: &Cli,
    verb: pmpx_plugin::Verb,
    argv: Vec<OsString>,
    allow_exec_fallback: bool,
) -> crate::error::Result<u8> {
    let session = Session::open(args).map_err(PmpxError::Other)?;
    app::run_verb(&session, verb, &argv, allow_exec_fallback)
}

// ---------------------------------------------------------------------------
// No subcommand: show the detection result
// ---------------------------------------------------------------------------

/// Bare `pmpx`: state what this directory is and which backend will run.
fn show_detection(args: &Cli) -> crate::error::Result<u8> {
    let session = Session::open(args).map_err(PmpxError::Other)?;

    let Some(root) = session.project_root().map(PathBuf::from) else {
        return Err(session.no_project_error());
    };

    let selection = session.select(&root).map_err(PmpxError::from)?;

    session.emit_notes(&selection);

    anstream::println!(
        "{}  {}",
        style::label(12, "Project root"),
        style::paint(style::DIM, root.display())
    );
    anstream::println!(
        "{}  {}",
        style::label(12, "Family"),
        selection.family.display()
    );
    anstream::println!(
        "{}  {} (score {})",
        style::label(12, "Plugin"),
        style::paint(style::PM, &selection.name),
        selection.score
    );
    anstream::println!();
    anstream::println!(
        "{}",
        style::paint(
            style::DIM,
            "Use `pmpx info` to see every candidate and score."
        )
    );

    Ok(EXIT_OK)
}

// ---------------------------------------------------------------------------
// info
// ---------------------------------------------------------------------------

/// `pmpx info`: lay out the whole detection process.
///
/// Like `plugin current`, it always lists every candidate and score -- that is what makes
/// ambiguity visible.
fn info(args: &Cli) -> crate::error::Result<u8> {
    let session = Session::open(args).map_err(PmpxError::Other)?;

    anstream::println!(
        "{}  {}",
        style::label(12, "Start"),
        style::paint(style::DIM, session.start_dir.display())
    );
    match session.project_root() {
        Some(root) => anstream::println!(
            "{}  {}",
            style::label(12, "Project root"),
            style::paint(style::DIM, root.display())
        ),
        None => anstream::println!("{}  (not found)", style::label(12, "Project root")),
    }
    anstream::println!(
        "{}  {}, stopped because: {}",
        style::label(12, "Walk-up"),
        crate::discovery::dirs(session.walk.dirs.len()),
        session
            .walk
            .stopped
            .describe(session.global.discovery.max_depth)
    );

    if session.project.sources.is_empty() {
        anstream::println!("{}  (none)", style::label(12, "Project config"));
    } else {
        anstream::println!(
            "{}  (nearest first, nearest wins)",
            style::label(12, "Project config")
        );
        for p in &session.project.sources {
            anstream::println!("              {}", style::paint(style::DIM, p.display()));
        }
    }
    for (family, plugin) in &session.project.plugin {
        anstream::println!(
            "  {}  {family} = \"{}\"",
            style::label(10, "pinned"),
            style::paint(style::PM, plugin)
        );
    }

    anstream::println!();

    if session.plugins.plugins.is_empty() {
        anstream::println!("{}  (none)", style::label(12, "Installed plugins"));
        anstream::println!();
        anstream::println!(
            "{}",
            style::paint(style::ERROR_BODY, session.no_project_error())
        );
        return Ok(EXIT_OK);
    }

    anstream::println!("Installed plugins");
    for p in &session.plugins.plugins {
        match p.problem() {
            None => anstream::println!(
                "  {} {:<8} v{}",
                style::padded(style::PM, 10, &p.name),
                p.family.as_ref().map(Family::as_str).unwrap_or("?"),
                style::paint(style::DIM, &p.version)
            ),
            Some(why) => anstream::println!(
                "  {} ⚠ {}",
                style::padded(style::PM, 10, &p.name),
                style::paint(style::DIM, why)
            ),
        }
    }
    anstream::println!();

    let Some(root) = session.project_root().map(PathBuf::from) else {
        anstream::println!(
            "{}",
            style::paint(style::DIM, "(no project root, cannot score)")
        );
        return Ok(EXIT_OK);
    };

    let families = detect::score_all(&session.plugins, &root, &session.project);

    if families.is_empty() {
        anstream::println!(
            "{}  (no plugin can take part in the resolution)",
            style::label(12, "Candidates")
        );
        return Ok(EXIT_OK);
    }

    anstream::println!("Candidates and scores");
    let mut rows: Vec<&FamilyScore> = families.values().collect();
    rows.sort_by(|a, b| {
        b.score
            .cmp(&a.score)
            .then_with(|| a.family.as_str().cmp(b.family.as_str()))
    });

    for fs in rows {
        let pin = if fs.pinned {
            "  [pinned in .pmpx.toml]"
        } else {
            ""
        };
        anstream::println!("  {}  score {}{pin}", fs.family.display(), fs.score);

        for p in &fs.plugins {
            let hits = p.all_hits().collect::<Vec<_>>().join(", ");
            let detail = if hits.is_empty() {
                "(no match)".to_string()
            } else {
                hits
            };
            anstream::println!(
                "    {} score {:>4}   {}",
                style::padded(style::PM, 8, &p.name),
                p.score,
                style::paint(style::DIM, detail)
            );
        }
    }
    anstream::println!();

    // The resolution result. The scores below are the ones this command already computed, so the
    // decision costs no further filesystem work.
    match session.select_from(&root, &families) {
        Ok(selection) => {
            session.emit_notes(&selection);
            anstream::println!(
                "{}  {} ({})",
                style::label(12, "Selected"),
                style::paint(style::PM, &selection.name),
                selection.crate_name
            );

            match session.load_backend(&selection) {
                Ok(backend) => {
                    let d = backend.diagnostics();
                    anstream::println!(
                        "  {} {}",
                        style::label(15, "reported name"),
                        style::paint(style::PM, &d.name)
                    );
                    anstream::println!("  {} {}", style::label(15, "reported family"), d.family);
                    anstream::println!(
                        "  {} {}",
                        style::label(15, "compiled with"),
                        style::paint(style::DIM, d.rustc_version)
                    );
                    anstream::println!(
                        "  {} {}",
                        style::label(15, "target"),
                        style::paint(style::DIM, d.target)
                    );

                    if d.family != selection.family.as_str() {
                        anstream::println!(
                            "  {}",
                            style::paint(
                                style::DIM,
                                format!(
                                    "⚠ the manifest says it is {}, it says it is {} -- was the \
                                     manifest edited?",
                                    selection.family.as_str(),
                                    d.family
                                )
                            )
                        );
                    }
                }
                Err(e) => anstream::println!(
                    "  {}",
                    style::paint(style::DIM, format!("⚠ failed to load: {e}"))
                ),
            }
        }
        Err(failure) => anstream::println!(
            "{}  (nothing selected)\n{}",
            style::label(12, "Selected"),
            style::paint(style::ERROR_BODY, failure.message())
        ),
    }

    Ok(EXIT_OK)
}

// ---------------------------------------------------------------------------
// plugin
// ---------------------------------------------------------------------------

fn plugin_cmd(args: &Cli, cmd: &PluginCommand) -> crate::error::Result<u8> {
    match cmd {
        PluginCommand::Ls { flat } => plugin_ls(args, *flat),
        PluginCommand::Current => plugin_current(args),
        PluginCommand::Set { name } => plugin_set(args, name),
        PluginCommand::Unset { family, yes } => plugin_unset(args, family.as_deref(), *yes),
        PluginCommand::Add { names, version } => plugin_add(args, names, version.as_deref()),
        PluginCommand::Rm { names } => plugin_rm(args, names),
        PluginCommand::Update { names, version } => plugin_update(args, names, version.as_deref()),
        PluginCommand::Search { keyword, limit } => plugin_search(args, keyword, *limit),
        PluginCommand::Info { name } => plugin_info(args, name),
    }
}

/// `plugin ls`: list grouped by family.
fn plugin_ls(args: &Cli, flat: bool) -> crate::error::Result<u8> {
    let session = Session::open(args).map_err(PmpxError::Other)?;

    if session.plugins.plugins.is_empty() {
        anstream::println!("No plugins are installed.");
        anstream::println!();
        anstream::println!(
            "{}",
            style::paint(
                style::DIM,
                "Install one with `pmpx plugin add <name>`, for example `pmpx plugin add cargo`."
            )
        );
        return Ok(EXIT_OK);
    }

    if flat {
        for p in &session.plugins.plugins {
            print_plugin_row(p);
        }
        return Ok(EXIT_OK);
    }

    // Group in one pass. `BTreeMap` supplies the family name order, and the bucket for plugins that
    // declare no family is printed last rather than wherever `Option`'s ordering would put it.
    let mut grouped: BTreeMap<Option<&Family>, Vec<&InstalledPlugin>> = BTreeMap::new();
    for p in &session.plugins.plugins {
        grouped.entry(p.family.as_ref()).or_default().push(p);
    }

    for (family, plugins) in &grouped {
        if let Some(family) = family {
            print_family_group(family.display(), plugins);
        }
    }
    if let Some(plugins) = grouped.get(&None) {
        print_family_group("(no family declared)", plugins);
    }

    Ok(EXIT_OK)
}

/// One `plugin ls` section: a header and its rows, indented by one level.
fn print_family_group(title: &str, plugins: &[&InstalledPlugin]) {
    anstream::println!("{}", style::paint(style::LABEL, title));
    for p in plugins {
        anstream::print!("  ");
        print_plugin_row(p);
    }
}

fn print_plugin_row(p: &InstalledPlugin) {
    match p.problem() {
        None => anstream::println!(
            "{} v{} {:<28} {}",
            style::padded(style::PM, 10, &p.name),
            style::padded(style::DIM, 10, &p.version),
            p.crate_name,
            style::paint(style::DIM, p.dir.display())
        ),
        Some(why) => anstream::println!(
            "{} ⚠ {}",
            style::padded(style::PM, 10, &p.name),
            style::paint(style::DIM, why)
        ),
    }
}

/// `plugin current`: the current plugin per family, plus candidates and scores.
fn plugin_current(args: &Cli) -> crate::error::Result<u8> {
    let session = Session::open(args).map_err(PmpxError::Other)?;
    let Some(root) = session.project_root().map(PathBuf::from) else {
        return Err(session.no_project_error());
    };

    let families = detect::score_all(&session.plugins, &root, &session.project);
    if families.is_empty() {
        anstream::println!("No plugin can take part in the resolution.");
        return Ok(EXIT_OK);
    }

    let selection = session.select_from(&root, &families).ok();

    for (family, fs) in &families {
        let current = selection
            .as_ref()
            .filter(|s| &s.family == family)
            .map(|s| s.name.as_str());

        anstream::println!("{}", style::paint(style::LABEL, family.display()));
        let mut ranked: Vec<&ScoredPlugin> = fs.plugins.iter().collect();
        ranked.sort_by(|a, b| b.score.cmp(&a.score).then_with(|| a.name.cmp(&b.name)));

        for p in ranked {
            let mark = if Some(p.name.as_str()) == current {
                "←"
            } else {
                " "
            };
            anstream::println!(
                "  {} {} score {:>4}",
                mark,
                style::padded(style::PM, 8, &p.name),
                p.score
            );
        }
        if let Some(pinned) = session.project.pinned_plugin(family.as_str()) {
            anstream::println!(
                "  {} {}",
                style::paint(style::LABEL, "pinned:"),
                style::paint(style::PM, pinned)
            );
        }
        anstream::println!();
    }

    Ok(EXIT_OK)
}

/// `plugin set <name>`: pin it in the nearest layer of `.pmpx.toml`.
fn plugin_set(args: &Cli, name: &str) -> crate::error::Result<u8> {
    let session = Session::open(args).map_err(PmpxError::Other)?;

    let Some(plugin) = session.plugins.by_name(name) else {
        return Err(PmpxError::not_found(format!(
            "no plugin named {name}. Installed: {}",
            session
                .plugins
                .usable()
                .map(|p| p.name.clone())
                .collect::<Vec<_>>()
                .join(", ")
        )));
    };

    let Some(family) = plugin.family.clone() else {
        return Err(PmpxError::Usage(format!(
            "{name}'s manifest declares no family, so it cannot be pinned."
        )));
    };

    let path = target_config_path(&session);
    let current = ProjectConfig::load_from(&path)
        .map_err(PmpxError::Other)?
        .unwrap_or_default();
    edit_project_config(&path, current, |cfg| {
        cfg.plugin
            .insert(family.as_str().to_string(), plugin.name.clone());
    })
    .map_err(PmpxError::Other)?;

    anstream::println!(
        "Pinned {} = \"{}\" in {}",
        family.as_str(),
        style::paint(style::PM, &plugin.name),
        style::paint(style::DIM, path.display())
    );
    Ok(EXIT_OK)
}

/// `plugin unset [family] [--yes]`
fn plugin_unset(args: &Cli, family: Option<&str>, yes: bool) -> crate::error::Result<u8> {
    let session = Session::open(args).map_err(PmpxError::Other)?;
    let path = target_config_path(&session);

    let existing = ProjectConfig::load_from(&path)
        .map_err(PmpxError::Other)?
        .unwrap_or_default();

    match family {
        Some(f) => {
            if !existing.plugin.contains_key(f) {
                return Err(PmpxError::Usage(format!(
                    "{} has no pin for {f}",
                    path.display()
                )));
            }
            edit_project_config(&path, existing, |cfg| {
                cfg.plugin.remove(f);
            })
            .map_err(PmpxError::Other)?;
            anstream::println!(
                "Removed the pin for {f} from {}",
                style::paint(style::DIM, path.display())
            );
        }

        None => {
            if existing.plugin.is_empty() {
                return Err(PmpxError::Usage(format!(
                    "{} has no pins at all",
                    path.display()
                )));
            }

            // With the family omitted and more than one pin present, `--yes` is required;
            // otherwise list what would be deleted and exit with code 2.
            if existing.plugin.len() > 1 && !yes {
                let mut msg = format!(
                    "{} has {} pins; deleting all of them needs `--yes`:",
                    path.display(),
                    existing.plugin.len()
                );
                for (f, p) in &existing.plugin {
                    msg.push_str(&format!("\n  {f} = \"{p}\""));
                }
                return Err(PmpxError::Usage(msg));
            }

            let removed: Vec<String> = existing.plugin.keys().cloned().collect();
            edit_project_config(&path, existing, |cfg| {
                cfg.plugin.clear();
            })
            .map_err(PmpxError::Other)?;
            anstream::println!(
                "Removed the pins for {} from {}",
                removed.join(", "),
                style::paint(style::DIM, path.display())
            );
        }
    }

    Ok(EXIT_OK)
}

/// Which `.pmpx.toml` to write.
///
/// The nearest layer wins: an existing file is the layer the user chose; when there is none,
/// write at the project root.
fn target_config_path(session: &Session) -> PathBuf {
    // `walk.dirs` goes from nearest to farthest
    for dir in &session.walk.dirs {
        let p = dir.join(".pmpx.toml");
        if p.is_file() {
            return p;
        }
    }

    let base = session
        .project_root()
        .map(PathBuf::from)
        .unwrap_or_else(|| session.start_dir.clone());
    base.join(".pmpx.toml")
}

/// Read-modify-write one `.pmpx.toml`, keeping keys it does not recognise.
///
/// `current` is the content the caller already read: passing it in keeps "what was inspected" and
/// "what is edited" the same document, and saves parsing the same file twice.
fn edit_project_config(
    path: &Path,
    current: ProjectConfig,
    edit: impl FnOnce(&mut ProjectConfig),
) -> Result<()> {
    let mut cfg = current;
    edit(&mut cfg);

    // Do not leave an empty file behind for an empty config
    if cfg.plugin.is_empty() && cfg.scripts.is_empty() && cfg.extra.is_empty() {
        if path.is_file() {
            std::fs::remove_file(path).with_context(|| {
                format!("failed to delete the empty config file: {}", path.display())
            })?;
        }
        return Ok(());
    }

    let text = toml::to_string_pretty(&cfg).context("failed to serialise the project config")?;
    std::fs::write(path, text)
        .with_context(|| format!("failed to write the project config: {}", path.display()))
}

/// `plugin add`
fn plugin_add(args: &Cli, names: &[String], version: Option<&str>) -> crate::error::Result<u8> {
    let session = Session::open(args).map_err(PmpxError::Other)?;

    if version.is_some() && names.len() > 1 {
        return Err(PmpxError::Usage(
            "--version can only be used with a single plugin name".to_string(),
        ));
    }

    for name in names {
        anstream::println!("Installing {}...", style::paint(style::PM, name));
        let installed = session.kit.install(name, version)?;

        anstream::println!(
            "  {} v{} ({}) -> {}",
            installed.crate_name,
            style::paint(style::DIM, installed.version),
            style::paint(style::DIM, describe_source(installed.source)),
            style::paint(style::DIM, installed.dir.display())
        );
    }

    Ok(EXIT_OK)
}

/// `plugin rm`
fn plugin_rm(args: &Cli, names: &[String]) -> crate::error::Result<u8> {
    let session = Session::open(args).map_err(PmpxError::Other)?;

    for name in names {
        session.kit.uninstall(name)?;
        anstream::println!("Removed {}", style::paint(style::PM, name));
    }

    Ok(EXIT_OK)
}

/// `plugin update`
fn plugin_update(args: &Cli, names: &[String], version: Option<&str>) -> crate::error::Result<u8> {
    let session = Session::open(args).map_err(PmpxError::Other)?;

    if version.is_some() && names.len() > 1 {
        return Err(PmpxError::Usage(
            "--version can only be used with a single plugin name".to_string(),
        ));
    }

    // No names = update all of them
    let targets: Vec<String> = if names.is_empty() {
        session.plugins.usable().map(|p| p.name.clone()).collect()
    } else {
        names.to_vec()
    };

    if targets.is_empty() {
        anstream::println!("No plugins to update.");
        return Ok(EXIT_OK);
    }

    for name in targets {
        let installed = session.kit.update(&name, version)?;
        anstream::println!(
            "{} -> v{}",
            installed.crate_name,
            style::paint(style::DIM, installed.version)
        );
    }

    Ok(EXIT_OK)
}

/// `plugin search` -- search crates.io.
fn plugin_search(args: &Cli, keyword: &str, limit: usize) -> crate::error::Result<u8> {
    let session = Session::open(args).map_err(PmpxError::Other)?;

    // The user types the short name (`cargo`) while crates.io has `pmpx-plugin-cargo`. Search
    // the short name directly: crates.io search is full text, so the `pmpx-plugin-` prefix is
    // not a keyword.
    let results = session.kit.search(keyword, limit)?;

    if results.is_empty() {
        anstream::println!("crates.io has no crate matching {keyword:?}.");
        return Ok(EXIT_OK);
    }

    for r in results {
        anstream::println!(
            "{:<32} v{} ↓{}",
            r.name,
            style::padded(style::DIM, 10, &r.version),
            r.downloads
        );
        if let Some(d) = r.description {
            anstream::println!("  {}", style::paint(style::DIM, d));
        }
    }

    Ok(EXIT_OK)
}

/// `plugin info <name>`: local install state plus crates.io information.
fn plugin_info(args: &Cli, name: &str) -> crate::error::Result<u8> {
    let session = Session::open(args).map_err(PmpxError::Other)?;

    let mut found = false;

    if let Some(p) = session.plugins.by_name(name) {
        found = true;
        anstream::println!("Installed");
        anstream::println!(
            "  {} {}",
            style::label(15, "reported name"),
            style::paint(style::PM, &p.name)
        );
        anstream::println!("  {} {}", style::label(15, "crate"), p.crate_name);
        anstream::println!(
            "  {} {}",
            style::label(15, "version"),
            style::paint(style::DIM, &p.version)
        );
        anstream::println!(
            "  {} {}",
            style::label(15, "family"),
            p.family
                .as_ref()
                .map(Family::as_str)
                .unwrap_or("(not declared)")
        );
        anstream::println!(
            "  {} {}",
            style::label(15, "ABI"),
            p.abi
                .map(|a| a.to_string())
                .unwrap_or_else(|| "(not declared)".into())
        );
        anstream::println!(
            "  {} {}",
            style::label(15, "directory"),
            style::paint(style::DIM, p.dir.display())
        );
        anstream::println!(
            "  {} {}",
            style::label(15, "strong evidence"),
            style::paint(style::DIM, join_or_dash(&p.strong))
        );
        anstream::println!(
            "  {} {}",
            style::label(15, "weak evidence"),
            style::paint(style::DIM, join_or_dash(&p.weak))
        );
        if let Some(why) = p.problem() {
            anstream::println!("  {}", style::paint(style::DIM, format!("⚠ {why}")));
        }
        anstream::println!();

        // The plugin record we already have is enough to load it -- no need to dress it up as a
        // detection result.
        if let Ok(backend) = Backend::load(&session.kit, p) {
            let d = backend.diagnostics();
            anstream::println!("Plugin reports");
            anstream::println!(
                "  {} {}",
                style::label(15, "name"),
                style::paint(style::PM, &d.name)
            );
            anstream::println!("  {} {}", style::label(15, "family"), d.family);
            anstream::println!(
                "  {} {}",
                style::label(15, "compiled with"),
                style::paint(style::DIM, d.rustc_version)
            );
            anstream::println!(
                "  {} {}",
                style::label(15, "target"),
                style::paint(style::DIM, d.target)
            );
            anstream::println!();
        }
    }

    // The crates.io side
    let crate_name = session.kit.config().normalize_crate_name(name);
    match session.kit.view(&crate_name) {
        Ok(Some(info)) => {
            found = true;
            anstream::println!("crates.io");
            anstream::println!("  {} {}", style::label(15, "crate"), info.name);
            anstream::println!(
                "  {} {}",
                style::label(15, "latest"),
                style::paint(style::DIM, info.version)
            );
            if let Some(d) = info.description {
                anstream::println!(
                    "  {} {}",
                    style::label(15, "description"),
                    style::paint(style::DIM, d)
                );
            }
            if let Some(r) = info.repository {
                anstream::println!(
                    "  {} {}",
                    style::label(15, "repository"),
                    style::paint(style::DIM, r)
                );
            }
        }
        Ok(None) => {
            if !found {
                anstream::println!("crates.io has no {crate_name}.");
            }
        }
        Err(e) => {
            // Being offline or having no network must not hide the local information
            anstream::eprintln!(
                "{} {}",
                style::paint(style::ERROR, "pmpx:"),
                style::paint(style::ERROR_BODY, format!("crates.io lookup failed: {e}"))
            );
        }
    }

    if !found {
        return Err(PmpxError::not_found(format!("no plugin named {name}.")));
    }

    Ok(EXIT_OK)
}

fn join_or_dash(items: &[String]) -> String {
    if items.is_empty() {
        "(none)".to_string()
    } else {
        items.join(", ")
    }
}

fn describe_source(source: crate_plugin_kit::cache::InstallSource) -> &'static str {
    match source {
        crate_plugin_kit::cache::InstallSource::Prebuilt => "prebuilt",
        crate_plugin_kit::cache::InstallSource::BuildHost => "built locally",
    }
}

// ---------------------------------------------------------------------------
// config
// ---------------------------------------------------------------------------

fn config_cmd(cmd: &ConfigCommand) -> crate::error::Result<u8> {
    let path = crate::config::global_config_path().map_err(PmpxError::Other)?;

    match cmd {
        ConfigCommand::Get { key } => {
            let doc = read_toml_table(&path).map_err(PmpxError::Other)?;
            match lookup_dotted(&doc, key) {
                Some(v) => {
                    anstream::println!("{}", render_value(v));
                    Ok(EXIT_OK)
                }
                None => Err(PmpxError::Usage(format!(
                    "{} has no {key} (config file: {})",
                    "global config",
                    path.display()
                ))),
            }
        }

        ConfigCommand::Set { key, value } => {
            let mut doc = read_toml_table(&path).map_err(PmpxError::Other)?;
            // Parse once: what gets printed has to be the value that was stored, and a second
            // independent parse is one more chance for the two to differ.
            let parsed = parse_value(value);
            insert_dotted(&mut doc, key, parsed.clone())
                .map_err(|e| PmpxError::Usage(e.to_string()))?;

            if let Some(parent) = path.parent() {
                std::fs::create_dir_all(parent).map_err(|e| PmpxError::Other(e.into()))?;
            }
            let text = toml::to_string_pretty(&doc).map_err(|e| PmpxError::Other(e.into()))?;
            std::fs::write(&path, text).map_err(|e| PmpxError::Other(e.into()))?;

            anstream::println!(
                "Wrote {key} = {} to {}",
                render_value(&parsed),
                style::paint(style::DIM, path.display())
            );
            Ok(EXIT_OK)
        }
    }
}

/// Read a TOML file into a table; a missing file = an empty table.
fn read_toml_table(path: &Path) -> Result<toml::Table> {
    match std::fs::read_to_string(path) {
        Ok(text) if !text.trim().is_empty() => {
            toml::from_str(&text).with_context(|| format!("failed to parse {}", path.display()))
        }
        Ok(_) => Ok(toml::Table::new()),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(toml::Table::new()),
        Err(e) => Err(e).with_context(|| format!("failed to read {}", path.display())),
    }
}

/// Look up a value by `a.b.c`.
fn lookup_dotted<'a>(table: &'a toml::Table, key: &str) -> Option<&'a toml::Value> {
    let mut parts = key.split('.');
    let first = parts.next()?;
    let mut current = table.get(first)?;

    for part in parts {
        current = current.as_table()?.get(part)?;
    }
    Some(current)
}

/// Write a value by `a.b.c`; missing intermediate tables are created.
fn insert_dotted(table: &mut toml::Table, key: &str, value: toml::Value) -> Result<()> {
    let parts: Vec<&str> = key.split('.').collect();
    if parts.iter().any(|p| p.is_empty()) {
        anyhow::bail!("a key must not have empty segments: {key}");
    }

    let mut current = table;
    for part in &parts[..parts.len() - 1] {
        let entry = current
            .entry((*part).to_string())
            .or_insert_with(|| toml::Value::Table(toml::Table::new()));

        current = entry
            .as_table_mut()
            .with_context(|| format!("{part} is not a table, cannot write into it"))?;
    }

    current.insert(parts[parts.len() - 1].to_string(), value);
    Ok(())
}

/// Parse a string from the command line into a TOML value.
///
/// The order is deliberately "most specific to most permissive": `true` -> integer -> array
/// -> string. So `pmpx config set x 123` stores a number; to store a string, write `"123"`
/// (with quotes).
fn parse_value(raw: &str) -> toml::Value {
    if raw == "true" {
        return toml::Value::Boolean(true);
    }
    if raw == "false" {
        return toml::Value::Boolean(false);
    }
    if let Ok(n) = raw.parse::<i64>() {
        return toml::Value::Integer(n);
    }

    // Arrays and quoted strings borrow TOML's own parser
    if let Ok(doc) = toml::from_str::<toml::Table>(&format!("v = {raw}")) {
        if let Some(v) = doc.get("v") {
            return v.clone();
        }
    }

    toml::Value::String(raw.to_string())
}

/// Print a TOML value. Strings get no quotes -- the user wants the value, not the syntax.
fn render_value(v: &toml::Value) -> String {
    match v {
        toml::Value::String(s) => s.clone(),
        other => other.to_string().trim().to_string(),
    }
}

// ---------------------------------------------------------------------------
// completion
// ---------------------------------------------------------------------------

fn completion(shell: clap_complete::Shell) -> crate::error::Result<u8> {
    let mut cmd = Cli::command();
    let name = cmd.get_name().to_string();
    // Print to stdout and let the user redirect -- pmpx does not guess which file to write.
    clap_complete::generate(shell, &mut cmd, name, &mut std::io::stdout());
    Ok(EXIT_OK)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_value_recognises_booleans() {
        assert_eq!(parse_value("true"), toml::Value::Boolean(true));
        assert_eq!(parse_value("false"), toml::Value::Boolean(false));
    }

    #[test]
    fn parse_value_recognises_integers() {
        assert_eq!(parse_value("42"), toml::Value::Integer(42));
        assert_eq!(parse_value("-7"), toml::Value::Integer(-7));
    }

    #[test]
    fn parse_value_recognises_arrays() {
        let v = parse_value("[\"rust\", \"node\"]");
        let arr = v.as_array().expect("should be an array");
        assert_eq!(arr.len(), 2);
        assert_eq!(arr[0].as_str(), Some("rust"));
    }

    #[test]
    fn parse_value_falls_back_to_a_string() {
        assert_eq!(parse_value("node"), toml::Value::String("node".to_string()));
        // A number stored as a string has to carry quotes
        assert_eq!(
            parse_value("\"123\""),
            toml::Value::String("123".to_string())
        );
    }

    #[test]
    fn render_value_omits_quotes_for_strings() {
        assert_eq!(render_value(&toml::Value::String("node".into())), "node");
        assert_eq!(render_value(&toml::Value::Integer(3)), "3");
        assert_eq!(render_value(&toml::Value::Boolean(true)), "true");
    }

    #[test]
    fn lookup_dotted_walks_tables() {
        let doc: toml::Table = toml::from_str(
            r#"
[plugin]
family_priority = ["node"]
[deep]
[deep.er]
x = 1
"#,
        )
        .unwrap();

        assert!(lookup_dotted(&doc, "plugin.family_priority").is_some());
        assert_eq!(
            lookup_dotted(&doc, "deep.er.x"),
            Some(&toml::Value::Integer(1))
        );
        assert!(lookup_dotted(&doc, "plugin.nope").is_none());
        assert!(lookup_dotted(&doc, "nope.at.all").is_none());
    }

    #[test]
    fn insert_dotted_creates_missing_tables() {
        let mut doc = toml::Table::new();
        insert_dotted(&mut doc, "a.b.c", toml::Value::Integer(1)).unwrap();

        assert_eq!(lookup_dotted(&doc, "a.b.c"), Some(&toml::Value::Integer(1)));
    }

    #[test]
    fn insert_dotted_refuses_to_clobber_a_non_table() {
        let mut doc: toml::Table = toml::from_str("a = 1\n").unwrap();
        let err = insert_dotted(&mut doc, "a.b", toml::Value::Integer(2)).unwrap_err();
        assert!(err.to_string().contains("not a table"), "{err}");
    }

    #[test]
    fn insert_dotted_rejects_empty_segments() {
        let mut doc = toml::Table::new();
        assert!(insert_dotted(&mut doc, "a..b", toml::Value::Integer(1)).is_err());
        assert!(insert_dotted(&mut doc, "", toml::Value::Integer(1)).is_err());
    }

    #[test]
    fn read_toml_table_treats_a_missing_file_as_empty() {
        let tmp = tempfile::tempdir().unwrap();
        let t = read_toml_table(&tmp.path().join("nope.toml")).unwrap();
        assert!(t.is_empty());
    }

    #[test]
    fn read_toml_table_treats_an_empty_file_as_empty() {
        let tmp = tempfile::tempdir().unwrap();
        let p = tmp.path().join("empty.toml");
        std::fs::write(&p, "   \n").unwrap();
        assert!(read_toml_table(&p).unwrap().is_empty());
    }

    #[test]
    fn join_or_dash_handles_the_empty_case() {
        assert_eq!(join_or_dash(&[]), "(none)");
        assert_eq!(join_or_dash(&["a".into(), "b".into()]), "a, b");
    }
}