xbp 10.17.2

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
pub mod app;
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_config, run_config_secret_delete,
    run_config_secret_set, run_config_secret_show, run_init, run_login, run_redeploy,
    run_redeploy_service, run_service_command, run_setup, run_version_command,
    run_version_release_command, show_service_help, VersionReleaseOptions,
};
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 _ = err.print();
            if matches!(
                kind,
                ClapErrorKind::DisplayHelp | ClapErrorKind::DisplayVersion
            ) {
                return Ok(());
            }
            return Err(ErrorFactory::clap_parse(err));
        }
    };

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

    let debug: bool = cli.debug;
    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_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,
                        ));
                    }
                }
            },
        }
    } 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: String, debug: bool) -> CliResult<()> {
    if package.is_empty() || package == "--help" || package == "help" {
        return install_package("", debug).await.map_err(Into::into);
    }

    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::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,
        git,
        command,
    } = cmd;

    if command.is_some() && (target.is_some() || git) {
        return Err(ErrorFactory::validation(
            "version",
            "`xbp version release` cannot be combined with `--git` or positional targets.",
            Some("Run `xbp version release` as a standalone command."),
        ));
    }

    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,
                };
                if let Err(e) = run_version_release_command(options).await {
                    let _ = log_error("version", "Version release failed", Some(&e)).await;
                    return Err(e.into());
                }
                return Ok(());
            }
        }
    }

    if let Err(e) = run_version_command(target, git, debug).await {
        let _ = log_error("version", "Version command failed", Some(&e)).await;
        return Err(e.into());
    }
    Ok(())
}

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(),
    );
}