xbp 10.28.0

XBP is a zero-config build pack that can also interact with proxies, kafka, sockets, synthetic monitors.
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
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
pub mod app;
pub mod auto_commit;
pub mod commands;
pub mod error;
pub mod features;
pub mod handlers;
pub mod router;
pub mod ui;

pub use handlers::*;

use crate::cli::app::AppContext;
use crate::cli::error::{CliResult, ErrorFactory};
use crate::commands::curl;
use crate::commands::generate_systemd::{run_generate_systemd, GenerateSystemdArgs};
use crate::commands::redeploy_v2::run_redeploy_v2;
use crate::commands::{
    install_package, list_services, open_global_config, run_commit, run_config,
    run_config_cloudflare_account_delete, run_config_cloudflare_account_set,
    run_config_cloudflare_account_show, run_config_linear_select_initiative,
    run_config_publish_setup, run_config_secret_delete, run_config_secret_set,
    run_config_secret_show, run_generate_config, run_init, run_login, run_publish_command,
    run_redeploy, run_redeploy_service, run_service_command, run_setup, run_version_command,
    run_version_release_command, run_version_workspace_command, show_service_help, CommitArgs,
    GenerateConfigArgs, PublishCommandOptions, ReleaseLatestPolicy, VersionReleaseOptions,
    WorkspacePublishRunOptions, WorkspaceVersionCheckOptions, WorkspaceVersionCommand,
    WorkspaceVersionCommandOptions, WorkspaceVersionSyncOptions, WorkspaceVersionValidateOptions,
};
use crate::commands::{run_diag, run_nginx};
use crate::config::sync_versioning_files_registry;
use crate::logging::{init_logger, log_error, log_info, log_success, log_warn};
use clap::{error::ErrorKind as ClapErrorKind, CommandFactory, Parser};
use colored::Colorize;
use commands::Cli;

pub async fn run() -> CliResult<()> {
    let cli: Cli = match Cli::try_parse() {
        Ok(cli) => cli,
        Err(err) => {
            let kind = err.kind();
            let rendered = err.to_string();
            if matches!(
                kind,
                ClapErrorKind::DisplayHelp
                    | ClapErrorKind::DisplayVersion
                    | ClapErrorKind::MissingSubcommand
            ) || rendered.contains("Manage the XBP API server")
            {
                print!("{rendered}");
                return Ok(());
            }
            return Err(ErrorFactory::clap_parse(err));
        }
    };

    // Keep plain `xbp` aligned with `xbp --help` instead of entering
    // interactive project selection flow.
    if should_print_help(&cli) {
        let mut cmd = Cli::command();
        let _ = cmd.print_help();
        println!();
        return Ok(());
    }

    let debug: bool = cli.debug;
    ui::configure_color_output();
    let command_name = cli
        .command
        .as_ref()
        .map(commands::command_label)
        .unwrap_or("interactive");
    ui::print_cli_header(command_name, debug);

    if let Err(e) = init_logger(debug).await {
        let _ = log_error(
            "system",
            "Failed to initialize logger",
            Some(&e.to_string()),
        )
        .await;
    }
    if let Err(e) = sync_versioning_files_registry() {
        let _ = log_warn("config", "Failed to sync versioning registry", Some(&e)).await;
    }

    let mut ctx = AppContext::new(debug);
    router::dispatch(cli, &mut ctx).await
}

pub(super) async fn handle_init(debug: bool) -> CliResult<()> {
    if let Err(e) = run_init(debug).await {
        let _ = log_error("init", "Init failed", Some(&e)).await;
        return Err(e.into());
    }
    Ok(())
}

pub(super) async fn handle_commit(cmd: commands::CommitCmd) -> CliResult<()> {
    let args = CommitArgs {
        dry_run: cmd.dry_run,
        push: cmd.push,
        no_ai: cmd.no_ai,
        model: cmd.model,
        scope: cmd.scope,
    };

    if let Err(e) = run_commit(args).await {
        let _ = log_error("commit", "Commit command failed", Some(&e)).await;
        return Err(ErrorFactory::operation(
            "commit",
            "create conventional commit",
            e,
            Some("Run `xbp commit --dry-run` to inspect the generated message first."),
        ));
    }

    Ok(())
}

pub(super) async fn handle_publish(cmd: commands::PublishCmd, _debug: bool) -> CliResult<()> {
    let options = PublishCommandOptions {
        dry_run: cmd.dry_run,
        allow_dirty: cmd.allow_dirty,
        target: cmd.target,
        expected_version: None,
    };

    if let Err(e) = run_publish_command(options).await {
        let _ = log_error("publish", "Publish command failed", Some(&e)).await;
        return Err(ErrorFactory::operation(
            "publish",
            "run publish workflow",
            e,
            Some("Configure project targets with `xbp config npm setup-release` or `xbp config crates setup-release`."),
        ));
    }

    Ok(())
}

pub(super) async fn handle_setup(debug: bool) -> CliResult<()> {
    if let Err(e) = ui::with_loader("Running setup checks", run_setup(debug)).await {
        let _ = log_error("setup", "Setup failed", Some(&e)).await;
        return Err(ErrorFactory::operation(
            "setup",
            "setup environment",
            e,
            Some("Run with `--debug` for command-level output."),
        ));
    }
    Ok(())
}

pub(super) async fn handle_redeploy(service_name: Option<String>, debug: bool) -> CliResult<()> {
    if let Some(name) = service_name {
        if let Err(e) = ui::with_loader(
            &format!("Redeploying service `{}`", name),
            run_redeploy_service(&name, debug),
        )
        .await
        {
            let _ = log_error("redeploy", "Service redeploy failed", Some(&e)).await;
            return Err(ErrorFactory::operation(
                "redeploy",
                &format!("redeploy service `{}`", name),
                e,
                Some("Verify service name with `xbp services`."),
            ));
        }
    } else if let Err(e) = ui::with_loader("Redeploying full project", run_redeploy()).await {
        let _ = log_error("redeploy", "Redeploy failed", Some(&e)).await;
        return Err(ErrorFactory::operation(
            "redeploy",
            "redeploy project",
            e,
            Some("Try `xbp redeploy <service>` for scoped retries."),
        ));
    }
    Ok(())
}

pub(super) async fn handle_redeploy_v2(cmd: commands::RedeployV2Cmd, debug: bool) -> CliResult<()> {
    let _ = log_info("redeploy_v2", "Starting remote redeploy process", None).await;
    match run_redeploy_v2(cmd.password, cmd.username, cmd.host, cmd.project_dir, debug).await {
        Ok(()) => Ok(()),
        Err(e) => {
            let _ = log_error("redeploy_v2", "Remote redeploy failed", Some(&e)).await;
            Err(e.into())
        }
    }
}

pub(super) async fn handle_config(cmd: commands::ConfigCmd, debug: bool) -> CliResult<()> {
    let commands::ConfigCmd {
        project,
        no_open,
        provider,
    } = cmd;

    if provider.is_some() && (project || no_open) {
        return Err(ErrorFactory::validation(
            "config",
            "`xbp config <provider> ...` cannot be combined with `--project` or `--no-open`.",
            Some("Run either provider key management OR project/global config actions."),
        ));
    }

    if let Some(provider_cmd) = provider {
        match provider_cmd {
            commands::ConfigProviderCmd::Openrouter(subcmd) => match subcmd.action {
                commands::ConfigSecretAction::SetKey { key } => {
                    if let Err(e) = run_config_secret_set("openrouter", key).await {
                        let _ = log_error("config", "Failed to set OpenRouter key", Some(&e)).await;
                        return Err(ErrorFactory::operation(
                            "config",
                            "set OpenRouter key",
                            e,
                            Some("Run `xbp config openrouter show` to confirm key state."),
                        ));
                    }
                }
                commands::ConfigSecretAction::DeleteKey => {
                    if let Err(e) = run_config_secret_delete("openrouter").await {
                        let _ =
                            log_error("config", "Failed to delete OpenRouter key", Some(&e)).await;
                        return Err(ErrorFactory::operation(
                            "config",
                            "delete OpenRouter key",
                            e,
                            Some("Use `xbp config openrouter show` to verify removal."),
                        ));
                    }
                }
                commands::ConfigSecretAction::Show { raw } => {
                    if let Err(e) = run_config_secret_show("openrouter", raw).await {
                        let _ =
                            log_error("config", "Failed to show OpenRouter key", Some(&e)).await;
                        return Err(ErrorFactory::operation(
                            "config",
                            "show OpenRouter key",
                            e,
                            None,
                        ));
                    }
                }
            },
            commands::ConfigProviderCmd::Github(subcmd) => match subcmd.action {
                commands::ConfigSecretAction::SetKey { key } => {
                    if let Err(e) = run_config_secret_set("github", key).await {
                        let _ = log_error("config", "Failed to set GitHub token", Some(&e)).await;
                        return Err(ErrorFactory::operation(
                            "config",
                            "set GitHub token",
                            e,
                            Some("Use a token with repo scope for private repos."),
                        ));
                    }
                }
                commands::ConfigSecretAction::DeleteKey => {
                    if let Err(e) = run_config_secret_delete("github").await {
                        let _ =
                            log_error("config", "Failed to delete GitHub token", Some(&e)).await;
                        return Err(ErrorFactory::operation(
                            "config",
                            "delete GitHub token",
                            e,
                            None,
                        ));
                    }
                }
                commands::ConfigSecretAction::Show { raw } => {
                    if let Err(e) = run_config_secret_show("github", raw).await {
                        let _ = log_error("config", "Failed to show GitHub token", Some(&e)).await;
                        return Err(ErrorFactory::operation(
                            "config",
                            "show GitHub token",
                            e,
                            None,
                        ));
                    }
                }
            },
            commands::ConfigProviderCmd::Cloudflare(subcmd) => match subcmd.action {
                commands::CloudflareConfigAction::SetKey { key } => {
                    if let Err(e) = run_config_secret_set("cloudflare", key).await {
                        let _ =
                            log_error("config", "Failed to set Cloudflare token", Some(&e)).await;
                        return Err(ErrorFactory::operation(
                            "config",
                            "set Cloudflare token",
                            e,
                            Some("Use a Cloudflare API token with Secrets Store and DNS permissions."),
                        ));
                    }
                }
                commands::CloudflareConfigAction::DeleteKey => {
                    if let Err(e) = run_config_secret_delete("cloudflare").await {
                        let _ = log_error("config", "Failed to delete Cloudflare token", Some(&e))
                            .await;
                        return Err(ErrorFactory::operation(
                            "config",
                            "delete Cloudflare token",
                            e,
                            None,
                        ));
                    }
                }
                commands::CloudflareConfigAction::ShowKey { raw } => {
                    if let Err(e) = run_config_secret_show("cloudflare", raw).await {
                        let _ =
                            log_error("config", "Failed to show Cloudflare token", Some(&e)).await;
                        return Err(ErrorFactory::operation(
                            "config",
                            "show Cloudflare token",
                            e,
                            None,
                        ));
                    }
                }
                commands::CloudflareConfigAction::SetAccountId { account_id } => {
                    if let Err(e) = run_config_cloudflare_account_set(account_id).await {
                        let _ =
                            log_error("config", "Failed to set Cloudflare account ID", Some(&e))
                                .await;
                        return Err(ErrorFactory::operation(
                            "config",
                            "set Cloudflare account ID",
                            e,
                            None,
                        ));
                    }
                }
                commands::CloudflareConfigAction::DeleteAccountId => {
                    if let Err(e) = run_config_cloudflare_account_delete().await {
                        let _ =
                            log_error("config", "Failed to delete Cloudflare account ID", Some(&e))
                                .await;
                        return Err(ErrorFactory::operation(
                            "config",
                            "delete Cloudflare account ID",
                            e,
                            None,
                        ));
                    }
                }
                commands::CloudflareConfigAction::ShowAccountId { raw } => {
                    if let Err(e) = run_config_cloudflare_account_show(raw).await {
                        let _ =
                            log_error("config", "Failed to show Cloudflare account ID", Some(&e))
                                .await;
                        return Err(ErrorFactory::operation(
                            "config",
                            "show Cloudflare account ID",
                            e,
                            None,
                        ));
                    }
                }
            },
            commands::ConfigProviderCmd::Linear(subcmd) => match subcmd.action {
                commands::LinearConfigAction::SetKey { key } => {
                    if let Err(e) = run_config_secret_set("linear", key).await {
                        let _ = log_error("config", "Failed to set Linear API key", Some(&e)).await;
                        return Err(ErrorFactory::operation(
                            "config",
                            "set Linear API key",
                            e,
                            Some("Use this to link Linear issue IDs in generated release notes and publish release updates to Linear initiatives."),
                        ));
                    }
                }
                commands::LinearConfigAction::DeleteKey => {
                    if let Err(e) = run_config_secret_delete("linear").await {
                        let _ =
                            log_error("config", "Failed to delete Linear API key", Some(&e)).await;
                        return Err(ErrorFactory::operation(
                            "config",
                            "delete Linear API key",
                            e,
                            None,
                        ));
                    }
                }
                commands::LinearConfigAction::Show { raw } => {
                    if let Err(e) = run_config_secret_show("linear", raw).await {
                        let _ =
                            log_error("config", "Failed to show Linear API key", Some(&e)).await;
                        return Err(ErrorFactory::operation(
                            "config",
                            "show Linear API key",
                            e,
                            None,
                        ));
                    }
                }
                commands::LinearConfigAction::SelectInitiative => {
                    if let Err(e) = run_config_linear_select_initiative().await {
                        let _ = log_error(
                            "config",
                            "Failed to select repo Linear initiative",
                            Some(&e),
                        )
                        .await;
                        return Err(ErrorFactory::operation(
                            "config",
                            "select repo Linear initiative",
                            e,
                            Some("Run this inside an XBP project and configure a Linear key with `xbp config linear set-key` first."),
                        ));
                    }
                }
            },
            commands::ConfigProviderCmd::Npm(subcmd) => match subcmd.action {
                commands::RegistryConfigAction::SetKey { key } => {
                    if let Err(e) = run_config_secret_set("npm", key).await {
                        let _ = log_error("config", "Failed to set npm token", Some(&e)).await;
                        return Err(ErrorFactory::operation(
                            "config",
                            "set npm token",
                            e,
                            Some("Use a valid npm automation or granular publish token."),
                        ));
                    }
                }
                commands::RegistryConfigAction::DeleteKey => {
                    if let Err(e) = run_config_secret_delete("npm").await {
                        let _ = log_error("config", "Failed to delete npm token", Some(&e)).await;
                        return Err(ErrorFactory::operation(
                            "config",
                            "delete npm token",
                            e,
                            None,
                        ));
                    }
                }
                commands::RegistryConfigAction::Show { raw } => {
                    if let Err(e) = run_config_secret_show("npm", raw).await {
                        let _ = log_error("config", "Failed to show npm token", Some(&e)).await;
                        return Err(ErrorFactory::operation("config", "show npm token", e, None));
                    }
                }
                commands::RegistryConfigAction::SetupRelease => {
                    if let Err(e) = run_config_publish_setup("npm").await {
                        let _ =
                            log_error("config", "Failed to configure npm publish", Some(&e)).await;
                        return Err(ErrorFactory::operation(
                            "config",
                            "configure npm publish",
                            e,
                            Some("Run this inside the target XBP project and ensure the package manifest exists."),
                        ));
                    }
                }
            },
            commands::ConfigProviderCmd::Crates(subcmd) => match subcmd.action {
                commands::RegistryConfigAction::SetKey { key } => {
                    if let Err(e) = run_config_secret_set("crates", key).await {
                        let _ = log_error("config", "Failed to set crates token", Some(&e)).await;
                        return Err(ErrorFactory::operation(
                            "config",
                            "set crates token",
                            e,
                            Some("Use a crates.io API token or rely on CARGO_REGISTRY_TOKEN."),
                        ));
                    }
                }
                commands::RegistryConfigAction::DeleteKey => {
                    if let Err(e) = run_config_secret_delete("crates").await {
                        let _ =
                            log_error("config", "Failed to delete crates token", Some(&e)).await;
                        return Err(ErrorFactory::operation(
                            "config",
                            "delete crates token",
                            e,
                            None,
                        ));
                    }
                }
                commands::RegistryConfigAction::Show { raw } => {
                    if let Err(e) = run_config_secret_show("crates", raw).await {
                        let _ = log_error("config", "Failed to show crates token", Some(&e)).await;
                        return Err(ErrorFactory::operation(
                            "config",
                            "show crates token",
                            e,
                            None,
                        ));
                    }
                }
                commands::RegistryConfigAction::SetupRelease => {
                    if let Err(e) = run_config_publish_setup("crates").await {
                        let _ = log_error("config", "Failed to configure crates publish", Some(&e))
                            .await;
                        return Err(ErrorFactory::operation(
                            "config",
                            "configure crates publish",
                            e,
                            Some("Run this inside the target XBP project and point the workflow at the crate manifest you want to publish."),
                        ));
                    }
                }
            },
        }
    } else if project {
        if let Err(e) = run_config(debug).await {
            return Err(ErrorFactory::operation(
                "config",
                "read project config",
                e,
                Some("Ensure you're inside an XBP project root."),
            ));
        }
    } else if let Err(e) = open_global_config(no_open).await {
        let _ = log_error("config", "Failed to open global config", Some(&e)).await;
        return Err(ErrorFactory::operation(
            "config",
            "open global config",
            e,
            None,
        ));
    }
    Ok(())
}

pub(super) async fn handle_install(
    package: Option<String>,
    list: bool,
    debug: bool,
) -> CliResult<()> {
    if list {
        crate::commands::print_install_targets_help();
        return Ok(());
    }

    let Some(package) = package else {
        crate::commands::print_install_empty_state();
        return Ok(());
    };

    if package.trim().is_empty() {
        crate::commands::print_install_empty_state();
        return Ok(());
    }

    if crate::commands::is_install_listing_request(&package) {
        crate::commands::print_install_targets_help();
        return Ok(());
    }

    let install_msg: String = format!("Installing package: {}", package);
    let _ = log_info("install", &install_msg, None).await;
    match ui::with_loader(
        &format!("Installing package `{}`", package),
        install_package(&package, debug),
    )
    .await
    {
        Ok(()) => {
            let success_msg = format!("Successfully installed: {}", package);
            let _ = log_success("install", &success_msg, None).await;
            Ok(())
        }
        Err(e) => Err(e.into()),
    }
}

pub(super) async fn handle_curl(cmd: commands::CurlCmd, debug: bool) -> CliResult<()> {
    let url = cmd
        .url
        .unwrap_or_else(|| "https://example.com/api".to_string());
    if let Err(e) = ui::with_loader(
        &format!("Requesting {}", url),
        curl::run_curl(&url, cmd.no_timeout, debug),
    )
    .await
    {
        let _ = log_error("curl", "Curl command failed", Some(&e)).await;
        return Err(ErrorFactory::operation(
            "curl",
            "execute request",
            e,
            Some("Double-check the URL and network connectivity."),
        ));
    }
    Ok(())
}

pub(super) async fn handle_services(debug: bool) -> CliResult<()> {
    if let Err(e) = ui::with_loader("Loading configured services", list_services(debug)).await {
        let _ = log_error("services", "Failed to list services", Some(&e)).await;
        return Err(ErrorFactory::operation(
            "services",
            "list services",
            e,
            Some("Ensure xbp config is present and valid."),
        ));
    }
    Ok(())
}

pub(super) async fn handle_service(
    command: Option<String>,
    service_name: Option<String>,
    debug: bool,
) -> CliResult<()> {
    if let Some(cmd) = command {
        if cmd == "--help" || cmd == "help" {
            if let Some(name) = service_name {
                if let Err(e) = show_service_help(&name).await {
                    let _ = log_error("service", "Failed to show service help", Some(&e)).await;
                    return Err(ErrorFactory::operation(
                        "service",
                        "show service help",
                        e,
                        None,
                    ));
                }
            } else {
                print_service_usage();
            }
        } else if let Some(name) = service_name {
            if let Err(e) = run_service_command(&cmd, &name, debug).await {
                let _ = log_error(
                    "service",
                    &format!("Service command '{}' failed", cmd),
                    Some(&e),
                )
                .await;
                return Err(ErrorFactory::operation(
                    "service",
                    &format!("run `{}` for `{}`", cmd, name),
                    e,
                    Some("Check available services via `xbp services`."),
                ));
            }
        } else {
            let _ = log_error("service", "Service name required", None).await;
            return Err(ErrorFactory::validation(
                "service",
                "Service name required.",
                Some("Usage: `xbp service <build|install|start|dev> <service-name>`"),
            ));
        }
    } else {
        print_service_usage();
    }
    Ok(())
}

pub(super) async fn handle_nginx(cmd: commands::NginxSubCommand, debug: bool) -> CliResult<()> {
    if let Err(e) = run_nginx(cmd, debug).await {
        let _ = log_error("nginx", "Nginx command failed", Some(&e.to_string())).await;
        return Err(ErrorFactory::operation(
            "nginx",
            "execute nginx command",
            e.to_string(),
            Some("Try `xbp nginx --help` for command syntax."),
        ));
    }
    Ok(())
}

pub(super) async fn handle_diag(cmd: commands::DiagCmd, debug: bool) -> CliResult<()> {
    if let Err(e) = ui::with_loader("Running diagnostics", run_diag(cmd, debug)).await {
        let _ = log_error("diag", "Diag command failed", Some(&e.to_string())).await;
        return Err(ErrorFactory::operation(
            "diag",
            "run diagnostics",
            e.to_string(),
            Some("Re-run with `--debug` for more context."),
        ));
    }
    Ok(())
}

pub(super) async fn handle_generate(cmd: commands::GenerateCmd, debug: bool) -> CliResult<()> {
    match cmd.command {
        commands::GenerateSubCommand::Config(subcmd) => {
            let args = GenerateConfigArgs {
                force: subcmd.force,
                update: subcmd.update,
                from_json: subcmd.from_json,
            };
            if let Err(e) = run_generate_config(args, debug).await {
                let _ = log_error(
                    "generate-config",
                    "Failed to generate project config",
                    Some(&e),
                )
                .await;
                return Err(ErrorFactory::operation(
                    "generate-config",
                    "generate .xbp/xbp.yaml",
                    e,
                    Some("Use --update to refresh an existing config or --force to overwrite it."),
                ));
            }
        }
        commands::GenerateSubCommand::Systemd(subcmd) => {
            let args = GenerateSystemdArgs {
                output_dir: subcmd.output_dir,
                service: subcmd.service,
                api: subcmd.api,
            };
            if let Err(e) = run_generate_systemd(args, debug).await {
                let _ = log_error(
                    "generate-systemd",
                    "Failed to generate systemd units",
                    Some(&e),
                )
                .await;
                return Err(ErrorFactory::operation(
                    "generate-systemd",
                    "generate unit files",
                    e,
                    Some("Use a writable `--output-dir` or run with elevated permissions."),
                ));
            }
        }
    }
    Ok(())
}

pub(super) async fn handle_done(cmd: commands::DoneCmd, _debug: bool) -> CliResult<()> {
    if let Err(e) = crate::commands::run_done(
        cmd.root,
        cmd.since,
        cmd.output,
        cmd.no_ai,
        cmd.recursive,
        cmd.exclude,
    )
    .await
    {
        let _ = log_error("done", "Done command failed", Some(&e)).await;
        return Err(e.into());
    }
    Ok(())
}

pub(super) async fn handle_login() -> CliResult<()> {
    if let Err(e) = run_login().await {
        let _ = log_error("login", "Login failed", Some(&e)).await;
        return Err(e.into());
    }
    Ok(())
}

pub(super) async fn handle_version(cmd: commands::VersionCmd, debug: bool) -> CliResult<()> {
    let commands::VersionCmd {
        target,
        explicit_version,
        git,
        command,
    } = cmd;
    let resolved_target = explicit_version.or(target);

    if command.is_some() && (resolved_target.is_some() || git) {
        return Err(ErrorFactory::validation(
            "version",
            "`xbp version release` cannot be combined with `--git`, positional targets, or `--version`/`-v` on the parent command.",
            Some(
                "Run `xbp version release` as a standalone command, or use `xbp version --version <x.y.z>` without a subcommand.",
            ),
        ));
    }

    if let Some(subcommand) = command {
        match subcommand {
            commands::VersionSubCommand::Release(release_cmd) => {
                let options = VersionReleaseOptions {
                    explicit_version: release_cmd.version,
                    allow_dirty: release_cmd.allow_dirty,
                    title: release_cmd.title,
                    notes: release_cmd.notes,
                    notes_file: release_cmd.notes_file,
                    draft: release_cmd.draft,
                    prerelease: release_cmd.prerelease,
                    publish: release_cmd.publish,
                    latest_policy: match release_cmd.make_latest {
                        commands::VersionReleaseLatest::True => ReleaseLatestPolicy::True,
                        commands::VersionReleaseLatest::False => ReleaseLatestPolicy::False,
                        commands::VersionReleaseLatest::Legacy => ReleaseLatestPolicy::Legacy,
                    },
                };
                if let Err(e) = run_version_release_command(options).await {
                    return Err(ErrorFactory::operation(
                        "version",
                        "release version",
                        e,
                        Some("Use `--allow-dirty` if only generated files changed."),
                    ));
                }
                return Ok(());
            }
            commands::VersionSubCommand::Workspace(workspace_cmd) => {
                let (repo, json, workspace_command) = match workspace_cmd.command {
                    commands::VersionWorkspaceSubCommand::Check(check_cmd) => (
                        check_cmd.target.repo,
                        check_cmd.target.json,
                        WorkspaceVersionCommand::Check(WorkspaceVersionCheckOptions {
                            version: check_cmd.version,
                        }),
                    ),
                    commands::VersionWorkspaceSubCommand::Sync(sync_cmd) => (
                        sync_cmd.target.repo,
                        sync_cmd.target.json,
                        WorkspaceVersionCommand::Sync(WorkspaceVersionSyncOptions {
                            version: sync_cmd.version,
                            write: sync_cmd.write,
                        }),
                    ),
                    commands::VersionWorkspaceSubCommand::Validate(validate_cmd) => (
                        validate_cmd.target.repo,
                        validate_cmd.target.json,
                        WorkspaceVersionCommand::Validate(WorkspaceVersionValidateOptions {
                            package: validate_cmd.package,
                            cargo_check: validate_cmd.cargo_check,
                            package_dry_run: validate_cmd.package_dry_run,
                        }),
                    ),
                    commands::VersionWorkspaceSubCommand::Publish(publish_cmd) => {
                        match publish_cmd.command {
                            commands::VersionWorkspacePublishSubCommand::Plan(plan_cmd) => (
                                plan_cmd.target.repo,
                                plan_cmd.target.json,
                                WorkspaceVersionCommand::PublishPlan,
                            ),
                            commands::VersionWorkspacePublishSubCommand::Run(run_cmd) => (
                                run_cmd.target.repo,
                                run_cmd.target.json,
                                WorkspaceVersionCommand::PublishRun(WorkspacePublishRunOptions {
                                    dry_run: run_cmd.dry_run,
                                    from: run_cmd.from,
                                    only: run_cmd.only,
                                    continue_on_error: run_cmd.continue_on_error,
                                    allow_dirty: run_cmd.allow_dirty,
                                    timeout_seconds: run_cmd.timeout_seconds,
                                    poll_interval_seconds: run_cmd.poll_interval_seconds,
                                }),
                            ),
                        }
                    }
                };

                if let Err(e) = run_version_workspace_command(WorkspaceVersionCommandOptions {
                    repo,
                    json,
                    command: workspace_command,
                })
                .await
                {
                    return Err(ErrorFactory::operation(
                        "version",
                        "run workspace version command",
                        e,
                        Some("Run `xbp version workspace -h` to inspect supported usage."),
                    ));
                }
                return Ok(());
            }
        }
    }

    if let Err(e) = run_version_command(resolved_target, git, debug).await {
        return Err(ErrorFactory::operation(
            "version",
            "run version command",
            e,
            Some("Run `xbp version -h` to inspect supported usage."),
        ));
    }
    Ok(())
}

fn should_print_help(cli: &Cli) -> bool {
    cli.command.is_none() && !cli.list && !cli.logs && cli.port.is_none()
}

fn print_service_usage() {
    println!(
        "\n{} {}",
        "Usage:".bright_blue().bold(),
        "xbp service <command> <service-name>".bright_white()
    );
    println!("{} build, install, start, dev", "Commands:".bright_blue(),);
    println!("{} xbp service build zeus", "Example:".bright_blue());
    println!(
        "{} xbp service --help <service-name>",
        "Tip:".bright_yellow().bold(),
    );
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::commands::{Commands, VersionReleaseLatest, VersionSubCommand};

    #[test]
    fn plain_cli_invocation_prints_help() {
        let cli = Cli::try_parse_from(["xbp"]).expect("parse");
        assert!(should_print_help(&cli));
    }

    #[test]
    fn list_flag_skips_help_short_circuit() {
        let cli = Cli::try_parse_from(["xbp", "-l"]).expect("parse");
        assert!(!should_print_help(&cli));
    }

    #[test]
    fn install_without_package_parses_and_is_optional() {
        let cli = Cli::try_parse_from(["xbp", "install"]).expect("parse");
        let Some(Commands::Install { list, package }) = cli.command else {
            panic!("expected install command");
        };
        assert!(!list);
        assert!(package.is_none());
    }

    #[test]
    fn install_with_package_still_parses() {
        let cli = Cli::try_parse_from(["xbp", "install", "docker"]).expect("parse");
        let Some(Commands::Install { list, package }) = cli.command else {
            panic!("expected install command");
        };
        assert!(!list);
        assert_eq!(package.as_deref(), Some("docker"));
    }

    #[test]
    fn install_list_flag_parses() {
        let cli = Cli::try_parse_from(["xbp", "install", "--list"]).expect("parse");
        let Some(Commands::Install { list, package }) = cli.command else {
            panic!("expected install command");
        };
        assert!(list);
        assert!(package.is_none());
    }

    #[test]
    fn install_short_list_flag_parses() {
        let cli = Cli::try_parse_from(["xbp", "install", "-l"]).expect("parse");
        let Some(Commands::Install { list, package }) = cli.command else {
            panic!("expected install command");
        };
        assert!(list);
        assert!(package.is_none());
    }

    #[test]
    fn install_ls_alias_parses_as_package() {
        let cli = Cli::try_parse_from(["xbp", "install", "ls"]).expect("parse");
        let Some(Commands::Install { list, package }) = cli.command else {
            panic!("expected install command");
        };
        assert!(!list);
        assert_eq!(package.as_deref(), Some("ls"));
    }

    #[test]
    fn version_release_make_latest_parses_explicit_value() {
        let cli = Cli::try_parse_from([
            "xbp",
            "version",
            "release",
            "--version",
            "1.2.3",
            "--make-latest",
            "false",
        ])
        .expect("parse");
        let Some(Commands::Version(version_cmd)) = cli.command else {
            panic!("expected version command");
        };
        assert!(version_cmd.explicit_version.is_none());
        let Some(VersionSubCommand::Release(release_cmd)) = version_cmd.command else {
            panic!("expected version release subcommand");
        };
        assert!(matches!(
            release_cmd.make_latest,
            VersionReleaseLatest::False
        ));
    }

    #[test]
    fn version_release_make_latest_defaults_to_legacy() {
        let cli = Cli::try_parse_from(["xbp", "version", "release", "--version", "1.2.3"])
            .expect("parse");
        let Some(Commands::Version(version_cmd)) = cli.command else {
            panic!("expected version command");
        };
        let Some(VersionSubCommand::Release(release_cmd)) = version_cmd.command else {
            panic!("expected version release subcommand");
        };
        assert!(matches!(
            release_cmd.make_latest,
            VersionReleaseLatest::Legacy
        ));
    }

    #[test]
    fn version_explicit_flag_parses() {
        let cli = Cli::try_parse_from(["xbp", "version", "--version", "1.2.3"]).expect("parse");
        let Some(Commands::Version(version_cmd)) = cli.command else {
            panic!("expected version command");
        };
        assert_eq!(version_cmd.explicit_version.as_deref(), Some("1.2.3"));
        assert!(version_cmd.target.is_none());
        assert!(version_cmd.command.is_none());
    }

    #[test]
    fn version_short_explicit_flag_parses_with_alias() {
        let cli = Cli::try_parse_from(["xbp", "v", "-v", "1.2.3"]).expect("parse");
        let Some(Commands::Version(version_cmd)) = cli.command else {
            panic!("expected version command");
        };
        assert_eq!(version_cmd.explicit_version.as_deref(), Some("1.2.3"));
        assert!(version_cmd.target.is_none());
        assert!(version_cmd.command.is_none());
    }
}