bzr 0.2.0

A CLI for Bugzilla, inspired by gh
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
use std::io::{self, Write as _};

use colored::Colorize;
use tabled::{Table, Tabled};

use super::formatting::{opt_yes_no, print_field, print_formatted, print_optional_field};
use crate::types::{BugzillaUser, OutputFormat, WhoamiResponse};

#[derive(Tabled)]
struct UserRow {
    #[tabled(rename = "ID")]
    id: u64,
    #[tabled(rename = "NAME")]
    name: String,
    #[tabled(rename = "REAL NAME")]
    real_name: String,
    #[tabled(rename = "EMAIL")]
    email: String,
}

#[derive(Tabled)]
struct DetailedUserRow {
    #[tabled(rename = "ID")]
    id: u64,
    #[tabled(rename = "NAME")]
    name: String,
    #[tabled(rename = "REAL NAME")]
    real_name: String,
    #[tabled(rename = "EMAIL")]
    email: String,
    #[tabled(rename = "CAN LOGIN")]
    can_login: String,
    #[tabled(rename = "GROUPS")]
    groups: String,
}

fn basic_row(user: &BugzillaUser) -> UserRow {
    UserRow {
        id: user.id,
        name: user.name.clone(),
        real_name: user.real_name.clone().unwrap_or_default(),
        email: user.email.clone().unwrap_or_default(),
    }
}

fn detailed_row(user: &BugzillaUser) -> DetailedUserRow {
    DetailedUserRow {
        id: user.id,
        name: user.name.clone(),
        real_name: user.real_name.clone().unwrap_or_default(),
        email: user.email.clone().unwrap_or_default(),
        can_login: opt_yes_no(user.can_login).into(),
        groups: if user.groups.is_empty() {
            "-".into()
        } else {
            user.groups
                .iter()
                .map(|g| g.name.as_str())
                .collect::<Vec<_>>()
                .join(", ")
        },
    }
}

pub fn print_users(users: &[BugzillaUser], format: OutputFormat) {
    print_formatted(users, format, |users| {
        if users.is_empty() {
            let _ = writeln!(io::stdout(), "No users found.");
            return;
        }
        let rows: Vec<UserRow> = users.iter().map(basic_row).collect();
        let _ = writeln!(io::stdout(), "{}", Table::new(rows));
    });
}

pub fn print_users_detailed(users: &[BugzillaUser], format: OutputFormat) {
    print_formatted(users, format, |users| {
        if users.is_empty() {
            let _ = writeln!(io::stdout(), "No users found.");
            return;
        }
        let rows: Vec<DetailedUserRow> = users.iter().map(detailed_row).collect();
        let _ = writeln!(io::stdout(), "{}", Table::new(rows));
    });
}

pub fn print_whoami(whoami: &WhoamiResponse, format: OutputFormat) {
    print_formatted(whoami, format, |whoami| {
        let _ = writeln!(io::stdout(), "{} {}", "User".bold(), whoami.name.bold());
        print_optional_field("Name", whoami.real_name.as_deref());
        print_optional_field("Login", whoami.login.as_deref());
        print_field("ID", &whoami.id.to_string());
    });
}

#[cfg(test)]
#[expect(clippy::unwrap_used)]
mod tests {
    use super::*;
    use crate::types::{BugzillaUser, UserGroup, WhoamiResponse};
    use tabled::Table;

    fn make_user(id: u64, name: &str, can_login: Option<bool>, groups: Vec<&str>) -> BugzillaUser {
        BugzillaUser {
            id,
            name: name.into(),
            real_name: Some(format!("{name} Real")),
            email: Some(format!("{name}@example.com")),
            groups: groups
                .into_iter()
                .map(|g| UserGroup {
                    id: 1,
                    name: g.into(),
                    description: String::new(),
                })
                .collect(),
            can_login,
        }
    }

    fn make_whoami() -> WhoamiResponse {
        WhoamiResponse {
            id: 42,
            name: "testuser".into(),
            real_name: Some("Test User".into()),
            login: Some("testuser@example.com".into()),
        }
    }

    // ── Existing user row tests ──────────────────────────────────────

    #[test]
    fn user_row_excludes_detail_columns() {
        let user = make_user(1, "alice", Some(true), vec!["admin"]);
        let row = UserRow {
            id: user.id,
            name: user.name.clone(),
            real_name: user.real_name.clone().unwrap_or_default(),
            email: user.email.clone().unwrap_or_default(),
        };
        let table = Table::new(vec![row]).to_string();
        assert!(table.contains("ID"));
        assert!(table.contains("NAME"));
        assert!(table.contains("EMAIL"));
        assert!(!table.contains("CAN LOGIN"));
        assert!(!table.contains("GROUPS"));
    }

    #[test]
    fn detailed_user_row_includes_groups_and_login() {
        let users = [
            make_user(1, "alice", Some(true), vec!["admin", "dev"]),
            make_user(2, "bob", Some(false), vec![]),
            make_user(3, "carol", None, vec!["testers"]),
        ];
        let rows: Vec<DetailedUserRow> = users.iter().map(detailed_row).collect();
        let table = Table::new(rows).to_string();
        assert!(table.contains("CAN LOGIN"));
        assert!(table.contains("GROUPS"));
        assert!(table.contains("Yes"));
        assert!(table.contains("No"));
        assert!(table.contains("admin, dev"));
        assert!(table.contains('-'));
        let lines: Vec<&str> = table.lines().collect();
        let carol_line = lines.iter().find(|l| l.contains("carol")).unwrap();
        assert!(carol_line.contains("testers"));
        assert!(carol_line.contains('-'));
    }

    #[test]
    fn print_users_json_includes_can_login() {
        let users = vec![make_user(1, "alice", Some(true), vec!["admin"])];
        let json = serde_json::to_string_pretty(&users).unwrap();
        assert!(json.contains("\"can_login\": true"));
        assert!(json.contains("\"groups\""));
    }

    // ── print_whoami ─────────────────────────────────────────────────

    #[test]
    fn print_whoami_json() {
        let whoami = make_whoami();
        let json = serde_json::to_string_pretty(&whoami).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed["id"], 42);
        assert_eq!(parsed["name"], "testuser");
        assert_eq!(parsed["real_name"], "Test User");
        assert_eq!(parsed["login"], "testuser@example.com");
    }

    #[test]
    fn print_whoami_json_minimal() {
        let whoami = WhoamiResponse {
            id: 1,
            name: "bot".into(),
            real_name: None,
            login: None,
        };
        let json = serde_json::to_string_pretty(&whoami).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed["id"], 1);
        assert!(parsed["real_name"].is_null());
        assert!(parsed["login"].is_null());
    }

    // ── print_users (extended) ───────────────────────────────────────

    #[test]
    fn print_users_json_empty() {
        let users: Vec<BugzillaUser> = vec![];
        let json = serde_json::to_string_pretty(&users).unwrap();
        assert_eq!(json, "[]");
    }

    #[test]
    fn print_users_json_includes_all_fields() {
        let users = vec![make_user(1, "alice", Some(true), vec!["admin"])];
        let json = serde_json::to_string_pretty(&users).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed[0]["id"], 1);
        assert_eq!(parsed[0]["name"], "alice");
        assert_eq!(parsed[0]["real_name"], "alice Real");
        assert_eq!(parsed[0]["email"], "alice@example.com");
        assert_eq!(parsed[0]["can_login"], true);
        assert_eq!(parsed[0]["groups"][0]["name"], "admin");
    }

    // ── capture_stdout-based formatter tests ─────────────────────────

    #[cfg(unix)]
    #[tokio::test]
    async fn print_users_table_empty_says_none_found() {
        let _lock = crate::ENV_LOCK.lock().await;
        let ((), output) = crate::test_helpers::capture_stdout(async {
            print_users(&[], OutputFormat::Table);
        })
        .await;
        assert!(output.contains("No users found."));
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn print_users_json_empty_renders_empty_array() {
        let _lock = crate::ENV_LOCK.lock().await;
        let ((), output) = crate::test_helpers::capture_stdout(async {
            print_users(&[], OutputFormat::Json);
        })
        .await;
        let parsed = crate::test_helpers::extract_json(&output);
        assert!(parsed.is_array());
        assert_eq!(parsed.as_array().unwrap().len(), 0);
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn print_users_table_renders_basic_columns() {
        let _lock = crate::ENV_LOCK.lock().await;
        let users = vec![make_user(1, "alice", Some(true), vec!["admin"])];
        let ((), output) = crate::test_helpers::capture_stdout(async {
            print_users(&users, OutputFormat::Table);
        })
        .await;
        assert!(output.contains("ID"));
        assert!(output.contains("NAME"));
        assert!(output.contains("REAL NAME"));
        assert!(output.contains("EMAIL"));
        assert!(output.contains("alice"));
        assert!(output.contains("alice Real"));
        assert!(output.contains("alice@example.com"));
        // Basic table excludes detail columns
        assert!(!output.contains("CAN LOGIN"));
        assert!(!output.contains("GROUPS"));
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn print_users_detailed_table_empty_says_none_found() {
        let _lock = crate::ENV_LOCK.lock().await;
        let ((), output) = crate::test_helpers::capture_stdout(async {
            print_users_detailed(&[], OutputFormat::Table);
        })
        .await;
        assert!(output.contains("No users found."));
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn print_users_detailed_table_renders_groups_and_login() {
        let _lock = crate::ENV_LOCK.lock().await;
        let users = vec![
            make_user(1, "alice", Some(true), vec!["admin", "dev"]),
            make_user(2, "bob", Some(false), vec![]),
            make_user(3, "carol", None, vec!["testers"]),
        ];
        let ((), output) = crate::test_helpers::capture_stdout(async {
            print_users_detailed(&users, OutputFormat::Table);
        })
        .await;
        assert!(output.contains("CAN LOGIN"));
        assert!(output.contains("GROUPS"));
        assert!(output.contains("Yes"));
        assert!(output.contains("No"));
        assert!(output.contains("admin, dev"));
        // None can_login renders as "-"
        assert!(output.contains('-'));
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn print_users_detailed_handles_missing_real_name_and_email() {
        let _lock = crate::ENV_LOCK.lock().await;
        let users = vec![BugzillaUser {
            id: 99,
            name: "minimal".into(),
            real_name: None,
            email: None,
            groups: vec![],
            can_login: None,
        }];
        let ((), output) = crate::test_helpers::capture_stdout(async {
            print_users_detailed(&users, OutputFormat::Table);
        })
        .await;
        // Locate the data row that contains the user's name. Both
        // can_login (None → "-") and groups (empty → "-") render as a
        // dash in that row, anchored to the field semantics rather than
        // the table border.
        let data_row = output
            .lines()
            .find(|line| line.contains("minimal"))
            .expect("data row for 'minimal' user");
        // Two "-" cells (can_login + groups) should appear inside the
        // row. Border separators are `|`, so count the dashes that fall
        // between bars.
        let dash_cells = data_row
            .split('|')
            .filter(|cell| cell.trim() == "-")
            .count();
        assert_eq!(
            dash_cells, 2,
            "expected 2 dashed cells (can_login, groups) in row: {data_row}"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn print_whoami_table_renders_fields() {
        let _lock = crate::ENV_LOCK.lock().await;
        let whoami = make_whoami();
        let ((), output) = crate::test_helpers::capture_stdout(async {
            print_whoami(&whoami, OutputFormat::Table);
        })
        .await;
        assert!(output.contains("User"));
        assert!(output.contains("testuser"));
        assert!(output.contains("Test User"));
        assert!(output.contains("testuser@example.com"));
        assert!(output.contains("42"));
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn print_whoami_json_via_print() {
        let _lock = crate::ENV_LOCK.lock().await;
        let whoami = make_whoami();
        let ((), output) = crate::test_helpers::capture_stdout(async {
            print_whoami(&whoami, OutputFormat::Json);
        })
        .await;
        let parsed = crate::test_helpers::extract_json(&output);
        assert_eq!(parsed["id"], 42);
        assert_eq!(parsed["name"], "testuser");
        assert_eq!(parsed["real_name"], "Test User");
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn print_whoami_table_renders_dashes_for_missing_fields() {
        let _lock = crate::ENV_LOCK.lock().await;
        let whoami = WhoamiResponse {
            id: 1,
            name: "bot".into(),
            real_name: None,
            login: None,
        };
        let ((), output) = crate::test_helpers::capture_stdout(async {
            print_whoami(&whoami, OutputFormat::Table);
        })
        .await;
        assert!(output.contains("bot"));
        // print_optional_field renders "  {label:<12}  -" for missing
        // values. Anchor to those exact field renderings so the assertion
        // fails when rendering changes, not when borders do.
        assert!(
            output.contains("Name          -"),
            "expected dashed Name field, got: {output}"
        );
        assert!(
            output.contains("Login         -"),
            "expected dashed Login field, got: {output}"
        );
    }
}