xbp 10.57.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
use colored::Colorize;
use indicatif::{ProgressBar, ProgressStyle};
use std::future::Future;
use std::io::IsTerminal;
use std::time::Duration;
use supports_color::Stream;

const SPINNER_SETS: &[&[&str]] = &[
    &["", "", "", "", "", "", "", "", "", ""],
    &["", "", "", ""],
    &["", "", "", ""],
    &["∙∙∙", "●∙∙", "∙●∙", "∙∙●", "∙●∙"],
];

pub struct Loader {
    pb: ProgressBar,
    label: String,
}

impl Loader {
    pub fn start(label: &str) -> Self {
        let spinner_frames = select_spinner_set(label);
        let pb = ProgressBar::new_spinner();
        let style = ProgressStyle::with_template("{spinner:.cyan} {msg}")
            .unwrap_or_else(|_| ProgressStyle::default_spinner())
            .tick_strings(spinner_frames);
        pb.set_style(style);
        pb.set_message(format!("{}", label.bright_cyan()));
        pb.enable_steady_tick(Duration::from_millis(95));
        Self {
            pb,
            label: label.to_string(),
        }
    }

    pub fn success(&self) {
        self.pb
            .finish_with_message(format!("{} {}", "OK".bright_green().bold(), self.label));
    }

    pub fn success_with(&self, message: &str) {
        self.pb
            .finish_with_message(format!("{} {}", "OK".bright_green().bold(), message));
    }

    pub fn fail(&self, details: &str) {
        self.pb.finish_with_message(format!(
            "{} {} {}",
            "ERR".bright_red().bold(),
            self.label,
            format!("({})", details).bright_black()
        ));
    }

    pub fn update(&self, message: &str) {
        self.pb.set_message(format!("{}", message.bright_cyan()));
    }

    pub fn log(&self, message: &str) {
        self.pb.println(message);
    }

    pub fn suspend<T, F>(&self, op: F) -> T
    where
        F: FnOnce() -> T,
    {
        self.pb.suspend(op)
    }

    /// Finish the spinner so a determinate bar can take over the next line.
    pub fn finish_for_handoff(&self) {
        self.pb.finish_and_clear();
    }
}

/// Left-to-right determinate progress bar (tqdm-style) for multi-item work
/// like secrets push / pull.
pub struct TaskBar {
    pb: ProgressBar,
    label: String,
}

impl TaskBar {
    pub fn start(label: &str, total: u64) -> Self {
        let pb = ProgressBar::new(total.max(1));
        let style = ProgressStyle::with_template(
            "{spinner:.cyan} {msg} [{bar:28.cyan/blue}] {pos}/{len} {percent:>3}%  {elapsed_precise} · ETA {eta_precise}",
        )
        .unwrap_or_else(|_| ProgressStyle::default_bar())
        .progress_chars("█▓░")
        .tick_strings(select_spinner_set(label));
        pb.set_style(style);
        pb.set_message(format!("{}", label.bright_cyan()));
        pb.enable_steady_tick(Duration::from_millis(95));
        if total == 0 {
            pb.set_position(0);
        }
        Self {
            pb,
            label: label.to_string(),
        }
    }

    pub fn set_position(&self, completed: u64) {
        self.pb.set_position(completed);
    }

    pub fn set_message(&self, message: &str) {
        self.pb.set_message(format!("{}", message.bright_cyan()));
    }

    pub fn tick(&self, completed: u64, message: &str) {
        self.set_message(message);
        self.set_position(completed);
    }

    pub fn println(&self, message: &str) {
        self.pb.println(message);
    }

    pub fn success_with(&self, message: &str) {
        self.pb
            .finish_with_message(format!("{} {}", "OK".bright_green().bold(), message));
    }

    pub fn fail(&self, details: &str) {
        self.pb.finish_with_message(format!(
            "{} {} {}",
            "ERR".bright_red().bold(),
            self.label,
            format!("({})", details).bright_black()
        ));
    }
}

/// Format a duration for TTY progress lines (`1m48s`, `42.1s`, `3h02m`).
pub fn format_duration_short(d: Duration) -> String {
    let secs = d.as_secs_f64();
    if secs < 60.0 {
        if secs < 10.0 {
            format!("{secs:.1}s")
        } else {
            format!("{:.0}s", secs.round())
        }
    } else if secs < 3600.0 {
        let m = (secs / 60.0).floor() as u64;
        let s = (secs % 60.0).round() as u64;
        format!("{m}m{s:02}s")
    } else {
        let h = (secs / 3600.0).floor() as u64;
        let m = ((secs % 3600.0) / 60.0).floor() as u64;
        format!("{h}h{m:02}m")
    }
}

/// Determinate multi-unit bar with unit lines, elapsed, and optional ETA from history.
pub struct TimedTaskBar {
    inner: Option<TaskBar>,
    label: String,
    total: u64,
    completed: u64,
    tty: bool,
    phase_started: std::time::Instant,
}

impl TimedTaskBar {
    pub fn start(label: &str, total: u64) -> Self {
        let tty = std::io::stderr().is_terminal() || std::io::stdout().is_terminal();
        let total = total.max(1);
        let inner = if tty {
            Some(TaskBar::start(label, total))
        } else {
            eprintln!("{}  ({} unit(s))", label.bright_cyan(), total);
            None
        };
        Self {
            inner,
            label: label.to_string(),
            total,
            completed: 0,
            tty,
            phase_started: std::time::Instant::now(),
        }
    }

    pub fn begin_unit(&self, unit_label: &str, remaining_eta: Option<Duration>) {
        let msg = match remaining_eta {
            Some(eta) if eta.as_secs() > 0 => {
                format!(
                    "{} · {}  ~{}",
                    self.label,
                    unit_label,
                    format_duration_short(eta)
                )
            }
            _ => format!("{} · {}", self.label, unit_label),
        };
        if let Some(bar) = &self.inner {
            bar.set_message(&msg);
            bar.set_position(self.completed);
        } else {
            eprintln!(
                "  {} {}  [{}/{}]",
                "".bright_cyan(),
                unit_label.bright_white(),
                self.completed + 1,
                self.total
            );
        }
    }

    pub fn finish_unit(&mut self, unit_label: &str, ok: bool, elapsed: Duration, detail: &str) {
        self.completed = (self.completed + 1).min(self.total);
        let time = format_duration_short(elapsed);
        let line = if ok {
            format!(
                "  {} {:<28} {}  {}",
                "".bright_green().bold(),
                unit_label.bright_white(),
                time.bright_black(),
                detail.bright_black()
            )
        } else {
            format!(
                "  {} {:<28} {}  {}",
                "".bright_red().bold(),
                unit_label.bright_white(),
                time.bright_black(),
                detail.bright_red()
            )
        };
        if let Some(bar) = &self.inner {
            bar.println(&line);
            bar.set_position(self.completed);
        } else {
            eprintln!("{line}");
        }
        let _ = self.tty;
    }

    pub fn success_with(&self, message: &str) {
        let total = format_duration_short(self.phase_started.elapsed());
        let msg = format!("{message}  ({total})");
        if let Some(bar) = &self.inner {
            bar.success_with(&msg);
        } else {
            eprintln!("{} {}", "OK".bright_green().bold(), msg);
        }
    }

    pub fn fail(&self, details: &str) {
        if let Some(bar) = &self.inner {
            bar.fail(details);
        } else {
            eprintln!(
                "{} {} ({})",
                "ERR".bright_red().bold(),
                self.label,
                details.bright_black()
            );
        }
    }
}

pub async fn with_loader<T, E, F>(label: &str, op: F) -> Result<T, E>
where
    E: std::fmt::Display,
    F: Future<Output = Result<T, E>>,
{
    let loader = Loader::start(label);
    let result = op.await;
    match &result {
        Ok(_) => loader.success(),
        Err(err) => loader.fail(&err.to_string()),
    }
    result
}

pub fn print_cli_header(command: &str, debug: bool) {
    let mode = if debug {
        "DEBUG".bright_yellow().bold().to_string()
    } else {
        "NORMAL".bright_blue().bold().to_string()
    };
    println!(
        "{} {} {} {}",
        "xbp".bright_magenta().bold(),
        "".bright_black(),
        command.bright_white().bold(),
        format!("[{}]", mode).bright_black()
    );
}

pub fn configure_color_output() {
    colored::control::set_override(should_emit_ansi());
}

pub fn should_emit_ansi() -> bool {
    // Respect common color control environment variables first.
    let disable_via_clicolor = std::env::var("CLICOLOR")
        .map(|value| value == "0")
        .unwrap_or(false);
    if std::env::var_os("NO_COLOR").is_some() || disable_via_clicolor {
        return false;
    }
    if std::env::var_os("FORCE_COLOR").is_some() || std::env::var_os("CLICOLOR_FORCE").is_some() {
        return true;
    }

    if legacy_cmd_without_color_hints() {
        return false;
    }

    let stdout_color = supports_color::on(Stream::Stdout).is_some();
    let stderr_color = supports_color::on(Stream::Stderr).is_some();
    stdout_color || stderr_color
}

pub fn section(title: &str) {
    println!(
        "\n{} {}",
        "".bright_blue().bold(),
        title.bright_blue().bold()
    );
}

pub fn divider(width: usize) {
    println!("{}", "".repeat(width).bright_black());
}

pub fn status_line(label: &str, status: &str, ok: bool) {
    let icon = if ok {
        "".bright_green().bold()
    } else {
        "".bright_red().bold()
    };
    let status = if ok {
        status.bright_green().to_string()
    } else {
        status.bright_red().to_string()
    };
    println!("  {} {} {}", icon, label.bright_white(), status);
}

pub fn tip(message: &str) {
    println!("{} {}", "Hint:".bright_yellow().bold(), message);
}

fn select_spinner_set(label: &str) -> &'static [&'static str] {
    let hash = label
        .bytes()
        .fold(0_u64, |acc, b| acc.wrapping_mul(16777619) ^ u64::from(b));
    let idx = (hash as usize) % SPINNER_SETS.len();
    SPINNER_SETS[idx]
}

#[cfg(windows)]
fn legacy_cmd_without_color_hints() -> bool {
    let Some(comspec) = std::env::var("ComSpec").ok() else {
        return false;
    };

    if !comspec.to_ascii_lowercase().ends_with("cmd.exe") {
        return false;
    }

    let has_color_hints = std::env::var_os("WT_SESSION").is_some()
        || std::env::var_os("ANSICON").is_some()
        || std::env::var("TERM_PROGRAM").is_ok()
        || std::env::var("TERM").is_ok_and(|value| value != "dumb")
        || std::env::var("ConEmuANSI")
            .map(|value| value.eq_ignore_ascii_case("ON"))
            .unwrap_or(false);

    !has_color_hints
}

#[cfg(not(windows))]
fn legacy_cmd_without_color_hints() -> bool {
    false
}

#[cfg(all(test, windows))]
mod tests {
    use super::legacy_cmd_without_color_hints;
    use once_cell::sync::Lazy;
    use std::sync::Mutex;

    static ENV_LOCK: Lazy<Mutex<()>> = Lazy::new(|| Mutex::new(()));

    #[test]
    fn cmd_without_color_hints_disables_ansi() {
        let _guard = ENV_LOCK.lock().expect("env lock");

        let keys = [
            "ComSpec",
            "WT_SESSION",
            "ANSICON",
            "TERM_PROGRAM",
            "TERM",
            "ConEmuANSI",
        ];
        let snapshot: Vec<(String, Option<String>)> = keys
            .iter()
            .map(|key| ((*key).to_string(), std::env::var(key).ok()))
            .collect();

        std::env::set_var("ComSpec", r"C:\Windows\System32\cmd.exe");
        for key in [
            "WT_SESSION",
            "ANSICON",
            "TERM_PROGRAM",
            "TERM",
            "ConEmuANSI",
        ] {
            std::env::remove_var(key);
        }

        assert!(legacy_cmd_without_color_hints());

        std::env::set_var("WT_SESSION", "1");
        assert!(!legacy_cmd_without_color_hints());

        for (key, value) in snapshot {
            match value {
                Some(value) => std::env::set_var(key, value),
                None => std::env::remove_var(key),
            }
        }
    }
}