bob 0.99.4

Fast, robust, powerful, user-friendly pkgsrc package builder
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
/*
 * Copyright (c) 2026 Jonathan Perkin <jonathan@perkin.org.uk>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

use std::collections::{HashMap, HashSet};

use anyhow::{Result, bail};

use bob::db::{BuildDiff, Database, DiffEntry};
use bob::{PackageStateKind, parse_status_filter, try_println};

use super::{Col, Formatter, OutputFormat};

const DIFF_COLUMNS: &[(&str, &str)] = &[
    ("pkgname", "Package name (current, or previous if absent)"),
    ("pkgpath", "Package path in pkgsrc"),
    ("breaks", "Number of packages broken by this failure"),
    ("stage", "Build stage that failed (current)"),
    ("stage_prev", "Build stage that failed (previous)"),
    ("outcome", "Outcome (current)"),
    ("outcome_prev", "Outcome (previous)"),
    ("pkgname_prev", "Package name (previous)"),
];

const DEFAULT_COLUMNS: &[&str] = &["pkgname", "pkgpath", "breaks", "stage"];

#[derive(Debug, clap::Args)]
#[command(after_long_help = diff_after_help())]
pub struct DiffArgs {
    /// First build ID (baseline). Default: second most recent
    pub build1: Option<String>,
    /// Second build ID. Default: most recent
    pub build2: Option<String>,
    /// List available build IDs
    #[arg(short, long)]
    pub list: bool,
    /// Show all changes, not just failures and fixes
    #[arg(short, long)]
    pub all: bool,
    /// Columns to display (comma-separated, see --help for full list)
    #[arg(short = 'o', value_delimiter = ',')]
    pub columns: Option<Vec<String>>,
    /// Filter by baseline status (see `bob status -s` for valid values)
    #[arg(
        short = 'f',
        long = "from",
        value_parser = parse_status_filter,
        value_delimiter = ',',
    )]
    pub from: Vec<Vec<PackageStateKind>>,
    /// Filter by current status (see `bob status -s` for valid values)
    #[arg(
        short = 't',
        long = "to",
        value_parser = parse_status_filter,
        value_delimiter = ',',
    )]
    pub to: Vec<Vec<PackageStateKind>>,
}

fn diff_after_help() -> String {
    let width = DIFF_COLUMNS.iter().map(|(n, _)| n.len()).max().unwrap_or(0);
    let mut help = String::from("Columns:\n");
    for (name, desc) in DIFF_COLUMNS {
        help.push_str(&format!("  {:<width$}  {}\n", name, desc));
    }
    help.push_str(&format!("\nDefault columns: {}", DEFAULT_COLUMNS.join(",")));
    help
}

pub fn run(db: &Database, args: DiffArgs) -> Result<()> {
    if args.list {
        return list_builds(db);
    }

    let col_names: Vec<&str> = match &args.columns {
        Some(cols) => {
            for c in cols {
                if !DIFF_COLUMNS.iter().any(|(n, _)| *n == c.as_str()) {
                    let valid: Vec<&str> = DIFF_COLUMNS.iter().map(|(n, _)| *n).collect();
                    bail!(
                        "Unknown column '{}'. Valid columns: {}",
                        c,
                        valid.join(", ")
                    );
                }
            }
            cols.iter().map(|s| s.as_str()).collect()
        }
        None => DEFAULT_COLUMNS.to_vec(),
    };

    let (build1_id, build2_id) = match (args.build1, args.build2) {
        (Some(b1), Some(b2)) => (b1, b2),
        (Some(b1), None) => {
            let builds = db.list_history_builds()?;
            if builds.is_empty() {
                bail!("No builds in history");
            }
            (b1, builds[0].build_id.clone())
        }
        (None, Some(_)) => {
            bail!("Specify both build IDs, or none for the two most recent");
        }
        (None, None) => {
            let builds = db.list_history_builds()?;
            if builds.len() < 2 {
                bail!("Need at least two builds to compare. Use --list to see available builds.");
            }
            (builds[1].build_id.clone(), builds[0].build_id.clone())
        }
    };

    let diff = db.compute_build_diff(&build1_id, &build2_id)?;

    let breaks: HashMap<String, usize> = match bob::Scheduler::new(db) {
        Ok(sched) => sched
            .iter()
            .map(|sp| (sp.pkg.to_string(), sp.dep_count))
            .collect(),
        Err(_) => HashMap::new(),
    };

    let from: Option<HashSet<PackageStateKind>> =
        (!args.from.is_empty()).then(|| args.from.iter().flatten().copied().collect());
    let to: Option<HashSet<PackageStateKind>> =
        (!args.to.is_empty()).then(|| args.to.iter().flatten().copied().collect());

    if from.is_some() || to.is_some() {
        print_filtered(&diff, &breaks, &col_names, from.as_ref(), to.as_ref());
    } else {
        print_diff(&diff, &breaks, args.all, &col_names);
    }
    Ok(())
}

fn matches_filter(
    e: &DiffEntry,
    from: Option<&HashSet<PackageStateKind>>,
    to: Option<&HashSet<PackageStateKind>>,
) -> bool {
    let ok = |set: Option<&HashSet<PackageStateKind>>, state: Option<PackageStateKind>| match set {
        Some(s) => state.is_some_and(|k| s.contains(&k)),
        None => true,
    };
    ok(from, e.build1_outcome) && ok(to, e.build2_outcome)
}

fn print_filtered(
    diff: &BuildDiff,
    breaks: &HashMap<String, usize>,
    col_names: &[&str],
    from: Option<&HashSet<PackageStateKind>>,
    to: Option<&HashSet<PackageStateKind>>,
) {
    if !try_println(&format!("--- {}", diff.build1_id)) {
        return;
    }
    if !try_println(&format!("+++ {}", diff.build2_id)) {
        return;
    }

    let mut entries: Vec<&DiffEntry> = diff
        .new_failures
        .iter()
        .chain(diff.version_changes.iter())
        .chain(diff.fixes.iter())
        .chain(diff.other_changes.iter())
        .filter(|e| matches_filter(e, from, to))
        .collect();

    let label = |set: Option<&HashSet<PackageStateKind>>| -> String {
        set.map(|s| {
            let mut names: Vec<&str> = s.iter().map(<&str>::from).collect();
            names.sort_unstable();
            names.join(",")
        })
        .unwrap_or_else(|| "any".into())
    };
    let summary = format!(
        "@@ {}: from {} to {} @@",
        entries.len(),
        label(from),
        label(to),
    );
    if !try_println(&summary) {
        return;
    }
    if entries.is_empty() {
        return;
    }

    let widths: Vec<usize> = col_names
        .iter()
        .map(|name| {
            entries
                .iter()
                .map(|e| format_col(e, name, breaks).len())
                .max()
                .unwrap_or(0)
                .max(name.len())
        })
        .collect();

    let header: String = col_names
        .iter()
        .zip(&widths)
        .map(|(name, w)| format!("{:<w$}", name.to_uppercase(), w = w))
        .collect::<Vec<_>>()
        .join("  ");
    if !try_println(&format!(" {}", header)) {
        return;
    }

    entries.sort_by_key(|e| std::cmp::Reverse(get_breaks(e, breaks)));
    for e in &entries {
        let row: String = col_names
            .iter()
            .zip(&widths)
            .map(|(name, w)| format!("{:<w$}", format_col(e, name, breaks), w = w))
            .collect::<Vec<_>>()
            .join("  ");
        if !try_println(&format!(" {}", row)) {
            return;
        }
    }
}

fn list_builds(db: &Database) -> Result<()> {
    let builds = db.list_history_builds()?;
    if builds.is_empty() {
        println!("No builds in history.");
        return Ok(());
    }

    let mut fmt = Formatter::new(vec![
        Col::new("build_id", bob::Align::Left),
        Col::new("packages", bob::Align::Right),
        Col::new("succeeded", bob::Align::Right),
        Col::new("uptodate", bob::Align::Right),
        Col::new("failed", bob::Align::Right),
        Col::new("masked", bob::Align::Right),
    ]);
    for b in &builds {
        fmt.push(vec![
            b.build_id.clone(),
            b.package_count.to_string(),
            b.succeeded.to_string(),
            b.up_to_date.to_string(),
            b.failed.to_string(),
            b.masked.to_string(),
        ]);
    }
    fmt.print(OutputFormat::Table, false);
    Ok(())
}

fn format_col(e: &DiffEntry, col: &str, breaks: &HashMap<String, usize>) -> String {
    match col {
        "pkgname" => e
            .build2_pkgname
            .as_deref()
            .or(e.build1_pkgname.as_deref())
            .unwrap_or("-")
            .to_string(),
        "pkgpath" => e.pkgpath.clone(),
        "breaks" => get_breaks(e, breaks).to_string(),
        "stage" => match e.build2_outcome {
            Some(bob::PackageStateKind::Success) | Some(bob::PackageStateKind::UpToDate) => {
                String::new()
            }
            _ => e
                .build2_stage
                .map(|s| s.into_str().to_string())
                .unwrap_or_default(),
        },
        "stage_prev" => e
            .build1_stage
            .map(|s| s.into_str().to_string())
            .unwrap_or_default(),
        "outcome" => e
            .build2_outcome
            .map(|o| <&str>::from(o).to_string())
            .unwrap_or_default(),
        "outcome_prev" => e
            .build1_outcome
            .map(|o| <&str>::from(o).to_string())
            .unwrap_or_default(),
        "pkgname_prev" => e.build1_pkgname.as_deref().unwrap_or("").to_string(),
        _ => String::new(),
    }
}

fn get_breaks(e: &DiffEntry, breaks: &HashMap<String, usize>) -> usize {
    e.build2_pkgname
        .as_deref()
        .or(e.build1_pkgname.as_deref())
        .and_then(|n| breaks.get(n).copied())
        .unwrap_or(0)
}

fn print_diff(
    diff: &BuildDiff,
    breaks: &HashMap<String, usize>,
    show_all: bool,
    col_names: &[&str],
) {
    if !try_println(&format!("--- {}", diff.build1_id)) {
        return;
    }
    if !try_println(&format!("+++ {}", diff.build2_id)) {
        return;
    }

    let nf = diff.new_failures.len();
    let fx = diff.fixes.len();
    let vc = diff.version_changes.len();
    let oc = diff.other_changes.len();

    let mut parts = Vec::new();
    if nf > 0 {
        parts.push(format!("+{} failure{}", nf, if nf == 1 { "" } else { "s" }));
    }
    if fx > 0 {
        parts.push(format!("-{} fix{}", fx, if fx == 1 { "" } else { "es" }));
    }
    if vc > 0 {
        parts.push(format!("~{} change{}", vc, if vc == 1 { "" } else { "s" }));
    }
    if show_all && oc > 0 {
        parts.push(format!(
            "{} other change{}",
            oc,
            if oc == 1 { "" } else { "s" }
        ));
    }
    if parts.is_empty() {
        try_println("@@ no changes @@");
        return;
    }
    if !try_println(&format!("@@ {} @@", parts.join(", "))) {
        return;
    }

    let widths: Vec<usize> = col_names
        .iter()
        .map(|name| {
            let all_entries = diff
                .new_failures
                .iter()
                .chain(diff.version_changes.iter())
                .chain(diff.fixes.iter())
                .chain(if show_all {
                    diff.other_changes.iter()
                } else {
                    [].iter()
                });
            let max_val = all_entries
                .map(|e| format_col(e, name, breaks).len())
                .max()
                .unwrap_or(0);
            max_val.max(name.len())
        })
        .collect();

    let header: String = col_names
        .iter()
        .zip(&widths)
        .map(|(name, w)| format!("{:<w$}", name.to_uppercase(), w = w))
        .collect::<Vec<_>>()
        .join("  ");
    if !try_println(&format!(" {}", header)) {
        return;
    }

    let print_entries = |prefix: char, entries: &mut [&DiffEntry]| -> bool {
        entries.sort_by_key(|e| std::cmp::Reverse(get_breaks(e, breaks)));
        for e in entries.iter() {
            let row: String = col_names
                .iter()
                .zip(&widths)
                .map(|(name, w)| format!("{:<w$}", format_col(e, name, breaks), w = w))
                .collect::<Vec<_>>()
                .join("  ");
            if !try_println(&format!("{}{}", prefix, row)) {
                return false;
            }
        }
        true
    };

    let mut failures: Vec<_> = diff.new_failures.iter().collect();
    if !print_entries('+', &mut failures) {
        return;
    }

    let mut version_changes: Vec<_> = diff.version_changes.iter().collect();
    if !print_entries('~', &mut version_changes) {
        return;
    }

    let mut fixes: Vec<_> = diff.fixes.iter().collect();
    if !print_entries('-', &mut fixes) {
        return;
    }

    if show_all {
        let mut other: Vec<_> = diff.other_changes.iter().collect();
        print_entries(' ', &mut other);
    }
}