yandex-tracker-cli 1.0.1

Token-efficient Yandex Tracker CLI for humans and AI agents
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
//! Queue listings and field tables.

use std::fmt::Write as _;

use crate::api::{
    Automation, Component, FieldSpec, Holder, Permission, Queue, QueueAccess, QueueField,
    QueueSettings, Template, Unreadable,
};
use crate::render::Context;
use crate::render::style::Palette;
use crate::render::table::{Column, render, tally};

/// One line per queue: key first, because the key is what every other command
/// takes.
#[must_use]
pub fn queues(queues: &[Queue], ctx: &Context) -> String {
    let columns = [
        Column::whole("KEY", 12, Palette::key()),
        Column::whole("NAME", 28, anstyle::Style::new()),
        Column::whole("LEAD", 20, anstyle::Style::new()),
    ];
    let rows: Vec<Vec<String>> = queues
        .iter()
        .map(|queue| {
            vec![
                queue.key.clone(),
                queue.name.clone(),
                queue.lead.as_deref().unwrap_or("-").to_owned(),
            ]
        })
        .collect();

    let mut out = render(&columns, &rows, ctx);
    out.push_str(&tally(queues.len(), Some(queues.len() as u64), None, ctx));
    out
}

/// Field keys, types and names.
///
/// The key column comes first and is the point of the command: it is what
/// `--fields` and `--set` accept, and without it a caller is guessing. Custom
/// fields are marked, since those are the ones that differ per queue and are
/// therefore the ones worth pinning in a profile.
#[must_use]
pub fn fields(fields: &[QueueField], ctx: &Context) -> String {
    let columns = [
        Column::whole("KEY", 28, Palette::key()),
        Column::whole("TYPE", 12, anstyle::Style::new()),
        // Custom fields are the reason to run this command, so they are the ones
        // that stand out.
        Column::by_value("ORIGIN", 8, |origin| {
            if origin == "custom" {
                Palette::warn()
            } else {
                Palette::label()
            }
        }),
        Column::whole("NAME", 30, anstyle::Style::new()),
    ];
    let rows: Vec<Vec<String>> = fields
        .iter()
        .map(|field| {
            vec![
                field.key.clone(),
                field.field_type.clone(),
                if field.system { "system" } else { "custom" }.to_owned(),
                field.name.clone(),
            ]
        })
        .collect();

    let mut out = render(&columns, &rows, ctx);

    let custom = fields.iter().filter(|field| !field.system).count();
    let paint = ctx.painter();
    let _ = writeln!(
        out,
        "{}",
        paint.paint(
            &format!(
                "shown {} of {} ({custom} custom)",
                fields.len(),
                fields.len()
            ),
            Palette::label()
        )
    );
    out
}

/// How many values a constrained field lists before the rest are counted
/// rather than printed.
///
/// A field with two hundred options is a real thing, and printing all of them
/// by default makes a command nobody runs twice.
const VALUES_SHOWN: usize = 20;

/// One field: what it holds, whether it can be written, and what it accepts.
///
/// The last of those is the reason the command exists. `--set` is otherwise
/// written blind and judged by Tracker, which answers with the field's name in
/// the organisation's language and no hint of what it wanted instead.
#[must_use]
pub fn field_spec(field: &FieldSpec, all: bool, ctx: &Context) -> String {
    let mut out = String::with_capacity(240);
    let paint = ctx.painter();
    let label = |text: &str| paint.paint(text, Palette::label());
    let yes_no = |flag: bool| if flag { "yes" } else { "no" };

    let _ = writeln!(
        out,
        "{}  {}",
        paint.paint(&field.key, Palette::key()),
        field.name
    );

    // `type: array` on its own says nothing a caller can act on; what the
    // elements are is the part that decides whether `--set` takes one value or
    // a list.
    let kind = match &field.items {
        Some(items) => format!("{} of {items}", field.field_type),
        None => field.field_type.clone(),
    };
    let _ = writeln!(
        out,
        "{} {kind}   {} {}   {} {}",
        label("type:"),
        label("required:"),
        yes_no(field.required),
        label("readonly:"),
        yes_no(field.readonly),
    );
    if let Some(category) = &field.category {
        let _ = writeln!(out, "{} {category}", label("category:"));
    }

    out.push_str(&values(field, all, ctx));
    out
}

/// The values half of `field get`.
fn values(field: &FieldSpec, all: bool, ctx: &Context) -> String {
    let paint = ctx.painter();
    let label = |text: &str| paint.paint(text, Palette::label());

    let Some(options) = &field.options else {
        return format!("{} anything of that type\n", label("values:"));
    };

    if options.values.is_empty() {
        // A provider with no list is not an empty field: the values exist, they
        // are just kept somewhere this endpoint does not reach. Naming the
        // command that does reach them is the whole use of knowing the
        // provider's name.
        return match provider_source(&options.provider) {
            Some((what, command)) => format!("{} {what} — {command}\n", label("values:")),
            None => format!(
                "{} decided by {} — not listed by this endpoint\n",
                label("values:"),
                options.provider
            ),
        };
    }

    let mut out = String::with_capacity(64 + options.values.len() * 12);
    let shown = if all {
        options.values.len()
    } else {
        options.values.len().min(VALUES_SHOWN)
    };
    let _ = writeln!(
        out,
        "{} {}",
        label("values:"),
        options.values[..shown].join(", ")
    );
    let _ = writeln!(
        out,
        "{}",
        paint.paint(
            &if shown < options.values.len() {
                format!(
                    "shown {shown} of {} values; --all for the rest",
                    options.values.len()
                )
            } else {
                format!("shown {shown} of {shown} values")
            },
            Palette::label()
        )
    );
    out
}

/// Which command answers what a provider will accept, and what it holds.
///
/// Tracker names a class; a caller wants a command. Only the providers whose
/// answer this tool can actually fetch are mapped — an unrecognised one is
/// passed through by name rather than guessed at, because a wrong command here
/// costs a request and reads like a bug.
fn provider_source(provider: &str) -> Option<(&'static str, &'static str)> {
    Some(match provider {
        "TeamOptionsProvider" => ("people in the organisation", "ytcli user list"),
        "QueueOptionsProvider" => ("queue keys", "ytcli queue list"),
        "IssueTypeOptionsProvider" => ("issue types", "ytcli dict list --kind types"),
        "PriorityOptionsProvider" => ("priorities", "ytcli dict list --kind priorities"),
        "StatusOptionsProvider" => ("statuses", "ytcli dict list --kind statuses"),
        "ResolutionOptionsProvider" => ("resolutions", "ytcli dict list --kind resolutions"),
        "VersionOptionsProvider" => ("versions of the queue", "ytcli queue versions PROJ"),
        "TagOptionsProvider" => ("tags in use in the queue", "ytcli queue tags PROJ"),
        "SprintOptionsProvider" => ("sprints", "ytcli sprint list"),
        "BoardOptionsProvider" => ("boards", "ytcli board list"),
        "ProjectOptionsProvider" => ("projects", "ytcli project list"),
        "MetaEntityOptionsProvider" => ("goals", "ytcli goal list"),
        _ => return None,
    })
}

/// The fields a queue defines itself.
///
/// Carries what each accepts, which the organisation-wide `field get` cannot
/// answer for these: a local field is not reachable through `/v3/fields`, so if
/// this listing does not say, nothing does.
#[must_use]
pub fn local_fields(queue: &str, fields: &[FieldSpec], ctx: &Context) -> String {
    let columns = [
        Column::whole("KEY", 24, Palette::key()),
        Column::whole("TYPE", 10, anstyle::Style::new()),
        Column::new("NAME", 24, anstyle::Style::new()),
        Column::new("ACCEPTS", 28, Palette::label()),
    ];
    let rows: Vec<Vec<String>> = fields
        .iter()
        .map(|field| {
            vec![
                field.key.clone(),
                match &field.items {
                    Some(items) => format!("[{items}]"),
                    None => field.field_type.clone(),
                },
                field.name.clone(),
                accepts(field),
            ]
        })
        .collect();

    let mut out = render(&columns, &rows, ctx);
    out.push_str(&counted(queue, fields.len(), ctx));
    out
}

/// One cell's worth of what a field accepts.
fn accepts(field: &FieldSpec) -> String {
    match &field.options {
        None => "anything of that type".to_owned(),
        // The command, not the sentence: a cell has no room for prose, and the
        // command is the half a caller can run.
        Some(options) if options.values.is_empty() => provider_source(&options.provider)
            .map_or_else(
                || options.provider.clone(),
                |(_, command)| command.to_owned(),
            ),
        Some(options) => options.values.join(", "),
    }
}

/// The components a queue splits its work by.
///
/// The name leads, because the name is what `--set components=…` takes; the id
/// is beside it for the payloads that want one. `AUTO` is there because a
/// component that assigns automatically changes what a write does, which is not
/// something to discover afterwards.
#[must_use]
pub fn components(components: &[Component], scope: Option<&str>, ctx: &Context) -> String {
    let columns = [
        Column::new("NAME", 28, Palette::key()),
        Column::whole("ID", 8, anstyle::Style::new()),
        Column::whole("QUEUE", 12, anstyle::Style::new()),
        Column::new("LEAD", 20, anstyle::Style::new()),
        Column::by_value("AUTO", 6, |value| {
            if value == "yes" {
                Palette::warn()
            } else {
                Palette::label()
            }
        }),
    ];

    let rows: Vec<Vec<String>> = components
        .iter()
        .map(|component| {
            vec![
                component.name.clone(),
                component.id.clone(),
                component.queue.clone().unwrap_or_else(|| "-".to_owned()),
                component.lead.clone().unwrap_or_else(|| "-".to_owned()),
                if component.assign_auto { "yes" } else { "no" }.to_owned(),
            ]
        })
        .collect();

    let mut out = render(&columns, &rows, ctx);
    out.push_str(&match scope {
        Some(queue) => counted(queue, components.len(), ctx),
        None => tally(components.len(), Some(components.len() as u64), None, ctx),
    });
    out
}

/// The versions a queue defines.
#[must_use]
pub fn versions(queue: &str, versions: &[crate::api::Version], ctx: &Context) -> String {
    let columns = [
        Column::whole("ID", 10, Palette::key()),
        Column::new("NAME", 28, anstyle::Style::new()),
        // A released version and an archived one are both "not open", and
        // which of the two decides whether new work may still point at it.
        Column::by_value("STATE", 10, |state| match state {
            "open" => Palette::ok(),
            _ => Palette::label(),
        }),
        Column::whole("DUE", 12, anstyle::Style::new()),
    ];

    let rows: Vec<Vec<String>> = versions
        .iter()
        .map(|version| {
            vec![
                version.id.clone(),
                version.name.clone(),
                version.state.to_owned(),
                version.due.clone().unwrap_or_else(|| "-".to_owned()),
            ]
        })
        .collect();

    let mut out = render(&columns, &rows, ctx);
    out.push_str(&counted(queue, versions.len(), ctx));
    out
}

/// The tags in use in a queue.
#[must_use]
pub fn tags(queue: &str, tags: &[String], ctx: &Context) -> String {
    let columns = [Column::whole("TAG", 30, Palette::key())];
    let rows: Vec<Vec<String>> = tags.iter().map(|tag| vec![tag.clone()]).collect();

    let mut out = render(&columns, &rows, ctx);
    out.push_str(&counted(queue, tags.len(), ctx));
    out
}

/// `shown N of N for QUEUE` — neither endpoint pages, so both numbers are the
/// same one, and saying so is still better than leaving the reader to wonder.
fn counted(queue: &str, count: usize, ctx: &Context) -> String {
    let paint = ctx.painter();
    format!(
        "{}\n",
        paint.paint(
            &format!("shown {count} of {count} for {queue}"),
            Palette::label()
        )
    )
}

/// What changes issues in a queue without anybody touching them.
///
/// Three sections under their own headings, and the sections Tracker refused
/// named with its reason. A queue member cannot read triggers, and printing
/// nothing for them would say "no triggers", which is a different and wrong
/// answer.
#[must_use]
pub fn automation(queue: &str, automation: &Automation, ctx: &Context) -> String {
    let mut out = String::with_capacity(320);
    out.push_str(&macros_section(queue, automation, ctx));
    out.push('\n');
    out.push_str(&autoactions_section(queue, automation, ctx));
    out.push('\n');
    out.push_str(&triggers_section(queue, automation, ctx));
    out
}

fn heading(text: &str, ctx: &Context) -> String {
    format!("{}\n", ctx.painter().paint(text, Palette::heading()))
}

/// Canned changes somebody applies by hand.
fn macros_section(queue: &str, automation: &Automation, ctx: &Context) -> String {
    let rows: Vec<Vec<String>> = automation
        .macros
        .iter()
        .map(|entry| {
            vec![
                entry.id.clone(),
                entry.name.clone(),
                actions(&entry.updates),
                // The body is a comment somebody else wrote, so it is counted
                // rather than printed: this is a listing, and the text belongs
                // in the interface that runs it.
                if entry.body.is_some() { "yes" } else { "no" }.to_owned(),
            ]
        })
        .collect();

    let mut out = heading("macros", ctx);
    out.push_str(&render(
        &[
            Column::whole("ID", 8, Palette::key()),
            Column::new("NAME", 30, anstyle::Style::new()),
            Column::new("SETS", 24, anstyle::Style::new()),
            Column::whole("COMMENTS", 8, Palette::label()),
        ],
        &rows,
        ctx,
    ));
    out.push_str(&closing(
        queue,
        "macros",
        rows.len(),
        &automation.unreadable,
        ctx,
    ));
    out
}

/// Changes Tracker applies on a schedule to whatever matches a filter.
fn autoactions_section(queue: &str, automation: &Automation, ctx: &Context) -> String {
    let rows: Vec<Vec<String>> = automation
        .autoactions
        .iter()
        .map(|entry| {
            vec![
                entry.id.clone(),
                entry.name.clone(),
                active(entry.active).to_owned(),
                entry
                    .interval
                    .map_or_else(|| "-".to_owned(), |seconds| format!("{seconds}s")),
                actions(&entry.actions),
            ]
        })
        .collect();

    let mut out = heading("autoactions", ctx);
    out.push_str(&render(
        &[
            Column::whole("ID", 8, Palette::key()),
            Column::new("NAME", 28, anstyle::Style::new()),
            Column::by_value("ACTIVE", 8, state_colour),
            Column::whole("EVERY", 10, anstyle::Style::new()),
            Column::new("DOES", 22, anstyle::Style::new()),
        ],
        &rows,
        ctx,
    ));
    out.push_str(&closing(
        queue,
        "autoactions",
        rows.len(),
        &automation.unreadable,
        ctx,
    ));
    out
}

/// Changes Tracker applies the moment something happens to an issue.
fn triggers_section(queue: &str, automation: &Automation, ctx: &Context) -> String {
    let rows: Vec<Vec<String>> = automation
        .triggers
        .iter()
        .map(|entry| {
            vec![
                entry.id.clone(),
                entry.name.clone(),
                active(entry.active).to_owned(),
                entry.conditions.to_string(),
                actions(&entry.actions),
            ]
        })
        .collect();

    let mut out = heading("triggers", ctx);
    out.push_str(&render(
        &[
            Column::whole("ID", 8, Palette::key()),
            Column::new("NAME", 28, anstyle::Style::new()),
            Column::by_value("ACTIVE", 8, state_colour),
            Column::whole("WHEN", 10, Palette::label()),
            Column::new("DOES", 22, anstyle::Style::new()),
        ],
        &rows,
        ctx,
    ));
    out.push_str(&closing(
        queue,
        "triggers",
        rows.len(),
        &automation.unreadable,
        ctx,
    ));
    out
}

/// The last line of a section: a tally, or why there is nothing to tally.
///
/// A refused section must not end with `shown 0 of 0`. That reads as "there are
/// none", which is a different answer from "you may not see them" and the one
/// mistake this command exists to avoid.
fn closing(
    queue: &str,
    section: &str,
    count: usize,
    unreadable: &[Unreadable],
    ctx: &Context,
) -> String {
    match unreadable.iter().find(|refusal| refusal.section == section) {
        Some(refusal) => {
            let paint = ctx.painter();
            format!(
                "{}\n",
                paint.paint(
                    &format!("not readable — {}", refusal.reason),
                    Palette::warn()
                )
            )
        }
        None => counted(queue, count, ctx),
    }
}

/// Who may do what in a queue.
///
/// Two tables because the two answers are not the same one twice. The first is
/// the rule, roles and all; the second is the people it comes out as, and only
/// the second can say whether the caller is among them.
#[must_use]
pub fn access(queue: &str, access: &QueueAccess, ctx: &Context) -> String {
    let mut out = String::with_capacity(320);
    out.push_str(&permissions_section(queue, access, ctx));
    out.push('\n');
    out.push_str(&access_section(queue, access, ctx));
    out
}

/// The rule as somebody configured it.
fn permissions_section(queue: &str, access: &QueueAccess, ctx: &Context) -> String {
    let rows: Vec<Vec<String>> = access
        .permissions
        .iter()
        .map(|entry| {
            vec![
                entry.operation.clone(),
                granted_to(entry),
                holders(&entry.users),
            ]
        })
        .collect();

    let mut out = heading("permissions", ctx);
    out.push_str(&render(
        &[
            Column::whole("OPERATION", 14, Palette::key()),
            Column::new("ROLES", 34, anstyle::Style::new()),
            Column::new("USERS", 28, anstyle::Style::new()),
        ],
        &rows,
        ctx,
    ));
    out.push_str(&closing(
        queue,
        "permissions",
        rows.len(),
        &access.unreadable,
        ctx,
    ));

    // Without this the table looks like the whole answer, and a caller who is
    // in none of its user lists concludes they are locked out — while being the
    // assignee of every issue they care about.
    if rows.iter().any(|row| row[1] != "-") {
        let paint = ctx.painter();
        let _ = writeln!(
            out,
            "{}",
            paint.paint(
                "a role is decided per issue: `assignee` is whoever that issue names",
                Palette::label()
            )
        );
    }
    out
}

/// The people the rule comes out as.
fn access_section(queue: &str, access: &QueueAccess, ctx: &Context) -> String {
    let rows: Vec<Vec<String>> = access
        .access
        .iter()
        .map(|entry| {
            vec![
                entry.operation.clone(),
                holds(entry, access.you.as_deref()).to_owned(),
                holders(&entry.users),
            ]
        })
        .collect();

    let mut out = heading("access", ctx);
    out.push_str(&render(
        &[
            Column::whole("OPERATION", 14, Palette::key()),
            Column::by_value("YOU", 5, |held| match held {
                "yes" => Palette::ok(),
                "no" => Palette::warn(),
                _ => Palette::label(),
            }),
            Column::new("USERS", 44, anstyle::Style::new()),
        ],
        &rows,
        ctx,
    ));
    out.push_str(&closing(
        queue,
        "access",
        rows.len(),
        &access.unreadable,
        ctx,
    ));
    out
}

/// Whether the token's own user holds an operation.
///
/// `?` is not `no`. It means the user behind the token could not be read, and
/// answering "no" to a question that was never asked is the failure this whole
/// command is against.
fn holds(permission: &Permission, you: Option<&str>) -> &'static str {
    match you {
        Some(id) if permission.users.iter().any(|holder| holder.id == id) => "yes",
        Some(_) => "no",
        None => "?",
    }
}

/// Roles, and groups where a queue names any.
///
/// Groups share the column because they are the same kind of answer — a right
/// held by something other than a named person — and no queue reachable from
/// here has one to widen a column for.
fn granted_to(permission: &Permission) -> String {
    // Groups lead because the column truncates and the roles are the
    // predictable half: `queue-lead, assignee, author` says less about a
    // particular queue than one named group does.
    let mut names: Vec<String> = permission
        .groups
        .iter()
        .map(|group| format!("group:{}", group.display))
        .collect();
    names.extend(permission.roles.iter().map(|role| role.id.clone()));

    if names.is_empty() {
        "-".to_owned()
    } else {
        names.join(", ")
    }
}

/// A count, then as many names as fit.
///
/// The count leads because the column truncates: a cell cut off mid-name would
/// otherwise hide how many more there were, and `--format json` is the way to
/// the rest.
fn holders(list: &[Holder]) -> String {
    if list.is_empty() {
        return "-".to_owned();
    }
    let names: Vec<&str> = list.iter().map(|holder| holder.display.as_str()).collect();
    format!("{}: {}", list.len(), names.join(", "))
}

fn active(flag: bool) -> &'static str {
    if flag { "on" } else { "off" }
}

fn state_colour(state: &str) -> anstyle::Style {
    if state == "on" {
        Palette::ok()
    } else {
        Palette::label()
    }
}

fn actions(actions: &[String]) -> String {
    if actions.is_empty() {
        "-".to_owned()
    } else {
        actions.join(", ")
    }
}

/// One queue and the defaults an issue created in it starts with.
#[must_use]
pub fn settings(queue: &QueueSettings, ctx: &Context) -> String {
    let mut out = String::with_capacity(200);
    let paint = ctx.painter();
    let label = |text: &str| paint.paint(text, Palette::label());

    let _ = writeln!(
        out,
        "{}  {}",
        paint.paint(&queue.key, Palette::key()),
        queue.name
    );
    let _ = writeln!(
        out,
        "{} {}   {} {}   {} {}",
        label("lead:"),
        queue.lead.as_deref().unwrap_or("-"),
        label("default type:"),
        queue.default_type.as_deref().unwrap_or("-"),
        label("default priority:"),
        queue.default_priority.as_deref().unwrap_or("-"),
    );

    out
}

/// Issue or comment templates.
///
/// The id leads because it is what a caller passes on; the queue follows,
/// because a template that belongs to a queue only applies there.
#[must_use]
pub fn templates(templates: &[Template], ctx: &Context) -> String {
    let columns = [
        Column::whole("ID", 12, Palette::key()),
        Column::new("NAME", 36, anstyle::Style::new()),
        Column::whole("QUEUE", 12, anstyle::Style::new()),
        Column::new("AUTHOR", 18, Palette::label()),
    ];
    let rows: Vec<Vec<String>> = templates
        .iter()
        .map(|template| {
            vec![
                template.id.clone(),
                template.name.clone(),
                template.queue.as_deref().unwrap_or("-").to_owned(),
                template.author.as_deref().unwrap_or("-").to_owned(),
            ]
        })
        .collect();

    let mut out = render(&columns, &rows, ctx);
    out.push_str(&tally(
        templates.len(),
        Some(templates.len() as u64),
        None,
        ctx,
    ));
    out
}

#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
    use super::*;

    fn ctx() -> Context {
        Context {
            format: crate::render::Format::Text,
            audience: crate::render::Audience::Machine,
            description_lines: Some(10),
            extra_fields: Vec::new(),
            width: 80,
            images: false,
            inline: crate::render::image::Inline::default(),
        }
    }

    #[test]
    fn field_listing_marks_custom_fields_and_counts_them() {
        let listing = fields(
            &[
                QueueField {
                    key: "summary".to_owned(),
                    name: "Summary".to_owned(),
                    field_type: "string".to_owned(),
                    system: true,
                },
                QueueField {
                    key: "storyPoints".to_owned(),
                    name: "Story points".to_owned(),
                    field_type: "number".to_owned(),
                    system: false,
                },
            ],
            &ctx(),
        );

        assert!(listing.contains("summary"));
        assert!(listing.contains("system"));
        assert!(listing.contains("storyPoints"));
        assert!(listing.ends_with("shown 2 of 2 (1 custom)\n"));
    }
}