OXYGENHUB
# 27322cd2755a oxygenhub / crates / oh / src / main.rs
103.8 KiB · Rust · last changed Flow job reports and timings over the API, oh run report and oh report; 0.9.14 (closes #348) 7 days ago source blame history raw
1
//! `oh`: OxygenHub from the command line, as `gh` is for GitHub. It talks
2
//! to the hub's JSON API (hub spec §12) as the checkout's remote does:
3
//! same hub, same token, same CA.
4
5
mod client;
6
mod target;
7
mod ui;
8
9
use anyhow::{bail, Context, Result};
10
use clap::{Parser, Subcommand};
11
use client::Client;
12
use hub_api::{
13
    FlowJob, FlowLogLine, FlowRun, Issue, IssueStateChange, NewComment, NewIssue, NewProposal, NewRelease, Proposal, Release, Report, Tag,
14
};
15
use std::time::Duration;
16
use target::{Choice, Config, Target};
17
18
#[derive(Parser)]
19
#[command(name = "oh", version = env!("OXY_VERSION_LONG"), about = "OxygenHub from the command line: issues, proposals, Flow runs, releases and drops")]
20
struct Cli {
21
    /// The repository, when not inside an Oxygen checkout
22
    #[arg(long, short = 'R', global = true, value_name = "OWNER/NAME")]
23
    repo: Option<String>,
24
    /// The hub, with --repo or outside a checkout (default: OH_HUB or the one `oh auth login` saved)
25
    #[arg(long, global = true, value_name = "URL")]
26
    hub: Option<String>,
27
    /// Which of the checkout's remotes to use (default: origin, or the only one)
28
    #[arg(long, global = true)]
29
    remote: Option<String>,
30
    /// Machine-readable output: the API's JSON, unchanged
31
    #[arg(long, global = true)]
32
    json: bool,
33
    /// Plain output: no colour or glyphs (also NO_COLOR, or when not a terminal)
34
    #[arg(long, global = true)]
35
    plain: bool,
36
    #[command(subcommand)]
37
    cmd: Cmd,
38
}
39
40
#[derive(Subcommand)]
41
enum Cmd {
42
    /// Sign in to a hub, or show who you are signed in as
43
    Auth {
44
        #[command(subcommand)]
45
        cmd: AuthCmd,
46
    },
47
    /// The repository
48
    Repo {
49
        #[command(subcommand)]
50
        cmd: RepoCmd,
51
    },
52
    /// Issues
53
    Issue {
54
        #[command(subcommand)]
55
        cmd: IssueCmd,
56
    },
57
    /// Proposals (pull requests)
58
    Proposal {
59
        #[command(subcommand)]
60
        cmd: ProposalCmd,
61
    },
62
    /// Coverage: upload a report measured off the hub (oxygenhub#136)
63
    Coverage {
64
        #[command(subcommand)]
65
        cmd: CoverageCmd,
66
    },
67
    /// OxygenFlow runs
68
    Run {
69
        #[command(subcommand)]
70
        cmd: RunCmd,
71
    },
72
    /// Reports Flow jobs publish: the newest of each, one by name (oxygenhub#348)
73
    Report {
74
        #[command(subcommand)]
75
        cmd: ReportCmd,
76
    },
77
    /// Releases
78
    Release {
79
        #[command(subcommand)]
80
        cmd: ReleaseCmd,
81
    },
82
    /// Tags: list, create, withdraw
83
    Tag {
84
        #[command(subcommand)]
85
        cmd: TagCmd,
86
    },
87
    /// The repository's labels
88
    Label {
89
        #[command(subcommand)]
90
        cmd: LabelCmd,
91
    },
92
    /// Milestones: list, create, edit, close
93
    Milestone {
94
        #[command(subcommand)]
95
        cmd: MilestoneCmd,
96
    },
97
    /// Project boards of the repository's owner (or --owner): list,
98
    /// create, view, and cards
99
    Project {
100
        #[command(subcommand)]
101
        cmd: ProjectCmd,
102
        /// A user or organisation other than the repository's owner
103
        #[arg(long, global = true)]
104
        owner: Option<String>,
105
    },
106
    /// AI assistants of the repository (its admins), or with --org or
107
    /// --site of an organisation or the site
108
    Assistant {
109
        #[command(subcommand)]
110
        cmd: AssistantCmd,
111
        /// An organisation's assistants instead of the repository's
112
        #[arg(long, global = true)]
113
        org: Option<String>,
114
        /// The site's assistants (administrators)
115
        #[arg(long, global = true, conflicts_with = "org")]
116
        site: bool,
117
    },
118
    /// Agents that act for you without a key of their own (keyless
119
    /// signing): grant, list, revoke
120
    Agent {
121
        #[command(subcommand)]
122
        cmd: AgentCmd,
123
    },
124
    /// Drops: small snippets of files, each its own repository, never
125
    /// listed among your repositories (oxygenhub#279)
126
    Drop {
127
        #[command(subcommand)]
128
        cmd: DropCmd,
129
    },
130
    /// Runners that update themselves (site administrators; oxygenhub#322):
131
    /// where builds come from, who takes them, what is held back
132
    #[command(name = "runner-updates")]
133
    RunnerUpdates {
134
        #[command(subcommand)]
135
        cmd: Option<RunnerUpdatesCmd>,
136
    },
137
    /// Call the API directly: `oh api /repos/OWNER/NAME/issues`
138
    Api {
139
        /// A path under /api/v1
140
        path: String,
141
        /// The method
142
        #[arg(long, short = 'X', default_value = "GET")]
143
        method: String,
144
        /// A JSON body
145
        #[arg(long, short = 'd')]
146
        data: Option<String>,
147
    },
148
}
149
150
#[derive(Subcommand)]
151
enum AgentCmd {
152
    /// Let an agent act for you: your oxy key (the one your oxy home names
153
    /// as author.key) signs a grant to agent:NAME@YOU, and the hub gives
154
    /// the agent a token it exchanges for ten-minute certificates. The
155
    /// token is printed once: give it to the agent (`oxy auth grant`)
156
    Grant {
157
        /// The agent's name, as in agent:NAME@YOU
158
        name: String,
159
        /// What its keys may do for you: changes, seal, refs
160
        #[arg(long, default_value = "changes,seal,refs")]
161
        scope: String,
162
        /// How long the grant lasts: 30d, 12h, 90m
163
        #[arg(long = "for", value_name = "DURATION", default_value = "30d")]
164
        lasts: String,
165
    },
166
    /// Your grants, live and past
167
    List,
168
    /// Stop a grant at once: no more certificates under it
169
    Revoke { id: i64 },
170
}
171
172
#[derive(Subcommand)]
173
enum DropCmd {
174
    /// Make a drop of these files, signed by the hub as your delegate
175
    Create {
176
        /// The files (their names in the drop are their file names)
177
        #[arg(required = true)]
178
        files: Vec<std::path::PathBuf>,
179
        /// Unlisted: readable by anyone with its address, listed nowhere
180
        #[arg(long)]
181
        secret: bool,
182
        /// A description
183
        #[arg(long, short = 'd', value_name = "TEXT")]
184
        description: Option<String>,
185
        /// A title (default: the first file's name)
186
        #[arg(long, short = 't')]
187
        title: Option<String>,
188
    },
189
    /// Your drops, or someone's public ones
190
    List {
191
        /// Whose drops
192
        #[arg(long, short = 'u', value_name = "NAME")]
193
        user: Option<String>,
194
    },
195
    /// A drop's files, printed (by id or address)
196
    View {
197
        /// The drop's id, or its address
198
        id: String,
199
        /// Print only this file's content
200
        #[arg(long, short = 'f', value_name = "NAME")]
201
        file: Option<String>,
202
    },
203
    /// Delete a drop and its history
204
    Delete {
205
        /// The drop's id, or its address
206
        id: String,
207
    },
208
}
209
210
#[derive(Subcommand)]
211
enum RunnerUpdatesCmd {
212
    /// Every level's settings, the test groups, each runner's policy and what it is offered (the default)
213
    Show,
214
    /// Change one level's settings; what is not given stays as it is
215
    Set {
216
        /// `site`, `owner:NAME`, `group:NAME` (or `group:OWNER/NAME`, `group:ID`), `runner:NAME` (or `runner:ID`)
217
        scope: String,
218
        /// `on`, `off` or `inherit`
219
        #[arg(long)]
220
        updates: Option<String>,
221
        /// `stable`, `canary`, a version, or `inherit`
222
        #[arg(long)]
223
        channel: Option<String>,
224
        /// Hours (UTC) updates may start in, `02-05`, or `inherit`
225
        #[arg(long)]
226
        window: Option<String>,
227
        /// `on`, `off` or `inherit`
228
        #[arg(long)]
229
        dry_run: Option<String>,
230
    },
231
    /// Offer a held build again (it rolled back on a runner)
232
    Lift { version: String },
233
}
234
235
#[derive(Subcommand)]
236
enum AuthCmd {
237
    /// Sign in to a hub and make it the default: approve a code on the web
238
    /// (device sign-in), or give a token
239
    Login {
240
        /// The hub, e.g. https://oxygenhub.io
241
        #[arg(long = "with-hub", value_name = "URL")]
242
        url: String,
243
        /// An API token from the hub's Settings → Tokens, instead of
244
        /// approving a code ("-" reads it from stdin)
245
        #[arg(long)]
246
        token: Option<String>,
247
        /// The hub's CA certificate, when self-signed
248
        #[arg(long)]
249
        ca: Option<std::path::PathBuf>,
250
    },
251
    /// Who the token in use belongs to
252
    Status,
253
}
254
255
#[derive(Subcommand)]
256
enum RepoCmd {
257
    /// Name, description, visibility and default bookmark
258
    View,
259
}
260
261
#[derive(Subcommand)]
262
enum IssueCmd {
263
    /// Put labels on an issue or take them off (triage)
264
    Label(LabelChange),
265
    /// Open issues (or --state closed|all)
266
    List {
267
        #[arg(long, default_value = "open")]
268
        state: String,
269
    },
270
    /// One issue with its comments
271
    View { number: i64 },
272
    /// Open an issue
273
    Create {
274
        #[arg(long, short)]
275
        title: String,
276
        #[arg(long, short)]
277
        body: Option<String>,
278
        /// Read the body from a file ("-" for stdin)
279
        #[arg(long, short = 'F')]
280
        body_file: Option<String>,
281
        /// A label (repeatable)
282
        #[arg(long, short)]
283
        label: Vec<String>,
284
        /// Also put it on this board of the repository's owner
285
        #[arg(long, short)]
286
        project: Option<i64>,
287
        /// The board's column for it, by name (default: the first)
288
        #[arg(long, requires = "project")]
289
        column: Option<String>,
290
    },
291
    /// Close an issue
292
    Close {
293
        number: i64,
294
        /// `completed` or `not_planned`
295
        #[arg(long, default_value = "completed")]
296
        reason: String,
297
    },
298
    /// Reopen an issue
299
    Reopen { number: i64 },
300
    /// Change an issue's title or body (its author or triage), or its
301
    /// labels, assignees or milestone as whole sets (triage)
302
    Edit {
303
        number: i64,
304
        #[arg(long, short)]
305
        title: Option<String>,
306
        #[arg(long, short)]
307
        body: Option<String>,
308
        /// Read the body from a file ("-" for stdin)
309
        #[arg(long, short = 'F', conflicts_with = "body")]
310
        body_file: Option<String>,
311
        /// The labels it should have (repeatable; `oh issue label` adds and removes)
312
        #[arg(long, short)]
313
        label: Vec<String>,
314
        /// Clear its labels
315
        #[arg(long, conflicts_with = "label")]
316
        no_labels: bool,
317
        /// The users it should be assigned to (repeatable)
318
        #[arg(long, short)]
319
        assignee: Vec<String>,
320
        /// Take everyone off it
321
        #[arg(long, conflicts_with = "assignee")]
322
        no_assignees: bool,
323
        /// A milestone's title ("" takes it out of its milestone)
324
        #[arg(long, short)]
325
        milestone: Option<String>,
326
    },
327
    /// Comment on an issue
328
    Comment {
329
        number: i64,
330
        #[arg(long, short)]
331
        body: String,
332
    },
333
}
334
335
#[derive(Subcommand)]
336
enum ProposalCmd {
337
    /// Open proposals (or --state draft|landed|closed|all), newest first
338
    List {
339
        #[arg(long, default_value = "open")]
340
        state: String,
341
        /// At most this many
342
        #[arg(long, default_value_t = 30)]
343
        limit: usize,
344
    },
345
    /// One proposal: its changes, approvals and whether it can land
346
    View { number: i64 },
347
    /// Propose a bookmark's changes for another bookmark
348
    Create {
349
        #[arg(long, short)]
350
        title: String,
351
        #[arg(long, short)]
352
        body: Option<String>,
353
        /// Read the body from a file ("-" for stdin)
354
        #[arg(long, short = 'F', conflicts_with = "body")]
355
        body_file: Option<String>,
356
        /// The bookmark with the changes (or OWNER/NAME:BOOKMARK of a fork)
357
        #[arg(long)]
358
        from: String,
359
        /// The bookmark to land them on (default: the repository's default bookmark)
360
        #[arg(long)]
361
        into: Option<String>,
362
        #[arg(long)]
363
        draft: bool,
364
    },
365
    /// Change a proposal's title or description (its author or a maintainer)
366
    Edit {
367
        number: i64,
368
        #[arg(long, short)]
369
        title: Option<String>,
370
        #[arg(long, short)]
371
        body: Option<String>,
372
        /// Read the body from a file ("-" for stdin)
373
        #[arg(long, short = 'F', conflicts_with = "body")]
374
        body_file: Option<String>,
375
    },
376
    /// Put labels on a proposal or take them off (triage)
377
    Label(LabelChange),
378
    /// Comment on a proposal's conversation
379
    Comment {
380
        number: i64,
381
        #[arg(long, short)]
382
        body: Option<String>,
383
        /// Read the comment from a file ("-" for stdin)
384
        #[arg(long, short = 'F', conflicts_with = "body")]
385
        body_file: Option<String>,
386
    },
387
    /// The checks on a proposal's projected state
388
    Checks { number: i64 },
389
    /// Land a proposal on its target, as the page's Land button does
390
    Land {
391
        number: i64,
392
        /// Land before its required checks pass, saying why (maintainers;
393
        /// recorded and audited, #261)
394
        #[arg(long, value_name = "REASON", conflicts_with = "when_ready")]
395
        over_checks: Option<String>,
396
        /// Land it by itself once its checks pass (#261); with --off, don't
397
        #[arg(long)]
398
        when_ready: bool,
399
        /// With --when-ready: turn it off
400
        #[arg(long, requires = "when_ready")]
401
        off: bool,
402
    },
403
    /// Close a proposal without landing it, with an optional comment
404
    Close {
405
        number: i64,
406
        /// Say why, as a comment before it closes
407
        #[arg(long, short = 'm')]
408
        message: Option<String>,
409
    },
410
    /// Reopen a closed proposal
411
    Reopen { number: i64 },
412
    /// Take a draft proposal out of draft, ready for review (its author or triage)
413
    Ready {
414
        number: i64,
415
        /// Turn an open proposal back into a draft instead
416
        #[arg(long)]
417
        undo: bool,
418
    },
419
}
420
421
#[derive(Subcommand)]
422
enum AssistantCmd {
423
    /// The assistants this level sees, its own and those inherited
424
    List,
425
    /// Add an assistant, or change the one of that name
426
    Add {
427
        /// How it shows on reviews (default: the provider's name)
428
        #[arg(long, default_value = "")]
429
        name: String,
430
        /// anthropic, openai, gemini, deepseek, mistral, perplexity or ollama
431
        #[arg(long, default_value = "")]
432
        preset: String,
433
        /// The endpoint, when no preset or another one
434
        #[arg(long, default_value = "")]
435
        endpoint: String,
436
        /// chat-completions or anthropic-messages
437
        #[arg(long, default_value = "")]
438
        api: String,
439
        /// One the endpoint lists (`oh assistant models` shows them)
440
        #[arg(long)]
441
        model: String,
442
        /// The API key, read from this environment variable (never typed on the command line)
443
        #[arg(long, value_name = "VAR")]
444
        token_env: Option<String>,
445
        /// Add it turned off
446
        #[arg(long)]
447
        off: bool,
448
    },
449
    /// Remove this level's assistant of that name
450
    Remove { name: String },
451
    /// Show this level's prompt, and those it inherits
452
    Prompt {
453
        /// Set it from this file (`-` for standard input; an empty file clears it)
454
        #[arg(long, value_name = "FILE")]
455
        set: Option<std::path::PathBuf>,
456
    },
457
}
458
459
#[derive(Subcommand)]
460
enum LabelCmd {
461
    /// The repository's labels
462
    List,
463
    /// Create a label, or change the one of that name (triage)
464
    Create {
465
        name: String,
466
        /// `#rrggbb` (default: one the hub picks)
467
        #[arg(long)]
468
        colour: Option<String>,
469
        #[arg(long, short, default_value = "")]
470
        description: String,
471
    },
472
    /// Delete a label, taking it off every issue and proposal (triage)
473
    Delete { name: String },
474
}
475
476
#[derive(Subcommand)]
477
enum ProjectCmd {
478
    /// The owner's boards
479
    List,
480
    /// One board: its columns and cards
481
    View {
482
        number: i64,
483
        /// Its archived cards instead (#293)
484
        #[arg(long)]
485
        archived: bool,
486
    },
487
    /// Create a board (owner, or an organisation's members)
488
    Create {
489
        title: String,
490
        #[arg(long, short, default_value = "")]
491
        description: String,
492
        /// Only the owner (or the organisation's members) can see it
493
        #[arg(long)]
494
        private: bool,
495
    },
496
    /// Close a board
497
    Close { number: i64 },
498
    /// Reopen a board
499
    Reopen { number: i64 },
500
    /// Move a board to another owner you may make boards under (an
501
    /// organisation, say); it takes the next number there
502
    Transfer {
503
        number: i64,
504
        /// The new owner
505
        #[arg(long)]
506
        to: String,
507
    },
508
    /// Cards on a board: add, move, archive, restore, remove
509
    Card {
510
        #[command(subcommand)]
511
        cmd: CardCmd,
512
    },
513
}
514
515
#[derive(Subcommand)]
516
enum CardCmd {
517
    /// Put an issue or proposal on a board (`12` or `#12` in this
518
    /// repository, `name#12` or `owner/name#12` in another of the owner's),
519
    /// or a note with --note
520
    Add {
521
        number: i64,
522
        /// The issue or proposal; a number means this repository's
523
        reference: Option<String>,
524
        /// A note card instead
525
        #[arg(long, conflicts_with = "reference")]
526
        note: Option<String>,
527
        /// The column, by name or id (default: the first)
528
        #[arg(long, short)]
529
        column: Option<String>,
530
    },
531
    /// Move a card to another column (by name or id), or with --from every
532
    /// card of a column at once
533
    Move {
534
        number: i64,
535
        /// The card (its id); leave it out with --from
536
        card: Option<i64>,
537
        #[arg(long, short)]
538
        column: String,
539
        /// Move every card of this column (#289)
540
        #[arg(long, conflicts_with = "card")]
541
        from: Option<String>,
542
        /// With --from: leave these where they are (card ids, or 12, #12, name#12, owner/name#12), comma-separated
543
        #[arg(long, value_delimiter = ',', requires = "from")]
544
        except: Vec<String>,
545
        /// With --from: only cards whose issue or proposal is in one of these states (closed, landed…), comma-separated
546
        #[arg(long, value_delimiter = ',', requires = "from")]
547
        state: Vec<String>,
548
        /// With --from: say what would move, and move nothing
549
        #[arg(long, requires = "from")]
550
        dry_run: bool,
551
    },
552
    /// Archive a column's cards: off the board, kept and restorable (#293)
553
    Archive {
554
        number: i64,
555
        /// The column, by name or id
556
        #[arg(long)]
557
        from: String,
558
        /// Only cards that joined the column more than this long ago (14d, or 14)
559
        #[arg(long)]
560
        older: Option<String>,
561
        /// Leave these on the board (card ids, or 12, #12, name#12, owner/name#12), comma-separated
562
        #[arg(long, value_delimiter = ',')]
563
        except: Vec<String>,
564
        /// Only cards whose issue or proposal is in one of these states (closed, landed…), comma-separated
565
        #[arg(long, value_delimiter = ',')]
566
        state: Vec<String>,
567
        /// Say what would be archived, and archive nothing
568
        #[arg(long)]
569
        dry_run: bool,
570
    },
571
    /// Put an archived card back at the end of its column
572
    Restore { number: i64, card: i64 },
573
    /// Take a card off a board
574
    Remove { number: i64, card: i64 },
575
}
576
577
#[derive(Subcommand)]
578
enum MilestoneCmd {
579
    /// The repository's milestones
580
    List,
581
    /// Create a milestone, or change the one of that title (triage)
582
    Create {
583
        title: String,
584
        #[arg(long, short, default_value = "")]
585
        description: String,
586
        /// Due date, YYYY-MM-DD
587
        #[arg(long)]
588
        due: Option<String>,
589
    },
590
    /// Change a milestone's title, description or due date (triage)
591
    Edit {
592
        title: String,
593
        #[arg(long, short)]
594
        rename: Option<String>,
595
        #[arg(long, short)]
596
        description: Option<String>,
597
        /// Due date, YYYY-MM-DD ("" for none)
598
        #[arg(long)]
599
        due: Option<String>,
600
    },
601
    /// Close a milestone
602
    Close { title: String },
603
    /// Reopen a milestone
604
    Reopen { title: String },
605
}
606
607
/// Labels to put on or take off an issue or proposal.
608
#[derive(clap::Args)]
609
struct LabelChange {
610
    number: i64,
611
    /// A label to add (repeatable)
612
    #[arg(long, short)]
613
    add: Vec<String>,
614
    /// A label to take off (repeatable)
615
    #[arg(long, short)]
616
    remove: Vec<String>,
617
}
618
619
impl LabelChange {
620
    /// The set after the change, from the one there now.
621
    fn apply(&self, now: &[hub_api::Label]) -> Result<Vec<String>> {
622
        if self.add.is_empty() && self.remove.is_empty() {
623
            bail!("say what to change: --add NAME or --remove NAME");
624
        }
625
        let mut names: Vec<String> = now.iter().map(|l| l.name.clone()).filter(|n| !self.remove.contains(n)).collect();
626
        for a in &self.add {
627
            if !names.contains(a) {
628
                names.push(a.clone());
629
            }
630
        }
631
        Ok(names)
632
    }
633
}
634
635
fn label_names(labels: &[String]) -> String {
636
    if labels.is_empty() {
637
        ui::dim("no labels")
638
    } else {
639
        labels.iter().map(|l| format!("[{l}]")).collect::<Vec<_>>().join(" ")
640
    }
641
}
642
643
#[derive(Subcommand)]
644
enum CoverageCmd {
645
    /// Upload an LCOV or Cobertura report measured on this machine, as the
646
    /// coverage of a bookmark's current state (default: the default
647
    /// bookmark) or of one change's. The hub shows it as uploaded by you,
648
    /// not measured by a runner, and sets no check from it
649
    Upload {
650
        file: std::path::PathBuf,
651
        #[arg(long)]
652
        bookmark: Option<String>,
653
        /// A change's full hash
654
        #[arg(long, conflicts_with = "bookmark")]
655
        change: Option<String>,
656
    },
657
}
658
659
#[derive(Subcommand)]
660
enum RunCmd {
661
    /// Recent runs, newest first
662
    List {
663
        #[arg(long, default_value_t = 20)]
664
        limit: i64,
665
    },
666
    /// A run and its jobs
667
    View {
668
        number: i64,
669
        /// Each job's wait, phases (image, prepare, run, finish) and peak disk and memory
670
        #[arg(long)]
671
        timings: bool,
672
    },
673
    /// Run the pipeline without a push: a bookmark's current state (default: the default bookmark), or one change's
674
    Start {
675
        #[arg(long)]
676
        bookmark: Option<String>,
677
        /// A change's full hash
678
        #[arg(long, conflicts_with = "bookmark")]
679
        change: Option<String>,
680
        /// Only this job, with the jobs it depends on (repeatable; default: every job a manual run starts)
681
        #[arg(long = "job", value_name = "NAME")]
682
        jobs: Vec<String>,
683
        /// Wait for the run and exit 1 unless it passes
684
        #[arg(long)]
685
        watch: bool,
686
    },
687
    /// Follow a run until it finishes; exit 1 unless it passes
688
    Watch { number: i64 },
689
    /// A job's log
690
    Log { number: i64, job: String },
691
    /// A report a job published: its report.toml; --list for what it holds, --file for one file
692
    Report {
693
        number: i64,
694
        job: String,
695
        #[command(flatten)]
696
        pick: ReportPick,
697
    },
698
    /// Run a finished run's state again; with --job, only that job (and the
699
    /// jobs that depend on it) in the same run
700
    Rerun {
701
        number: i64,
702
        #[arg(long)]
703
        job: Option<String>,
704
    },
705
    /// Cancel a run still queued or running; its running jobs are stopped
706
    Cancel { number: i64 },
707
    /// Approve a job that waits for a person (oxygenflow#57)
708
    Approve {
709
        number: i64,
710
        #[arg(long)]
711
        job: String,
712
    },
713
    /// Reject a job that waits for a person: it ends cancelled
714
    Reject {
715
        number: i64,
716
        #[arg(long)]
717
        job: String,
718
    },
719
}
720
721
/// Which report of a job, and what of it to show.
722
#[derive(clap::Args)]
723
struct ReportPick {
724
    /// Which report, when the job published more than one
725
    #[arg(long)]
726
    name: Option<String>,
727
    /// What it holds: its metrics, context and files
728
    #[arg(long, conflicts_with = "file")]
729
    list: bool,
730
    /// One file of it (`data/frames.csv`), as published
731
    #[arg(long, value_name = "PATH")]
732
    file: Option<String>,
733
    /// Write the file here instead of to stdout
734
    #[arg(long, short, value_name = "FILE", requires = "file")]
735
    output: Option<std::path::PathBuf>,
736
}
737
738
#[derive(Subcommand)]
739
enum ReportCmd {
740
    /// The newest run of each report, newest first
741
    List {
742
        /// Only runs on this bookmark
743
        #[arg(long)]
744
        bookmark: Option<String>,
745
    },
746
    /// One report: its newest run on the default bookmark (or --bookmark), or the run --id names
747
    Show {
748
        report: String,
749
        #[arg(long, conflicts_with = "bookmark")]
750
        id: Option<i64>,
751
        #[arg(long)]
752
        bookmark: Option<String>,
753
        /// What it holds: its metrics, context and files
754
        #[arg(long, conflicts_with = "file")]
755
        list: bool,
756
        /// One file of it, as published
757
        #[arg(long, value_name = "PATH")]
758
        file: Option<String>,
759
        /// Write the file here instead of to stdout
760
        #[arg(long, short, value_name = "FILE", requires = "file")]
761
        output: Option<std::path::PathBuf>,
762
    },
763
}
764
765
#[derive(Subcommand)]
766
enum TagCmd {
767
    /// Tags, newest name first
768
    List,
769
    /// Tag the state of a bookmark, tag or change, signed by the hub as your
770
    /// delegate (as `oxy tag create` and a push would be)
771
    Create {
772
        name: String,
773
        /// What to tag (default: the default bookmark)
774
        #[arg(long)]
775
        target: Option<String>,
776
        #[arg(long, short)]
777
        message: Option<String>,
778
    },
779
    /// Withdraw a tag: a signed withdrawal, kept and logged; clones drop it on
780
    /// their next fetch, and the name is never used again. Refused while a
781
    /// release uses the tag
782
    Delete {
783
        name: String,
784
        /// Why, recorded with the withdrawal
785
        #[arg(long, short)]
786
        reason: Option<String>,
787
    },
788
}
789
790
#[derive(Subcommand)]
791
enum ReleaseCmd {
792
    /// Releases, newest first
793
    List,
794
    /// Create a release on an existing tag
795
    Create {
796
        tag: String,
797
        #[arg(long, short)]
798
        title: Option<String>,
799
        /// Notes in Markdown (default: generated from the changes since the previous release)
800
        #[arg(long, short)]
801
        notes: Option<String>,
802
        #[arg(long)]
803
        prerelease: bool,
804
    },
805
    /// Change a release's title, notes or prerelease flag
806
    Edit {
807
        tag: String,
808
        #[arg(long, short)]
809
        title: Option<String>,
810
        /// New notes in Markdown ("-" reads them from stdin)
811
        #[arg(long, short)]
812
        notes: Option<String>,
813
        /// Mark it a prerelease (true) or not (false)
814
        #[arg(long)]
815
        prerelease: Option<bool>,
816
    },
817
    /// Attach files to a release
818
    Upload { tag: String, files: Vec<std::path::PathBuf> },
819
    /// The release's trust report: signatures, builds, receipts and audit
820
    Trust { tag: String },
821
}
822
823
fn main() {
824
    // `oh issue view 90 | head -1`: die quietly on SIGPIPE, as oxy and
825
    // other command-line tools do, instead of panicking on the failed
826
    // write (oxygenhub#92).
827
    #[cfg(unix)]
828
    unsafe {
829
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
830
    }
831
    let cli = Cli::parse();
832
    ui::init(cli.plain);
833
    match run(cli) {
834
        Ok(code) => std::process::exit(code),
835
        Err(e) => {
836
            eprintln!("{} {e:#}", ui::bad("error:"));
837
            std::process::exit(2);
838
        }
839
    }
840
}
841
842
fn enc(s: &str) -> String {
843
    let mut out = String::new();
844
    for b in s.bytes() {
845
        if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
846
            out.push(b as char);
847
        } else {
848
            out.push_str(&format!("%{b:02X}"));
849
        }
850
    }
851
    out
852
}
853
854
fn run(cli: Cli) -> Result<i32> {
855
    let cfg = Config::load()?;
856
    if let Cmd::Auth { cmd: AuthCmd::Login { url, token, ca } } = &cli.cmd {
857
        return login(cfg, url, token.clone(), ca.clone());
858
    }
859
    let here = std::env::current_dir()?;
860
    let t = target::resolve(&Choice { repo: cli.repo.as_deref(), hub: cli.hub.as_deref(), remote: cli.remote.as_deref() }, &here, &cfg)?;
861
    let c = Client::new(&t)?;
862
    let json = cli.json;
863
    match cli.cmd {
864
        Cmd::Auth { cmd: AuthCmd::Status } => {
865
            let me: serde_json::Value = c.get("/user")?;
866
            if json {
867
                println!("{me}");
868
            } else {
869
                println!("{} signed in to {} as {}", ui::ok("✔"), t.hub, ui::strong(me["username"].as_str().unwrap_or("?")));
870
            }
871
            Ok(0)
872
        }
873
        Cmd::Auth { .. } => unreachable!(),
874
        Cmd::Api { path, method, data } => {
875
            let path = if path.starts_with('/') { path } else { format!("/{path}") };
876
            let text = match data {
877
                Some(d) => c.send_text(
878
                    &method.to_uppercase(),
879
                    &path,
880
                    &serde_json::from_str::<serde_json::Value>(&d).context("--data is not JSON")?,
881
                )?,
882
                None => c.get_text(&path)?,
883
            };
884
            println!("{text}");
885
            Ok(0)
886
        }
887
        Cmd::Repo { cmd: RepoCmd::View } => {
888
            let path = t.repo_path()?;
889
            if json {
890
                println!("{}", c.get_text(&path)?);
891
                return Ok(0);
892
            }
893
            let r: serde_json::Value = c.get(&path)?;
894
            println!("{} {}", ui::strong(&format!("{}/{}", t.owner, t.name)), ui::dim(r["visibility"].as_str().unwrap_or("")));
895
            if let Some(d) = r["description"].as_str().filter(|d| !d.is_empty()) {
896
                println!("{d}");
897
            }
898
            println!("{}", ui::kv("default bookmark", r["default_bookmark"].as_str().unwrap_or("")));
899
            println!("{}", ui::kv("clone", &format!("oxy clone {}/{}/{}", t.hub, t.owner, t.name)));
900
            Ok(0)
901
        }
902
        Cmd::Issue { cmd } => issue(&c, &t, cmd, json),
903
        Cmd::Proposal { cmd } => proposal(&c, &t, cmd, json),
904
        Cmd::Run { cmd } => flow(&c, &t, cmd, json),
905
        Cmd::Report { cmd } => report(&c, &t, cmd, json),
906
        Cmd::Coverage { cmd: CoverageCmd::Upload { file, bookmark, change } } => {
907
            let content = std::fs::read_to_string(&file).with_context(|| format!("read {}", file.display()))?;
908
            let mut body = serde_json::json!({ "content": content });
909
            if let Some(b) = bookmark {
910
                body["bookmark"] = b.into();
911
            }
912
            if let Some(ch) = change {
913
                body["change"] = ch.into();
914
            }
915
            let base = t.repo_path()?;
916
            let r: hub_api::CoverageReport = c.send("POST", &format!("{base}/coverage"), &body)?;
917
            if json {
918
                println!("{}", serde_json::to_string(&r)?);
919
            } else {
920
                let pct = r.percent.map(|p| format!("{p:.1}%")).unwrap_or_else(|| "no lines".into());
921
                let on = if r.bookmark.is_empty() { format!("state {}", &r.state[..12.min(r.state.len())]) } else { r.bookmark.clone() };
922
                println!(
923
                    "{} uploaded coverage {pct} ({} of {} lines, {} files) for {on} {}",
924
                    ui::ok("✔"),
925
                    r.lines_hit,
926
                    r.lines_found,
927
                    r.files,
928
                    ui::dim(&r.url)
929
                );
930
                if r.dropped > 0 {
931
                    println!("  {}", ui::dim(&format!("{} files it named are not in that state and were left out", r.dropped)));
932
                }
933
            }
934
            Ok(0)
935
        }
936
        Cmd::Release { cmd } => release(&c, &t, cmd, json),
937
        Cmd::Tag { cmd } => tag(&c, &t, cmd, json),
938
        Cmd::Label { cmd } => label(&c, &t, cmd, json),
939
        Cmd::Milestone { cmd } => milestone(&c, &t, cmd, json),
940
        Cmd::Project { cmd, owner } => project(&c, &t, cmd, owner, json),
941
        Cmd::Assistant { cmd, org, site } => assistant(&c, &t, cmd, org, site, json),
942
        Cmd::Agent { cmd } => agent(&c, cmd, json),
943
        Cmd::RunnerUpdates { cmd } => runner_updates(&c, cmd.unwrap_or(RunnerUpdatesCmd::Show), json),
944
        Cmd::Drop { cmd } => drop_cmd(&c, cmd, json),
945
    }
946
}
947
948
/// `on`/`off`/`inherit` as a setting: `Some(Some(b))` to set, `Some(None)` to inherit.
949
fn switch(v: Option<&str>) -> Result<Option<Option<bool>>> {
950
    Ok(match v {
951
        None => None,
952
        Some("on") => Some(Some(true)),
953
        Some("off") => Some(Some(false)),
954
        Some("inherit") => Some(None),
955
        Some(other) => bail!("{other:?}: say on, off or inherit"),
956
    })
957
}
958
959
/// A scope as `oh runner-updates set` takes it, resolved to (scope, key).
960
fn update_scope(scope: &str, all: &hub_api::RunnerUpdates) -> Result<(String, String)> {
961
    let (kind, name) = scope.split_once(':').unwrap_or((scope, ""));
962
    Ok(match kind {
963
        "site" if name.is_empty() => ("site".into(), String::new()),
964
        "owner" if !name.is_empty() => ("owner".into(), name.into()),
965
        "group" => {
966
            let g = all
967
                .groups
968
                .iter()
969
                .find(|g| g.id.to_string() == name || g.name == name || format!("{}/{}", g.owner, g.name) == name)
970
                .with_context(|| format!("no test group {name:?} (see `oh runner-updates`)"))?;
971
            ("group".into(), g.id.to_string())
972
        }
973
        "runner" => {
974
            let r = all
975
                .runners
976
                .iter()
977
                .find(|r| r.id.to_string() == name || r.name == name)
978
                .with_context(|| format!("no runner {name:?} (see `oh runner-updates`)"))?;
979
            ("runner".into(), r.id.to_string())
980
        }
981
        _ => bail!("{scope:?}: say site, owner:NAME, group:NAME or runner:NAME"),
982
    })
983
}
984
985
fn runner_updates(c: &Client, cmd: RunnerUpdatesCmd, json: bool) -> Result<i32> {
986
    let all: hub_api::RunnerUpdates = c.get("/admin/runner-updates")?;
987
    match cmd {
988
        RunnerUpdatesCmd::Show if json => println!("{}", serde_json::to_string_pretty(&all)?),
989
        RunnerUpdatesCmd::Show => {
990
            println!(
991
                "{} {}",
992
                ui::strong("Builds from"),
993
                if all.repo.is_empty() { ui::dim("no repository: no runner is offered a build") } else { all.repo.clone() }
994
            );
995
            for h in &all.holds {
996
                println!("{} flow {} held: rolled back on {} ({})", ui::warn("!"), h.version, h.runner, h.why);
997
            }
998
            for s in &all.settings {
999
                let mut said = vec![];
1000
                if let Some(u) = s.updates {
1001
                    said.push(format!("updates {}", if u { "on" } else { "off" }));
1002
                }
1003
                if let Some(ch) = &s.channel {
1004
                    said.push(format!("channel {ch}"));
1005
                }
1006
                if let Some(w) = &s.window {
1007
                    said.push(format!("window {w} UTC"));
1008
                }
1009
                if let Some(d) = s.dry_run {
1010
                    said.push(format!("dry run {}", if d { "on" } else { "off" }));
1011
                }
1012
                let level = if s.scope == "site" { "site".to_string() } else { format!("{}:{}", s.scope, s.key) };
1013
                println!("  {:<18} {}", level, if said.is_empty() { ui::dim("off unless chosen") } else { said.join(", ") });
1014
            }
1015
            for g in &all.groups {
1016
                let of = if g.owner.is_empty() { "the site's runners".to_string() } else { format!("{}'s runners", g.owner) };
1017
                let mut what = g.percent.map(|p| format!("{p}% of {of}")).unwrap_or_else(|| format!("chosen, of {of}"));
1018
                if let Some(w) = g.wave {
1019
                    what.push_str(&format!(", wave {w}"));
1020
                }
1021
                println!(
1022
                    "  group {} ({what}): {}",
1023
                    ui::strong(&g.name),
1024
                    if g.members.is_empty() { "none".into() } else { g.members.join(", ") }
1025
                );
1026
            }
1027
            for r in &all.runners {
1028
                let on = if r.updates { ui::ok(&format!("on, {}", r.channel)) } else { ui::dim("off") };
1029
                println!("  {:<16} flow {:<22} {} ({})  {}", r.name, r.version, on, r.from[0], ui::dim(&r.now));
1030
            }
1031
        }
1032
        RunnerUpdatesCmd::Set { scope, updates, channel, window, dry_run } => {
1033
            let (scope, key) = update_scope(&scope, &all)?;
1034
            let mut s = all.settings.iter().find(|x| x.scope == scope && x.key == key).cloned().unwrap_or(hub_api::UpdateSetting {
1035
                scope: scope.clone(),
1036
                key: key.clone(),
1037
                ..Default::default()
1038
            });
1039
            if let Some(u) = switch(updates.as_deref())? {
1040
                s.updates = u;
1041
            }
1042
            if let Some(d) = switch(dry_run.as_deref())? {
1043
                s.dry_run = d;
1044
            }
1045
            if let Some(ch) = channel {
1046
                s.channel = Some(ch).filter(|c| c != "inherit");
1047
            }
1048
            if let Some(w) = window {
1049
                s.window = Some(w).filter(|w| w != "inherit");
1050
            }
1051
            let out: serde_json::Value = serde_json::from_str(&c.send_text("PUT", "/admin/runner-updates/settings", &s)?)?;
1052
            println!("{} {}", ui::ok("✔"), out["notice"].as_str().unwrap_or("saved"));
1053
        }
1054
        RunnerUpdatesCmd::Lift { version } => {
1055
            c.send_text("POST", &format!("/admin/runner-updates/holds/{version}/lift"), &serde_json::json!({}))?;
1056
            println!("{} flow {version} is offered again where the settings say so", ui::ok("✔"));
1057
        }
1058
    }
1059
    Ok(0)
1060
}
1061
1062
/// A drop's id from an id or its address (`https://hub/owner/drops/ID`).
1063
fn drop_id(s: &str) -> Result<String> {
1064
    let id = s.trim().trim_end_matches('/').rsplit('/').next().unwrap_or("").to_string();
1065
    if id.len() < 16 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
1066
        bail!("{s:?} is not a drop's id or address");
1067
    }
1068
    Ok(id.to_ascii_lowercase())
1069
}
1070
1071
fn drop_line(d: &hub_api::Drop) -> String {
1072
    let title = if d.title.is_empty() { d.files.first().map(|f| f.name.clone()).unwrap_or_else(|| d.id.clone()) } else { d.title.clone() };
1073
    let files: Vec<&str> = d.files.iter().map(|f| f.name.as_str()).collect();
1074
    format!(
1075
        "{} {} {}{}",
1076
        ui::dim(&d.id),
1077
        ui::strong(&title),
1078
        if d.visibility == "secret" { ui::warn("secret ") } else { String::new() },
1079
        ui::dim(&format!("{} · {}", files.join(", "), ui::ago(d.updated_ms)))
1080
    )
1081
}
1082
1083
fn drop_cmd(c: &Client, cmd: DropCmd, json: bool) -> Result<i32> {
1084
    match cmd {
1085
        DropCmd::Create { files, secret, description, title } => {
1086
            let mut out = Vec::with_capacity(files.len());
1087
            for f in &files {
1088
                let name = f.file_name().and_then(|n| n.to_str()).with_context(|| format!("{} has no file name", f.display()))?;
1089
                let content =
1090
                    std::fs::read_to_string(f).with_context(|| format!("read {} (a drop made here holds text files)", f.display()))?;
1091
                out.push(hub_api::NewDropFile { name: name.to_string(), content });
1092
            }
1093
            let new =
1094
                hub_api::NewDrop { title: title.unwrap_or_default(), description: description.unwrap_or_default(), secret, files: out };
1095
            let d: hub_api::Drop = c.send("POST", "/drops", &new)?;
1096
            if json {
1097
                println!("{}", serde_json::to_string(&d)?);
1098
            } else {
1099
                println!("{} made {}drop {} {}", ui::ok("✔"), if secret { "secret " } else { "" }, ui::strong(&d.id), ui::dim(&d.url));
1100
                println!("  {}", ui::dim(&format!("oxy clone {}", d.clone_url)));
1101
            }
1102
        }
1103
        DropCmd::List { user } => {
1104
            let path = match &user {
1105
                Some(u) => format!("/users/{}/drops", enc(u)),
1106
                None => "/drops".to_string(),
1107
            };
1108
            if json {
1109
                println!("{}", c.get_text(&path)?);
1110
                return Ok(0);
1111
            }
1112
            let list: Vec<hub_api::Drop> = c.get(&path)?;
1113
            if list.is_empty() {
1114
                println!("{}", ui::dim("No drops."));
1115
            }
1116
            for d in &list {
1117
                println!("{}", drop_line(d));
1118
            }
1119
        }
1120
        DropCmd::View { id, file } => {
1121
            let path = format!("/drops/{}", drop_id(&id)?);
1122
            if json && file.is_none() {
1123
                println!("{}", c.get_text(&path)?);
1124
                return Ok(0);
1125
            }
1126
            let d: hub_api::Drop = c.get(&path)?;
1127
            if let Some(name) = file {
1128
                let f = d.files.iter().find(|f| f.name == name).with_context(|| format!("the drop has no file {name}"))?;
1129
                let content = f.content.as_deref().with_context(|| format!("{name} is not shown as text: download {}", f.raw_url))?;
1130
                print!("{content}");
1131
                return Ok(0);
1132
            }
1133
            println!("{}", drop_line(&d));
1134
            if !d.description.is_empty() {
1135
                println!("{}", d.description);
1136
            }
1137
            println!("{}", ui::kv("url", &d.url));
1138
            println!("{}", ui::kv("clone", &format!("oxy clone {}", d.clone_url)));
1139
            for f in &d.files {
1140
                println!("\n{} {}", ui::strong(&format!("── {}", f.name)), ui::dim(&format!("({} bytes)", f.size)));
1141
                match &f.content {
1142
                    Some(text) => {
1143
                        print!("{text}");
1144
                        if !text.ends_with('\n') && !text.is_empty() {
1145
                            println!();
1146
                        }
1147
                    }
1148
                    None => println!("{}", ui::dim(&format!("not text, or too large: {}", f.raw_url))),
1149
                }
1150
            }
1151
        }
1152
        DropCmd::Delete { id } => {
1153
            let id = drop_id(&id)?;
1154
            c.send_text("DELETE", &format!("/drops/{id}"), &serde_json::json!({}))?;
1155
            println!("{} drop {id}", ui::ok("✔ deleted"));
1156
        }
1157
    }
1158
    Ok(0)
1159
}
1160
1161
/// `30d`, `12h`, `90m` in milliseconds.
1162
fn duration_ms(s: &str) -> Result<i64> {
1163
    let s = s.trim();
1164
    let (n, unit) = s.split_at(s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len()));
1165
    let n: i64 = n.parse().with_context(|| format!("{s:?} is not a duration such as 30d, 12h or 90m"))?;
1166
    let per = match unit {
1167
        "d" => 86_400_000,
1168
        "h" => 3_600_000,
1169
        "m" => 60_000,
1170
        _ => bail!("{s:?} is not a duration such as 30d, 12h or 90m"),
1171
    };
1172
    if n <= 0 {
1173
        bail!("a grant must last some time");
1174
    }
1175
    Ok(n * per)
1176
}
1177
1178
fn agent(c: &Client, cmd: AgentCmd, json: bool) -> Result<i32> {
1179
    use oxy_core::cert::{Grant, SignedGrant};
1180
    use oxy_core::identity::{Identity, Scope};
1181
    match cmd {
1182
        AgentCmd::Grant { name, scope, lasts } => {
1183
            let home = oxy_core::repo::default_home();
1184
            let (me_id, sk) = oxy_core::repo::home_key(&home).map_err(|e| anyhow::anyhow!("{e}"))?.with_context(|| {
1185
                format!(
1186
                    "{} names no key of yours (author.key) with its secret: the grant is signed with your own key, in your own shell",
1187
                    home.display()
1188
                )
1189
            })?;
1190
            let me: serde_json::Value = c.get("/user")?;
1191
            let username = me["username"].as_str().context("the hub did not say who you are")?;
1192
            let hub = Identity::decode(&c.get_root_bytes("/.well-known/oxyhub-key")?).map_err(|e| anyhow::anyhow!("the hub's key: {e}"))?;
1193
            let scope = Scope::parse(&scope).map_err(|e| anyhow::anyhow!("{e}"))?;
1194
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
1195
            let grant = Grant {
1196
                grantor: me_id.hash(),
1197
                subject: format!("agent:{name}@{username}"),
1198
                issuer: hub.hash(),
1199
                scope,
1200
                not_before: (now - 60_000) as u64,
1201
                expires: (now + duration_ms(&lasts)?) as u64,
1202
            };
1203
            let signed = SignedGrant::sign(grant, &me_id, &sk);
1204
            let r: serde_json::Value =
1205
                c.send("POST", "/agents/grants", &serde_json::json!({ "grant": oxy_core::dsse::base64(&signed.encode()) }))?;
1206
            if json {
1207
                println!("{r}");
1208
                return Ok(0);
1209
            }
1210
            println!(
1211
                "{} {} to act for you as {} ({}), until {}",
1212
                ui::ok("✔ granted"),
1213
                ui::strong(&name),
1214
                r["subject"].as_str().unwrap_or(""),
1215
                r["scope"].as_str().unwrap_or(""),
1216
                ui::date(r["expires_ms"].as_i64().unwrap_or(0))
1217
            );
1218
            println!("  token (shown once): {}", r["token"].as_str().unwrap_or(""));
1219
            println!(
1220
                "  {}",
1221
                ui::dim("in the agent's shell: oxy auth grant, paste the token; then oxy config --user author.signer keyless")
1222
            );
1223
            println!("  {}", ui::dim(&format!("revoke it with: oh agent revoke {}", r["id"])));
1224
            Ok(0)
1225
        }
1226
        AgentCmd::List => {
1227
            let grants: Vec<serde_json::Value> = c.get("/agents/grants")?;
1228
            if json {
1229
                println!("{}", serde_json::to_string(&grants)?);
1230
                return Ok(0);
1231
            }
1232
            if grants.is_empty() {
1233
                println!("{}", ui::dim("no agent grants"));
1234
            }
1235
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
1236
            for g in grants {
1237
                let state = if g["revoked_ms"].is_i64() {
1238
                    ui::bad("revoked")
1239
                } else if g["expires_ms"].as_i64().unwrap_or(0) <= now {
1240
                    ui::dim("ended")
1241
                } else {
1242
                    ui::ok("live")
1243
                };
1244
                let used = g["last_used_ms"].as_i64().map(|t| format!("used {}", ui::ago(t))).unwrap_or_else(|| "never used".into());
1245
                println!(
1246
                    "#{:<4} {:<8} {} · {} · until {} · {}",
1247
                    g["id"],
1248
                    state,
1249
                    ui::strong(g["subject"].as_str().unwrap_or("")),
1250
                    g["scope"].as_str().unwrap_or(""),
1251
                    ui::date(g["expires_ms"].as_i64().unwrap_or(0)),
1252
                    ui::dim(&used)
1253
                );
1254
            }
1255
            Ok(0)
1256
        }
1257
        AgentCmd::Revoke { id } => {
1258
            c.send_text("DELETE", &format!("/agents/grants/{id}"), &serde_json::json!({}))?;
1259
            println!("{} grant #{id}: no more certificates under it", ui::ok("✔ revoked"));
1260
            Ok(0)
1261
        }
1262
    }
1263
}
1264
1265
fn login(mut cfg: Config, url: &str, token: Option<String>, ca: Option<std::path::PathBuf>) -> Result<i32> {
1266
    let hub = url.trim_end_matches('/').to_string();
1267
    let token = match token.as_deref() {
1268
        Some("-") => {
1269
            eprintln!("Paste a token from {hub}/settings/tokens, then press Enter:");
1270
            let mut line = String::new();
1271
            std::io::stdin().read_line(&mut line)?;
1272
            line.trim().to_string()
1273
        }
1274
        Some(t) => t.to_string(),
1275
        None => device_sign_in(&hub, ca.clone())?,
1276
    };
1277
    if token.is_empty() {
1278
        bail!("no token given");
1279
    }
1280
    let t = Target { hub: hub.clone(), token: Some(token.clone()), ca: ca.clone(), owner: String::new(), name: String::new() };
1281
    let me: serde_json::Value = Client::new(&t)?.get("/user").context("checking the token")?;
1282
    let account = me["username"].as_str().unwrap_or("?");
1283
    // One sign-in for oh and oxy alike: the token goes to oxy's store.
1284
    let key = oxy_core::credentials::hub_of(&hub).with_context(|| format!("{hub} is not a hub URL"))?;
1285
    let ca = ca.map(|c| std::fs::canonicalize(&c).unwrap_or(c));
1286
    oxy_core::credentials::Credentials::user().save(&key, &token, Some(account), ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?;
1287
    cfg.default_hub = Some(hub.clone());
1288
    cfg.save()?;
1289
    println!("{} signed in to {hub} as {}", ui::ok("✔"), ui::strong(account));
1290
    println!("{}", ui::dim("  oxy uses this sign-in too; oxy auth status lists it, oxy auth logout ends it"));
1291
    Ok(0)
1292
}
1293
1294
/// Device sign-in (oxygenhub#67): the hub gives a code, the user approves
1295
/// it on the web, and the token arrives here.
1296
fn device_sign_in(hub: &str, ca: Option<std::path::PathBuf>) -> Result<String> {
1297
    let t = Target { hub: hub.to_string(), token: None, ca, owner: String::new(), name: String::new() };
1298
    let c = Client::new(&t)?;
1299
    let host = std::fs::read_to_string("/etc/hostname")
1300
        .ok()
1301
        .or_else(|| std::env::var("COMPUTERNAME").ok())
1302
        .map(|h| h.trim().to_string())
1303
        .filter(|h| !h.is_empty());
1304
    let client = match host {
1305
        Some(h) => format!("oh on {h}"),
1306
        None => "oh".to_string(),
1307
    };
1308
    let scopes = ["repo:read", "repo:write", "proposals:write", "issues:write", "user:read"];
1309
    let (code, body) = c.post_raw("/device/code", &serde_json::json!({ "client": client, "scopes": scopes }))?;
1310
    let v: serde_json::Value = serde_json::from_str(&body).context("the hub's answer to a device code request")?;
1311
    if code != 200 {
1312
        bail!("{hub} cannot sign in a device: {}", v["error_description"].as_str().or(v["detail"].as_str()).unwrap_or(&body));
1313
    }
1314
    let device = v["device_code"].as_str().context("no device code")?.to_string();
1315
    let user = v["user_code"].as_str().unwrap_or("?");
1316
    let url = v["verification_uri_complete"].as_str().or(v["verification_uri"].as_str()).unwrap_or(hub);
1317
    let mut interval = v["interval"].as_u64().unwrap_or(5).max(1);
1318
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(v["expires_in"].as_u64().unwrap_or(900));
1319
    eprintln!("Open {} and approve the code {}", ui::strong(url), ui::strong(user));
1320
    eprintln!("{}", ui::dim("Waiting for approval (Ctrl-C to give up)…"));
1321
    loop {
1322
        std::thread::sleep(std::time::Duration::from_secs(interval));
1323
        if std::time::Instant::now() > deadline {
1324
            bail!("the code expired before it was approved; run oh auth login again");
1325
        }
1326
        let (code, body) = c.post_raw("/device/token", &serde_json::json!({ "device_code": device }))?;
1327
        let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
1328
        if code == 200 {
1329
            return v["access_token"].as_str().map(String::from).context("no token in the hub's answer");
1330
        }
1331
        match v["error"].as_str() {
1332
            Some("authorization_pending") => {}
1333
            Some("slow_down") => interval += 5,
1334
            Some("access_denied") => bail!("the sign-in was denied on the web"),
1335
            Some("expired_token") => bail!("the code expired before it was approved; run oh auth login again"),
1336
            _ => bail!("signing in: HTTP {code}: {body}"),
1337
        }
1338
    }
1339
}
1340
1341
fn body_of(body: Option<String>, file: Option<String>) -> Result<String> {
1342
    match (body, file) {
1343
        (Some(b), _) => Ok(b),
1344
        (None, Some(f)) if f == "-" => {
1345
            let mut s = String::new();
1346
            std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
1347
            Ok(s)
1348
        }
1349
        (None, Some(f)) => std::fs::read_to_string(&f).with_context(|| format!("read {f}")),
1350
        (None, None) => Ok(String::new()),
1351
    }
1352
}
1353
1354
fn issue_line(i: &Issue) -> String {
1355
    let glyph = if i.state == "open" { ui::ok("●") } else { ui::dim("○") };
1356
    let labels: Vec<String> = i.labels.iter().map(|l| format!("[{}]", l.name)).collect();
1357
    format!(
1358
        "{glyph} {} {}{}{}",
1359
        ui::dim(&format!("#{}", i.number)),
1360
        i.title,
1361
        if labels.is_empty() { String::new() } else { format!(" {}", ui::dim(&labels.join(" "))) },
1362
        ui::dim(&format!(" · {} · {}", i.author, ui::ago(i.updated_ms)))
1363
    )
1364
}
1365
1366
fn issue(c: &Client, t: &Target, cmd: IssueCmd, json: bool) -> Result<i32> {
1367
    let base = t.repo_path()?;
1368
    match cmd {
1369
        IssueCmd::List { state } => {
1370
            let path = format!("{base}/issues?state={}", enc(&state));
1371
            if json {
1372
                println!("{}", c.get_text(&path)?);
1373
                return Ok(0);
1374
            }
1375
            let list: Vec<Issue> = c.get(&path)?;
1376
            if list.is_empty() {
1377
                println!("{}", ui::dim(&format!("No {state} issues.")));
1378
            }
1379
            for i in &list {
1380
                println!("{}", issue_line(i));
1381
            }
1382
        }
1383
        IssueCmd::View { number } => {
1384
            let path = format!("{base}/issues/{number}");
1385
            if json {
1386
                println!("{}", c.get_text(&path)?);
1387
                return Ok(0);
1388
            }
1389
            let i: Issue = c.get(&path)?;
1390
            println!("{}", issue_line(&i));
1391
            if !i.body.trim().is_empty() {
1392
                println!("\n{}\n", i.body.trim_end());
1393
            }
1394
            let comments: Vec<hub_api::Comment> = c.get(&format!("{path}/comments"))?;
1395
            for cm in comments {
1396
                println!("{} {}\n{}\n", ui::strong(&cm.author), ui::dim(&ui::ago(cm.created_ms)), cm.body.trim_end());
1397
            }
1398
            println!("{}", ui::dim(&i.url));
1399
        }
1400
        IssueCmd::Create { title, body, body_file, label, project, column } => {
1401
            let new = NewIssue { title, body: body_of(body, body_file)?, labels: label, assignees: vec![], milestone: None };
1402
            let i: Issue = c.send("POST", &format!("{base}/issues"), &new)?;
1403
            if json {
1404
                println!("{}", serde_json::to_string(&i)?);
1405
            } else {
1406
                println!("{} opened #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
1407
            }
1408
            if let Some(n) = project {
1409
                let card = hub_api::NewCard { column, reference: format!("{}#{}", t.name, i.number), note: String::new() };
1410
                let added: hub_api::ProjectCard = c.send("POST", &format!("/projects/{}/{n}/cards", t.owner), &card)?;
1411
                if !json {
1412
                    println!("{} on project {n} as card {}", ui::ok("✔"), added.id);
1413
                }
1414
            }
1415
        }
1416
        IssueCmd::Close { number, reason } => {
1417
            let i: Issue = c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "closed".into(), reason })?;
1418
            println!("{} closed #{} {}", ui::ok("✔"), i.number, i.title);
1419
        }
1420
        IssueCmd::Reopen { number } => {
1421
            let i: Issue =
1422
                c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "open".into(), reason: String::new() })?;
1423
            println!("{} reopened #{} {}", ui::ok("✔"), i.number, i.title);
1424
        }
1425
        IssueCmd::Edit { number, title, body, body_file, label, no_labels, assignee, no_assignees, milestone } => {
1426
            let body = match (&body, &body_file) {
1427
                (None, None) => None,
1428
                _ => Some(body_of(body, body_file)?),
1429
            };
1430
            let labels = if no_labels {
1431
                Some(Vec::new())
1432
            } else if label.is_empty() {
1433
                None
1434
            } else {
1435
                Some(label)
1436
            };
1437
            let assignees = if no_assignees {
1438
                Some(Vec::new())
1439
            } else if assignee.is_empty() {
1440
                None
1441
            } else {
1442
                Some(assignee)
1443
            };
1444
            if title.is_none() && body.is_none() && labels.is_none() && assignees.is_none() && milestone.is_none() {
1445
                bail!("say what to change: --title, --body, --body-file, --label, --assignee or --milestone");
1446
            }
1447
            let edit = hub_api::IssueEdit { title, body, labels, assignees, milestone };
1448
            let i: Issue = c.send("PATCH", &format!("{base}/issues/{number}"), &edit)?;
1449
            if json {
1450
                println!("{}", serde_json::to_string(&i)?);
1451
            } else {
1452
                println!("{} edited #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
1453
            }
1454
        }
1455
        IssueCmd::Label(change) => {
1456
            let path = format!("{base}/issues/{}", change.number);
1457
            let now: Issue = c.get(&path)?;
1458
            let labels = change.apply(&now.labels)?;
1459
            let edit = hub_api::IssueEdit { title: None, body: None, labels: Some(labels.clone()), assignees: None, milestone: None };
1460
            let i: Issue = c.send("PATCH", &path, &edit)?;
1461
            if json {
1462
                println!("{}", serde_json::to_string(&i)?);
1463
            } else {
1464
                println!("{} #{} {}", ui::ok("✔"), i.number, label_names(&labels));
1465
            }
1466
        }
1467
        IssueCmd::Comment { number, body } => {
1468
            c.send_text("POST", &format!("{base}/issues/{number}/comments"), &NewComment { body, path: None, line: None })?;
1469
            println!("{} commented on #{number}", ui::ok("✔"));
1470
        }
1471
    }
1472
    Ok(0)
1473
}
1474
1475
fn source_name(s: &hub_api::ProposalSource) -> String {
1476
    match s {
1477
        hub_api::ProposalSource::Bookmark { bookmark } => bookmark.clone(),
1478
        hub_api::ProposalSource::Fork { owner, name, bookmark } => format!("{owner}/{name}:{bookmark}"),
1479
        hub_api::ProposalSource::Changes { hashes } => format!("{} changes", hashes.len()),
1480
    }
1481
}
1482
1483
fn proposal_line(p: &Proposal) -> String {
1484
    let state = serde_json::to_value(p.state).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default();
1485
    let glyph = match state.as_str() {
1486
        "open" => ui::ok("●"),
1487
        "draft" => ui::dim("◌"),
1488
        "landed" => ui::strong("✔"),
1489
        _ => ui::dim("○"),
1490
    };
1491
    format!(
1492
        "{glyph} {} {} {}{}",
1493
        ui::dim(&format!("#{}", p.number)),
1494
        p.title,
1495
        ui::dim(&format!("{} → {}", source_name(&p.source), p.target)),
1496
        ui::dim(&format!(" · {} · {state}", p.author))
1497
    )
1498
}
1499
1500
fn proposal(c: &Client, t: &Target, cmd: ProposalCmd, json: bool) -> Result<i32> {
1501
    let base = t.repo_path()?;
1502
    match cmd {
1503
        ProposalCmd::List { state, limit } => {
1504
            let path = format!("{base}/proposals?state={state}&limit={limit}");
1505
            if json {
1506
                println!("{}", c.get_text(&path)?);
1507
                return Ok(0);
1508
            }
1509
            let list: Vec<Proposal> = c.get(&path)?;
1510
            if list.is_empty() {
1511
                println!("{}", ui::dim(&format!("No {} proposals.", if state == "all" { "" } else { &state }).replace("  ", " ")));
1512
            }
1513
            for p in &list {
1514
                println!("{}", proposal_line(p));
1515
            }
1516
        }
1517
        ProposalCmd::View { number } => {
1518
            let path = format!("{base}/proposals/{number}");
1519
            if json {
1520
                println!("{}", c.get_text(&path)?);
1521
                return Ok(0);
1522
            }
1523
            let p: Proposal = c.get(&path)?;
1524
            println!("{}", proposal_line(&p));
1525
            if !p.body.trim().is_empty() {
1526
                println!("\n{}\n", p.body.trim_end());
1527
            }
1528
            println!("{}", ui::kv("changes", &p.changes.len().to_string()));
1529
            for ch in &p.changes {
1530
                println!("  {} {}", ui::dim(&ch.hash[..12.min(ch.hash.len())]), ch.message.lines().next().unwrap_or(""));
1531
            }
1532
            println!("{}", ui::kv("approvals", &p.approvals.iter().map(|a| a.account.clone()).collect::<Vec<_>>().join(", ")));
1533
            if p.landable {
1534
                println!("{} can land", ui::ok("✔"));
1535
            } else {
1536
                for b in &p.blockers {
1537
                    println!("{} {b}", ui::bad("✘"));
1538
                }
1539
            }
1540
            if p.conflicted {
1541
                println!("{} landing it would leave conflicts", ui::bad("!"));
1542
            }
1543
            println!("{}", ui::dim(&p.url));
1544
        }
1545
        ProposalCmd::Create { title, body, body_file, from, into, draft } => {
1546
            let target = match into {
1547
                Some(i) => i,
1548
                None => c.get::<serde_json::Value>(&base)?["default_bookmark"].as_str().unwrap_or("main").to_string(),
1549
            };
1550
            let new = NewProposal { title, body: body_of(body, body_file)?, target, source: from, draft };
1551
            let p: Proposal = c.send("POST", &format!("{base}/proposals"), &new)?;
1552
            if json {
1553
                println!("{}", serde_json::to_string(&p)?);
1554
            } else {
1555
                println!("{} proposed #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
1556
            }
1557
        }
1558
        ProposalCmd::Edit { number, title, body, body_file } => {
1559
            let body = match (&body, &body_file) {
1560
                (None, None) => None,
1561
                _ => Some(body_of(body, body_file)?),
1562
            };
1563
            if title.is_none() && body.is_none() {
1564
                bail!("say what to change: --title, --body or --body-file");
1565
            }
1566
            let edit = hub_api::ProposalEdit { title, body, ..Default::default() };
1567
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
1568
            if json {
1569
                println!("{}", serde_json::to_string(&p)?);
1570
            } else {
1571
                println!("{} edited #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
1572
            }
1573
        }
1574
        ProposalCmd::Label(change) => {
1575
            let path = format!("{base}/proposals/{}", change.number);
1576
            let now: Proposal = c.get(&path)?;
1577
            let labels = change.apply(&now.labels)?;
1578
            let edit = hub_api::ProposalEdit { labels: Some(labels.clone()), ..Default::default() };
1579
            let p: Proposal = c.send("PATCH", &path, &edit)?;
1580
            if json {
1581
                println!("{}", serde_json::to_string(&p)?);
1582
            } else {
1583
                println!("{} #{} {}", ui::ok("✔"), p.number, label_names(&labels));
1584
            }
1585
        }
1586
        ProposalCmd::Comment { number, body, body_file } => {
1587
            let body = body_of(body, body_file)?;
1588
            if body.trim().is_empty() {
1589
                bail!("give the comment with --body or --body-file");
1590
            }
1591
            c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
1592
            println!("{} commented on #{number}", ui::ok("✔"));
1593
        }
1594
        ProposalCmd::Land { number, when_ready: true, off, .. } => {
1595
            let path = format!("{base}/proposals/{number}/auto-land");
1596
            let p: Proposal =
1597
                if off { c.send("DELETE", &path, &serde_json::json!({}))? } else { c.send("POST", &path, &serde_json::json!({}))? };
1598
            if json {
1599
                println!("{}", serde_json::to_string(&p)?);
1600
            } else if p.landed.is_some() {
1601
                println!("{} landed #{} on {}: its checks had passed", ui::ok("✔"), p.number, p.target);
1602
            } else if p.auto_land.is_some() {
1603
                println!("{} #{} will land when its checks pass", ui::ok("✔"), p.number);
1604
            } else {
1605
                println!("{} #{} will not land by itself", ui::ok("✔"), p.number);
1606
            }
1607
        }
1608
        ProposalCmd::Land { number, over_checks, .. } => {
1609
            let body = match &over_checks {
1610
                Some(r) => serde_json::json!({ "over_checks": r }),
1611
                None => serde_json::json!({}),
1612
            };
1613
            let p: Proposal = c.send("POST", &format!("{base}/proposals/{number}/land"), &body)?;
1614
            if json {
1615
                println!("{}", serde_json::to_string(&p)?);
1616
            } else {
1617
                println!("{} landed #{} on {}", ui::ok("✔"), p.number, p.target);
1618
            }
1619
        }
1620
        ProposalCmd::Close { number, message } => {
1621
            if let Some(body) = message {
1622
                c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
1623
            }
1624
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "closed" }))?;
1625
            if json {
1626
                println!("{}", serde_json::to_string(&p)?);
1627
            } else {
1628
                println!("{} closed #{} {}", ui::ok("✔"), p.number, p.title);
1629
            }
1630
        }
1631
        ProposalCmd::Reopen { number } => {
1632
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "open" }))?;
1633
            if json {
1634
                println!("{}", serde_json::to_string(&p)?);
1635
            } else {
1636
                println!("{} reopened #{} {}", ui::ok("✔"), p.number, p.title);
1637
            }
1638
        }
1639
        ProposalCmd::Ready { number, undo } => {
1640
            let edit = hub_api::ProposalEdit { draft: Some(undo), ..Default::default() };
1641
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
1642
            if json {
1643
                println!("{}", serde_json::to_string(&p)?);
1644
            } else if undo {
1645
                println!("{} #{} {} is a draft again", ui::ok("✔"), p.number, p.title);
1646
            } else {
1647
                println!("{} #{} {} is ready for review", ui::ok("✔"), p.number, p.title);
1648
            }
1649
        }
1650
        ProposalCmd::Checks { number } => {
1651
            let path = format!("{base}/proposals/{number}/checks");
1652
            if json {
1653
                println!("{}", c.get_text(&path)?);
1654
                return Ok(0);
1655
            }
1656
            let checks: Vec<hub_api::Check> = c.get(&path)?;
1657
            if checks.is_empty() {
1658
                println!("{}", ui::dim("No checks yet."));
1659
            }
1660
            for ch in checks {
1661
                println!("{} {} {}", ui::status(ch.status.as_str()), ch.name, ui::dim(&ch.summary));
1662
            }
1663
        }
1664
    }
1665
    Ok(0)
1666
}
1667
1668
fn run_line(r: &FlowRun) -> String {
1669
    let what =
1670
        if r.bookmark.is_empty() { format!("change {}", r.heads.first().map(|h| &h[..12]).unwrap_or("")) } else { r.bookmark.clone() };
1671
    format!(
1672
        "{} {} {} {}",
1673
        ui::status(&r.status),
1674
        ui::dim(&format!("#{}", r.number)),
1675
        what,
1676
        ui::dim(&format!("· {} by {} · {}", r.trigger, r.actor, ui::ago(r.created_ms)))
1677
    )
1678
}
1679
1680
fn print_run(r: &FlowRun, timings: bool) {
1681
    println!("{}", run_line(r));
1682
    for j in &r.jobs {
1683
        let dur = match (j.started_ms, j.finished_ms) {
1684
            (Some(a), Some(b)) => format!(" {:.1} s", (b - a) as f64 / 1000.0),
1685
            _ => String::new(),
1686
        };
1687
        let on = if j.runner.is_empty() { String::new() } else { format!(" on {}", j.runner) };
1688
        println!("  {} {}{}", ui::status(&j.status), j.name, ui::dim(&format!("{dur}{on}")));
1689
        // Why a queued job no runner can take waits (oxygenhub#28), and
1690
        // why a job ran where it did (oxygenflow#42).
1691
        if j.status == "queued" && !j.waiting.is_empty() {
1692
            println!("    {}", ui::warn(&format!("waiting: {}", j.waiting)));
1693
        } else if !j.placed.is_empty() {
1694
            println!("    {}", ui::dim(&format!("placed: {}", j.placed)));
1695
        }
1696
        if timings {
1697
            let t = timing_line(j);
1698
            if !t.is_empty() {
1699
                println!("    {}", ui::dim(&t));
1700
            }
1701
        }
1702
    }
1703
    if !r.error.is_empty() {
1704
        println!("{}", ui::bad(&r.error));
1705
    }
1706
    println!("{}", ui::dim(&r.url));
1707
}
1708
1709
/// Milliseconds as a person reads them: "850 ms", "3.1 s", "2 min 5 s".
1710
fn took(ms: i64) -> String {
1711
    match ms {
1712
        ..=999 => format!("{ms} ms"),
1713
        1000..=59_999 => format!("{:.1} s", ms as f64 / 1000.0),
1714
        _ => format!("{} min {} s", ms / 60_000, (ms % 60_000) / 1000),
1715
    }
1716
}
1717
1718
/// MiB as a person reads them.
1719
fn mib(m: i64) -> String {
1720
    if m >= 1024 {
1721
        format!("{:.1} GiB", m as f64 / 1024.0)
1722
    } else {
1723
        format!("{m} MiB")
1724
    }
1725
}
1726
1727
/// Where a job's time went (oxygenhub#348): its wait for a runner, each
1728
/// phase its runner reported, and the most disk and memory it took.
1729
fn timing_line(j: &FlowJob) -> String {
1730
    let mut parts = vec![];
1731
    if let (Some(q), Some(s)) = (j.queued_ms, j.started_ms) {
1732
        parts.push(format!("waited {}", took((s - q).max(0))));
1733
    }
1734
    parts.extend(j.phases.iter().map(|p| format!("{} {}", p.name, took(p.ms as i64))));
1735
    let peaks: Vec<String> = [("disk", j.peak_disk_mib), ("memory", j.peak_memory_mib)]
1736
        .into_iter()
1737
        .filter_map(|(what, m)| m.map(|m| format!("{what} {}", mib(m))))
1738
        .collect();
1739
    if !peaks.is_empty() {
1740
        parts.push(format!("peak {}", peaks.join(", ")));
1741
    }
1742
    parts.join(" · ")
1743
}
1744
1745
/// A report's path, its segments encoded and its slashes kept.
1746
fn enc_path(path: &str) -> String {
1747
    path.split('/').map(enc).collect::<Vec<_>>().join("/")
1748
}
1749
1750
/// `oh run report` and `oh report show`: the report at `at` (JSON), whose
1751
/// files are at `files(path)`. By default its report.toml; with `list`
1752
/// what it holds; with `file` one file, to stdout or `output`.
1753
fn show_report(
1754
    c: &Client,
1755
    at: &str,
1756
    files: impl Fn(&str) -> String,
1757
    list: bool,
1758
    file: Option<String>,
1759
    output: Option<std::path::PathBuf>,
1760
    json: bool,
1761
) -> Result<()> {
1762
    use std::io::Write;
1763
    if let Some(path) = file {
1764
        let bytes = c.get_bytes(&files(&path))?;
1765
        match output {
1766
            Some(out) => {
1767
                std::fs::write(&out, &bytes).with_context(|| format!("writing {}", out.display()))?;
1768
                eprintln!("{} {path}: {} bytes to {}", ui::ok("✔"), bytes.len(), out.display());
1769
            }
1770
            None => std::io::stdout().write_all(&bytes)?,
1771
        }
1772
        return Ok(());
1773
    }
1774
    if json {
1775
        println!("{}", c.get_text(at)?);
1776
        return Ok(());
1777
    }
1778
    if !list {
1779
        std::io::stdout().write_all(&c.get_bytes(&files("report.toml"))?)?;
1780
        return Ok(());
1781
    }
1782
    let r: Report = c.get(at)?;
1783
    print_report(&r);
1784
    if r.files_expired_ms.is_some() {
1785
        println!("{}", ui::warn("its files expired under retention; its metrics stay"));
1786
    }
1787
    for f in &r.manifest {
1788
        println!("  {:>10}  {}", ui::dim(&f.size.to_string()), f.path);
1789
    }
1790
    println!("{}", ui::dim(&r.url));
1791
    Ok(())
1792
}
1793
1794
/// A report's heading, metrics and context.
1795
fn print_report(r: &Report) {
1796
    let from = match r.run {
1797
        Some(n) => format!("run #{n} {} on {}", r.job, r.bookmark),
1798
        None => format!("upload on {}", if r.bookmark.is_empty() { "a change" } else { &r.bookmark }),
1799
    };
1800
    println!(
1801
        "{} {} {}",
1802
        ui::strong(&r.name),
1803
        ui::dim(&format!("{} · {:?}", r.kind, r.title)),
1804
        ui::dim(&format!("· {from} · {} files", r.files))
1805
    );
1806
    if !r.summary.is_empty() {
1807
        println!("  {}", r.summary);
1808
    }
1809
    for m in &r.metrics {
1810
        let unit = if m.unit.is_empty() { String::new() } else { format!(" {}", m.unit) };
1811
        let mut notes = vec![];
1812
        if !m.better.is_empty() {
1813
            notes.push(format!("{} is better", m.better));
1814
        }
1815
        if let Some(a) = m.fail_above {
1816
            notes.push(format!("fails above {a}"));
1817
        }
1818
        if let Some(b) = m.fail_below {
1819
            notes.push(format!("fails below {b}"));
1820
        }
1821
        let notes = if notes.is_empty() { String::new() } else { format!("  ({})", notes.join(", ")) };
1822
        println!("  {} {}{unit}{}", m.key, m.value, ui::dim(&notes));
1823
    }
1824
    if let Some(ctx) = r.context.as_object().filter(|m| !m.is_empty()) {
1825
        let line: Vec<String> =
1826
            ctx.iter().map(|(k, v)| format!("{k}={}", v.as_str().map(String::from).unwrap_or_else(|| v.to_string()))).collect();
1827
        println!("  {}", ui::dim(&line.join(" ")));
1828
    }
1829
}
1830
1831
/// `oh report …` (oxygenhub#348).
1832
fn report(c: &Client, t: &Target, cmd: ReportCmd, json: bool) -> Result<i32> {
1833
    let base = t.repo_path()?;
1834
    match cmd {
1835
        ReportCmd::List { bookmark } => {
1836
            let path = format!("{base}/reports{}", bookmark.map(|b| format!("?bookmark={}", enc(&b))).unwrap_or_default());
1837
            if json {
1838
                println!("{}", c.get_text(&path)?);
1839
                return Ok(0);
1840
            }
1841
            let list: Vec<Report> = c.get(&path)?;
1842
            if list.is_empty() {
1843
                println!("{}", ui::dim("No reports yet: a Flow job publishes one with `output { report \"name\" { path … } }`."));
1844
            }
1845
            for r in &list {
1846
                print_report(r);
1847
            }
1848
        }
1849
        ReportCmd::Show { report, id, bookmark, list, file, output } => {
1850
            let at = format!("{base}/reports/{}", enc(&report));
1851
            let query = match (id, bookmark) {
1852
                (Some(id), _) => format!("?id={id}"),
1853
                (None, Some(b)) => format!("?bookmark={}", enc(&b)),
1854
                (None, None) => String::new(),
1855
            };
1856
            let files = |path: &str| format!("{at}/files/{}{query}", enc_path(path));
1857
            show_report(c, &format!("{at}{query}"), files, list, file, output, json)?;
1858
        }
1859
    }
1860
    Ok(0)
1861
}
1862
1863
fn live(status: &str) -> bool {
1864
    matches!(status, "queued" | "running")
1865
}
1866
1867
/// `oh run approve|reject N --job NAME` (oxygenflow#57).
1868
fn decide_job(c: &Client, base: &str, number: i64, job: &str, verb: &str, json: bool) -> Result<()> {
1869
    let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/{verb}"), &serde_json::json!({}))?;
1870
    if json {
1871
        println!("{done}");
1872
    } else {
1873
        println!("{} run #{number}: {}", ui::ok("✔"), done["said"].as_str().unwrap_or(""));
1874
    }
1875
    Ok(())
1876
}
1877
1878
fn watch(c: &Client, base: &str, number: i64, json: bool) -> Result<i32> {
1879
    let path = format!("{base}/flow/runs/{number}");
1880
    let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
1881
    loop {
1882
        let r: FlowRun = c.get(&path)?;
1883
        if !json {
1884
            for j in &r.jobs {
1885
                let shown = format!("{}\u{0}{}", j.status, j.waiting);
1886
                if seen.get(&j.name) != Some(&shown) {
1887
                    println!("{} {}", ui::status(&j.status), j.name);
1888
                    if j.status == "queued" && !j.waiting.is_empty() {
1889
                        println!("  {}", ui::warn(&format!("waiting: {}", j.waiting)));
1890
                    }
1891
                    seen.insert(j.name.clone(), shown);
1892
                }
1893
            }
1894
        }
1895
        if !live(&r.status) {
1896
            if json {
1897
                println!("{}", serde_json::to_string(&r)?);
1898
            } else {
1899
                println!("{} run #{} {}", ui::status(&r.status), r.number, r.status);
1900
            }
1901
            return Ok(if r.status == "passed" { 0 } else { 1 });
1902
        }
1903
        std::thread::sleep(Duration::from_secs(3));
1904
    }
1905
}
1906
1907
fn flow(c: &Client, t: &Target, cmd: RunCmd, json: bool) -> Result<i32> {
1908
    let base = t.repo_path()?;
1909
    match cmd {
1910
        RunCmd::List { limit } => {
1911
            let path = format!("{base}/flow/runs?limit={limit}");
1912
            if json {
1913
                println!("{}", c.get_text(&path)?);
1914
                return Ok(0);
1915
            }
1916
            let runs: Vec<FlowRun> = c.get(&path)?;
1917
            if runs.is_empty() {
1918
                println!("{}", ui::dim("No runs yet."));
1919
            }
1920
            for r in &runs {
1921
                println!("{}", run_line(r));
1922
            }
1923
        }
1924
        RunCmd::View { number, timings } => {
1925
            let path = format!("{base}/flow/runs/{number}");
1926
            if json {
1927
                println!("{}", c.get_text(&path)?);
1928
                return Ok(0);
1929
            }
1930
            print_run(&c.get(&path)?, timings);
1931
        }
1932
        RunCmd::Start { bookmark, change, jobs, watch: follow } => {
1933
            let mut body = match (bookmark, change) {
1934
                (_, Some(ch)) => serde_json::json!({ "change": ch }),
1935
                (Some(b), None) => serde_json::json!({ "bookmark": b }),
1936
                (None, None) => serde_json::json!({}),
1937
            };
1938
            if !jobs.is_empty() {
1939
                body["jobs"] = serde_json::json!(jobs);
1940
            }
1941
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs"), &body)?;
1942
            let n = started["number"].as_i64().context("the hub named no run")?;
1943
            if !json || !follow {
1944
                if json {
1945
                    println!("{started}");
1946
                } else {
1947
                    println!("{} started run #{n} {}", ui::ok("✔"), ui::dim(started["url"].as_str().unwrap_or("")));
1948
                }
1949
            }
1950
            if follow {
1951
                return watch(c, &base, n, json);
1952
            }
1953
        }
1954
        RunCmd::Watch { number } => return watch(c, &base, number, json),
1955
        RunCmd::Log { number, job } => {
1956
            let mut after = 0;
1957
            loop {
1958
                let path = format!("{base}/flow/runs/{number}/jobs/{}/log?after={after}&limit=5000", enc(&job));
1959
                let lines: Vec<FlowLogLine> = c.get(&path)?;
1960
                if lines.is_empty() {
1961
                    break;
1962
                }
1963
                for l in &lines {
1964
                    if json {
1965
                        println!("{}", serde_json::to_string(l)?);
1966
                    } else if l.stream == "flow" {
1967
                        println!("{}", ui::dim(&l.text));
1968
                    } else {
1969
                        println!("{}", l.text);
1970
                    }
1971
                }
1972
                after = lines.last().map(|l| l.seq).unwrap_or(after);
1973
            }
1974
        }
1975
        RunCmd::Report { number, job, pick } => {
1976
            let at = format!("{base}/flow/runs/{number}/jobs/{}/report", enc(&job));
1977
            let query = pick.name.as_deref().map(|n| format!("?name={}", enc(n))).unwrap_or_default();
1978
            let files = |path: &str| format!("{at}/{}{query}", enc_path(path));
1979
            show_report(c, &format!("{at}{query}"), files, pick.list, pick.file, pick.output, json)?;
1980
        }
1981
        RunCmd::Rerun { number, job: Some(job) } => {
1982
            let queued: serde_json::Value =
1983
                c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/rerun"), &serde_json::json!({}))?;
1984
            if json {
1985
                println!("{queued}");
1986
            } else {
1987
                let n = queued["queued"].as_i64().unwrap_or(1);
1988
                let with = if n > 1 { format!(" with the {} that depend on it", n - 1) } else { String::new() };
1989
                println!("{} queued {job} of run #{number} again{with}", ui::ok("✔"));
1990
            }
1991
        }
1992
        RunCmd::Rerun { number, job: None } => {
1993
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/rerun"), &serde_json::json!({}))?;
1994
            if json {
1995
                println!("{started}");
1996
            } else {
1997
                println!("{} started run #{} {}", ui::ok("✔"), started["number"], ui::dim(started["url"].as_str().unwrap_or("")));
1998
            }
1999
        }
2000
        RunCmd::Approve { number, job } => decide_job(c, &base, number, &job, "approve", json)?,
2001
        RunCmd::Reject { number, job } => decide_job(c, &base, number, &job, "reject", json)?,
2002
        RunCmd::Cancel { number } => {
2003
            let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/cancel"), &serde_json::json!({}))?;
2004
            if json {
2005
                println!("{done}");
2006
            } else {
2007
                println!("{} cancelled run #{number}", ui::ok("✔"));
2008
            }
2009
        }
2010
    }
2011
    Ok(0)
2012
}
2013
2014
fn label(c: &Client, t: &Target, cmd: LabelCmd, json: bool) -> Result<i32> {
2015
    let base = t.repo_path()?;
2016
    match cmd {
2017
        LabelCmd::List => {
2018
            let path = format!("{base}/labels");
2019
            if json {
2020
                println!("{}", c.get_text(&path)?);
2021
                return Ok(0);
2022
            }
2023
            let labels: Vec<hub_api::Label> = c.get(&path)?;
2024
            if labels.is_empty() {
2025
                println!("{}", ui::dim("No labels."));
2026
            }
2027
            for l in labels {
2028
                println!("{} {}  {}", ui::dim(&l.colour), l.name, ui::dim(&l.description));
2029
            }
2030
        }
2031
        LabelCmd::Create { name, colour, description } => {
2032
            let l: hub_api::Label = c.send("POST", &format!("{base}/labels"), &hub_api::NewLabel { name, colour, description })?;
2033
            if json {
2034
                println!("{}", serde_json::to_string(&l)?);
2035
            } else {
2036
                println!("{} label {} {}", ui::ok("✔"), l.name, ui::dim(&l.colour));
2037
            }
2038
        }
2039
        LabelCmd::Delete { name } => {
2040
            c.send_text("DELETE", &format!("{base}/labels/{}", enc(&name)), &serde_json::json!({}))?;
2041
            println!("{} deleted label {name}", ui::ok("✔"));
2042
        }
2043
    }
2044
    Ok(0)
2045
}
2046
2047
fn assistant(c: &Client, t: &Target, cmd: AssistantCmd, org: Option<String>, site: bool, json: bool) -> Result<i32> {
2048
    let base = match (&org, site) {
2049
        (Some(o), _) => format!("/orgs/{}/assistants", enc(o)),
2050
        (None, true) => "/admin/assistants".to_string(),
2051
        (None, false) => format!("{}/assistants", t.repo_path()?),
2052
    };
2053
    match cmd {
2054
        AssistantCmd::List => {
2055
            if json {
2056
                println!("{}", c.get_text(&base)?);
2057
                return Ok(0);
2058
            }
2059
            let list: Vec<hub_api::Assistant> = c.get(&base)?;
2060
            if list.is_empty() {
2061
                println!("{}", ui::dim("No assistants."));
2062
            }
2063
            for a in list {
2064
                let state = if a.enabled && !a.off_above {
2065
                    ui::ok("on")
2066
                } else if a.off_above {
2067
                    ui::dim("off above")
2068
                } else {
2069
                    ui::dim("off")
2070
                };
2071
                let from = if a.from.is_empty() { String::new() } else { ui::dim(&format!(" · from {}", a.from)) };
2072
                println!("{} {}  {} {}{}", state, a.name, ui::dim(&a.model), ui::dim(&a.endpoint), from);
2073
            }
2074
        }
2075
        AssistantCmd::Add { name, preset, endpoint, api, model, token_env, off } => {
2076
            let token = match token_env {
2077
                Some(var) => std::env::var(&var).map_err(|_| anyhow::anyhow!("${var} is not set"))?,
2078
                None => String::new(),
2079
            };
2080
            let body =
2081
                hub_api::NewAssistant { name, preset, endpoint, api, model, token, headers: String::new(), enabled: !off, budget: None };
2082
            let r: serde_json::Value = c.send("POST", &base, &body)?;
2083
            println!("{} {}", ui::ok("✔"), r["ok"].as_str().unwrap_or("saved"));
2084
        }
2085
        AssistantCmd::Remove { name } => {
2086
            c.send_text("DELETE", &format!("{base}/{}", enc(&name)), &serde_json::json!({}))?;
2087
            println!("{} removed {name}", ui::ok("✔"));
2088
        }
2089
        AssistantCmd::Prompt { set } => {
2090
            let p: hub_api::AssistantPrompt = match set {
2091
                Some(path) => {
2092
                    let text = if path.as_os_str() == "-" {
2093
                        let mut s = String::new();
2094
                        std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
2095
                        s
2096
                    } else {
2097
                        std::fs::read_to_string(&path)?
2098
                    };
2099
                    c.send("PUT", &format!("{base}/prompt"), &hub_api::AssistantPrompt { prompt: text, inherited: vec![] })?
2100
                }
2101
                None => c.get(&format!("{base}/prompt"))?,
2102
            };
2103
            if json {
2104
                println!("{}", serde_json::to_string(&p)?);
2105
                return Ok(0);
2106
            }
2107
            for (from, text) in &p.inherited {
2108
                println!("{}\n{}\n", ui::dim(&format!("── from {from}")), text);
2109
            }
2110
            if p.prompt.is_empty() {
2111
                println!("{}", ui::dim("No prompt of its own."));
2112
            } else {
2113
                println!("{}\n{}", ui::dim("── this level"), p.prompt);
2114
            }
2115
        }
2116
    }
2117
    Ok(0)
2118
}
2119
2120
fn project_line(p: &hub_api::Project) -> String {
2121
    let glyph = if p.closed { ui::dim("▢") } else { ui::ok("▣") };
2122
    let private = if p.public { "" } else { " · private" };
2123
    format!("{glyph} {} {}  {}", ui::dim(&p.number.to_string()), p.title, ui::dim(&format!("updated {}{private}", ui::ago(p.updated_ms))))
2124
}
2125
2126
fn project(c: &Client, t: &Target, cmd: ProjectCmd, owner: Option<String>, json: bool) -> Result<i32> {
2127
    let owner = match owner {
2128
        Some(o) => o,
2129
        None => t.repo()?.0.to_string(),
2130
    };
2131
    let base = format!("/projects/{}", enc(&owner));
2132
    let state = |number: i64, closed: bool, verb: &str| -> Result<()> {
2133
        let p: hub_api::Project =
2134
            c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { closed: Some(closed), ..Default::default() })?;
2135
        if json {
2136
            println!("{}", serde_json::to_string(&p)?);
2137
        } else {
2138
            println!("{} {verb} project {} {}", ui::ok("✔"), p.number, p.title);
2139
        }
2140
        Ok(())
2141
    };
2142
    match cmd {
2143
        ProjectCmd::List => {
2144
            if json {
2145
                println!("{}", c.get_text(&base)?);
2146
                return Ok(0);
2147
            }
2148
            let list: Vec<hub_api::Project> = c.get(&base)?;
2149
            if list.is_empty() {
2150
                println!("{}", ui::dim(&format!("No projects for {owner}: oh project create TITLE")));
2151
            }
2152
            for p in &list {
2153
                println!("{}", project_line(p));
2154
            }
2155
        }
2156
        ProjectCmd::View { number, archived } => {
2157
            let path = format!("{base}/{number}");
2158
            let cards = format!("{path}/cards?archived=true");
2159
            if json {
2160
                println!("{}", c.get_text(if archived { &cards } else { &path })?);
2161
                return Ok(0);
2162
            }
2163
            let mut b: hub_api::Board = c.get(&path)?;
2164
            if archived {
2165
                b.columns = c.get(&cards)?;
2166
            }
2167
            println!("{}", project_line(&b.project));
2168
            if !b.project.description.is_empty() {
2169
                println!("{}", b.project.description);
2170
            }
2171
            for col in &b.columns {
2172
                println!();
2173
                println!("{} {}", ui::strong(&col.name), ui::dim(&format!("{} · column {}", col.cards.len(), col.id)));
2174
                if col.cards.is_empty() {
2175
                    println!("  {}", ui::dim("(empty)"));
2176
                }
2177
                for card in &col.cards {
2178
                    let what = if card.reference.is_empty() { ui::dim("note") } else { card.reference.clone() };
2179
                    let st = if card.state.is_empty() { String::new() } else { format!(" {}", ui::dim(&card.state)) };
2180
                    let mut tags: Vec<String> = card.labels.iter().map(|l| format!("[{l}]")).collect();
2181
                    tags.extend(card.assignees.iter().map(|a| format!("@{a}")));
2182
                    let tags = if tags.is_empty() { String::new() } else { format!("  {}", ui::dim(&tags.join(" "))) };
2183
                    println!("  {} {what}{st}  {}{tags}", ui::dim(&format!("{:>4}", card.id)), card.title);
2184
                }
2185
            }
2186
            println!("{}", ui::dim(&format!("\n{}", b.project.url)));
2187
        }
2188
        ProjectCmd::Create { title, description, private } => {
2189
            let p: hub_api::Project = c.send("POST", &base, &hub_api::NewProject { title, description, private })?;
2190
            if json {
2191
                println!("{}", serde_json::to_string(&p)?);
2192
            } else {
2193
                println!("{} project {} {} {}", ui::ok("✔"), p.number, p.title, ui::dim(&p.url));
2194
            }
2195
        }
2196
        ProjectCmd::Close { number } => state(number, true, "closed")?,
2197
        ProjectCmd::Reopen { number } => state(number, false, "reopened")?,
2198
        ProjectCmd::Transfer { number, to } => {
2199
            let p: hub_api::Project =
2200
                c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { owner: Some(to.clone()), ..Default::default() })?;
2201
            if json {
2202
                println!("{}", serde_json::to_string(&p)?);
2203
            } else {
2204
                println!("{} transferred project {} to {to}: now {} {}", ui::ok("✔"), number, p.number, p.url);
2205
            }
2206
        }
2207
        ProjectCmd::Card { cmd: CardCmd::Add { number, reference, note, column } } => {
2208
            // The hub names a card's issue as `repo#N` among the owner's
2209
            // repositories.
2210
            let reference = match reference {
2211
                None => String::new(),
2212
                Some(r) if r.contains('#') && !r.starts_with('#') => match r.split_once('/') {
2213
                    Some((o, rest)) if o == owner => rest.to_string(),
2214
                    Some(_) => bail!("{r}: a project holds only {owner}'s issues and proposals"),
2215
                    None => r,
2216
                },
2217
                Some(r) => {
2218
                    let n = r.trim_start_matches('#');
2219
                    if n.parse::<i64>().is_err() {
2220
                        bail!("{r}: give an issue or proposal number, or NAME#N");
2221
                    }
2222
                    format!("{}#{n}", t.repo()?.1)
2223
                }
2224
            };
2225
            let note = note.unwrap_or_default();
2226
            if reference.is_empty() && note.is_empty() {
2227
                bail!("say what to add: an issue or proposal (12, #12, owner/name#12) or --note TEXT");
2228
            }
2229
            let card: hub_api::ProjectCard =
2230
                c.send("POST", &format!("{base}/{number}/cards"), &hub_api::NewCard { column, reference, note })?;
2231
            if json {
2232
                println!("{}", serde_json::to_string(&card)?);
2233
            } else {
2234
                println!("{} card {} {}", ui::ok("✔"), card.id, if card.reference.is_empty() { &card.title } else { &card.reference });
2235
            }
2236
        }
2237
        ProjectCmd::Card { cmd: CardCmd::Move { number, card, column, from, except, state, dry_run } } => match (card, from) {
2238
            (Some(card), None) => {
2239
                c.send_text("PATCH", &format!("{base}/{number}/cards/{card}"), &hub_api::CardMove { column: column.clone() })?;
2240
                println!("{} card {card} moved to {column}", ui::ok("✔"));
2241
            }
2242
            (None, Some(from)) => {
2243
                let r: hub_api::CardsMoved = c.send(
2244
                    "POST",
2245
                    &format!("{base}/{number}/cards/move"),
2246
                    &hub_api::CardsMove { from: from.clone(), column: column.clone(), except, state, dry_run },
2247
                )?;
2248
                if json {
2249
                    println!("{}", serde_json::to_string(&r)?);
2250
                    return Ok(0);
2251
                }
2252
                let name = |c: &hub_api::ProjectCard| if c.reference.is_empty() { c.title.clone() } else { c.reference.clone() };
2253
                for m in &r.moved {
2254
                    println!("  {} {}  {}", if dry_run { "would move" } else { "moved" }, name(m), ui::dim(&m.title));
2255
                }
2256
                let verb = if dry_run { "would move" } else { "moved" };
2257
                println!("{} {verb} {} card(s) from {from} to {column}; {} left in {from}", ui::ok("✔"), r.moved.len(), r.kept.len());
2258
            }
2259
            _ => bail!("name a card, or --from COLUMN to move every card of a column"),
2260
        },
2261
        ProjectCmd::Card { cmd: CardCmd::Archive { number, from, older, except, state, dry_run } } => {
2262
            let older_days = match older.as_deref().map(|o| o.trim().trim_end_matches('d')) {
2263
                None => None,
2264
                Some(d) => Some(d.parse::<i64>().map_err(|_| anyhow::anyhow!("--older takes days: 14d, or 14"))?),
2265
            };
2266
            let r: hub_api::CardsArchived = c.send(
2267
                "POST",
2268
                &format!("{base}/{number}/cards/archive"),
2269
                &hub_api::CardsArchive { from: from.clone(), older_days, except, state, dry_run },
2270
            )?;
2271
            if json {
2272
                println!("{}", serde_json::to_string(&r)?);
2273
                return Ok(0);
2274
            }
2275
            let verb = if dry_run { "would archive" } else { "archived" };
2276
            for a in &r.archived {
2277
                let name = if a.reference.is_empty() { a.title.clone() } else { a.reference.clone() };
2278
                println!("  {verb} {name}  {}", ui::dim(&a.title));
2279
            }
2280
            println!("{} {verb} {} card(s) from {from}; {} left on the board", ui::ok("✔"), r.archived.len(), r.kept.len());
2281
        }
2282
        ProjectCmd::Card { cmd: CardCmd::Restore { number, card } } => {
2283
            c.send_text("POST", &format!("{base}/{number}/cards/{card}/restore"), &serde_json::json!({}))?;
2284
            println!("{} card {card} restored", ui::ok("✔"));
2285
        }
2286
        ProjectCmd::Card { cmd: CardCmd::Remove { number, card } } => {
2287
            c.send_text("DELETE", &format!("{base}/{number}/cards/{card}"), &serde_json::json!({}))?;
2288
            println!("{} card {card} removed", ui::ok("✔"));
2289
        }
2290
    }
2291
    Ok(0)
2292
}
2293
2294
fn milestone_line(m: &hub_api::Milestone) -> String {
2295
    let glyph = if m.state == "open" { ui::ok("◆") } else { ui::dim("◇") };
2296
    let due = m.due_ms.map(|d| format!(" · due {}", ui::ago(d))).unwrap_or_default();
2297
    format!("{glyph} {}  {}{}", m.title, ui::dim(&format!("{} open, {} closed", m.open, m.closed)), ui::dim(&due))
2298
}
2299
2300
fn milestone(c: &Client, t: &Target, cmd: MilestoneCmd, json: bool) -> Result<i32> {
2301
    let base = t.repo_path()?;
2302
    let edit = |title: &str, e: hub_api::MilestoneEdit, verb: &str| -> Result<()> {
2303
        let m: hub_api::Milestone = c.send("PATCH", &format!("{base}/milestones/{}", enc(title)), &e)?;
2304
        if json {
2305
            println!("{}", serde_json::to_string(&m)?);
2306
        } else {
2307
            println!("{} {verb} milestone {}", ui::ok("✔"), m.title);
2308
        }
2309
        Ok(())
2310
    };
2311
    match cmd {
2312
        MilestoneCmd::List => {
2313
            let path = format!("{base}/milestones");
2314
            if json {
2315
                println!("{}", c.get_text(&path)?);
2316
                return Ok(0);
2317
            }
2318
            let list: Vec<hub_api::Milestone> = c.get(&path)?;
2319
            if list.is_empty() {
2320
                println!("{}", ui::dim("No milestones."));
2321
            }
2322
            for m in &list {
2323
                println!("{}", milestone_line(m));
2324
            }
2325
        }
2326
        MilestoneCmd::Create { title, description, due } => {
2327
            let m: hub_api::Milestone =
2328
                c.send("POST", &format!("{base}/milestones"), &hub_api::NewMilestone { title, description, due })?;
2329
            if json {
2330
                println!("{}", serde_json::to_string(&m)?);
2331
            } else {
2332
                println!("{} milestone {}", ui::ok("✔"), m.title);
2333
            }
2334
        }
2335
        MilestoneCmd::Edit { title, rename, description, due } => {
2336
            if rename.is_none() && description.is_none() && due.is_none() {
2337
                bail!("say what to change: --rename, --description or --due");
2338
            }
2339
            edit(&title, hub_api::MilestoneEdit { title: rename, description, due, state: None }, "edited")?;
2340
        }
2341
        MilestoneCmd::Close { title } => {
2342
            edit(&title, hub_api::MilestoneEdit { state: Some("closed".into()), ..Default::default() }, "closed")?;
2343
        }
2344
        MilestoneCmd::Reopen { title } => {
2345
            edit(&title, hub_api::MilestoneEdit { state: Some("open".into()), ..Default::default() }, "reopened")?;
2346
        }
2347
    }
2348
    Ok(0)
2349
}
2350
2351
fn tag(c: &Client, t: &Target, cmd: TagCmd, json: bool) -> Result<i32> {
2352
    let base = t.repo_path()?;
2353
    match cmd {
2354
        TagCmd::List => {
2355
            let path = format!("{base}/tags");
2356
            if json {
2357
                println!("{}", c.get_text(&path)?);
2358
                return Ok(0);
2359
            }
2360
            let tags: Vec<Tag> = c.get(&path)?;
2361
            if tags.is_empty() {
2362
                println!("{}", ui::dim("no tags"));
2363
            }
2364
            for t in tags {
2365
                let heads: Vec<&str> = t.heads.iter().map(|h| &h[..h.len().min(12)]).collect();
2366
                let signer = t.signer.map(|s| format!("signed by {s}")).unwrap_or_else(|| "unsigned".into());
2367
                println!("{}  {}  {}", t.name, ui::dim(&heads.join(" ")), ui::dim(&signer));
2368
            }
2369
        }
2370
        TagCmd::Create { name, target, message } => {
2371
            let new = hub_api::NewTag { name, target, message };
2372
            let made: Tag = c.send("POST", &format!("{base}/tags"), &new)?;
2373
            if json {
2374
                println!("{}", serde_json::to_string(&made)?);
2375
            } else {
2376
                println!("{} tagged {} {}", ui::ok("✔"), made.name, ui::dim(&format!("{} head(s)", made.heads.len())));
2377
            }
2378
        }
2379
        TagCmd::Delete { name, reason } => {
2380
            let reason = reason.unwrap_or_default();
2381
            c.send_text("DELETE", &format!("{base}/tags/{}?reason={}", enc(&name), enc(&reason)), &serde_json::json!({}))?;
2382
            if json {
2383
                println!("{}", serde_json::json!({ "withdrawn": name }));
2384
            } else {
2385
                println!("{} withdrew {} {}", ui::ok("✔"), name, ui::dim("(clones drop it on their next fetch)"));
2386
            }
2387
        }
2388
    }
2389
    Ok(0)
2390
}
2391
2392
fn release(c: &Client, t: &Target, cmd: ReleaseCmd, json: bool) -> Result<i32> {
2393
    let base = t.repo_path()?;
2394
    match cmd {
2395
        ReleaseCmd::List => {
2396
            let path = format!("{base}/releases");
2397
            if json {
2398
                println!("{}", c.get_text(&path)?);
2399
                return Ok(0);
2400
            }
2401
            let list: Vec<Release> = c.get(&path)?;
2402
            if list.is_empty() {
2403
                println!("{}", ui::dim("No releases."));
2404
            }
2405
            for r in &list {
2406
                println!(
2407
                    "{} {} {}{}",
2408
                    if r.latest { ui::ok("●") } else { ui::dim("○") },
2409
                    ui::strong(&r.tag),
2410
                    r.title,
2411
                    ui::dim(&format!(
2412
                        " · {} asset{} · {}",
2413
                        r.assets.len(),
2414
                        if r.assets.len() == 1 { "" } else { "s" },
2415
                        ui::ago(r.created_ms)
2416
                    ))
2417
                );
2418
            }
2419
        }
2420
        ReleaseCmd::Create { tag, title, notes, prerelease } => {
2421
            let new = NewRelease { title: title.unwrap_or_else(|| tag.clone()), tag, notes, prerelease };
2422
            let r: Release = c.send("POST", &format!("{base}/releases"), &new)?;
2423
            if json {
2424
                println!("{}", serde_json::to_string(&r)?);
2425
            } else {
2426
                println!("{} released {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
2427
            }
2428
        }
2429
        ReleaseCmd::Edit { tag, title, notes, prerelease } => {
2430
            let notes = match notes.as_deref() {
2431
                Some("-") => Some(body_of(None, Some("-".into()))?),
2432
                _ => notes,
2433
            };
2434
            if title.is_none() && notes.is_none() && prerelease.is_none() {
2435
                bail!("say what to change: --title, --notes or --prerelease");
2436
            }
2437
            let edit = hub_api::ReleaseEdit { title, notes, prerelease };
2438
            let r: Release = c.send("PATCH", &format!("{base}/releases/{tag}"), &edit)?;
2439
            if json {
2440
                println!("{}", serde_json::to_string(&r)?);
2441
            } else {
2442
                println!("{} edited {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
2443
            }
2444
        }
2445
        ReleaseCmd::Upload { tag, files } => {
2446
            if files.is_empty() {
2447
                bail!("name the files to attach");
2448
            }
2449
            for f in files {
2450
                let name = f.file_name().and_then(|n| n.to_str()).context("a file name")?.to_string();
2451
                let bytes = std::fs::read(&f).with_context(|| format!("read {}", f.display()))?;
2452
                c.upload(&format!("{base}/releases/{}/assets?name={}", enc(&tag), enc(&name)), &bytes)?;
2453
                println!("{} attached {name} to {tag}", ui::ok("✔"));
2454
            }
2455
        }
2456
        ReleaseCmd::Trust { tag } => {
2457
            let path = format!("{base}/releases/trust/{}", enc(&tag));
2458
            if json {
2459
                println!("{}", c.get_text(&path)?);
2460
                return Ok(0);
2461
            }
2462
            let r: serde_json::Value = c.get(&path)?;
2463
            println!("{} {}", ui::strong(&format!("Trust report for {tag}")), ui::dim(&format!("{} changes", r["changes"])));
2464
            let mut worst = 0;
2465
            for ch in r["audit"].as_array().into_iter().flatten() {
2466
                let v = ch["verdict"].as_str().unwrap_or("");
2467
                worst = worst.max(match v {
2468
                    "fail" => 2,
2469
                    "warn" => 1,
2470
                    _ => 0,
2471
                });
2472
                let g = match v {
2473
                    "pass" => ui::ok("✔"),
2474
                    "warn" => ui::warn("!"),
2475
                    _ => ui::bad("✘"),
2476
                };
2477
                println!("{g} {} {}", ch["title"].as_str().unwrap_or(""), ui::dim(ch["detail"].as_str().unwrap_or("")));
2478
            }
2479
            return Ok(if worst == 2 { 1 } else { 0 });
2480
        }
2481
    }
2482
    Ok(0)
2483
}
2484
2485
#[cfg(test)]
2486
mod tests {
2487
2488
    #[test]
2489
    fn job_timings_and_report_commands_read_plainly() {
2490
        use clap::Parser;
2491
        let job = hub_api::FlowJob {
2492
            name: "perf".into(),
2493
            status: "passed".into(),
2494
            depends_on: vec![],
2495
            runner: "earth-1".into(),
2496
            exit_code: Some(0),
2497
            error: String::new(),
2498
            started_ms: Some(13_000),
2499
            finished_ms: Some(200_000),
2500
            log_lines: 10,
2501
            waiting: String::new(),
2502
            placed: String::new(),
2503
            approval: String::new(),
2504
            queued_ms: Some(1_000),
2505
            ready_ms: Some(12_500),
2506
            phases: vec![hub_api::FlowPhase { name: "image".into(), ms: 850 }, hub_api::FlowPhase { name: "run".into(), ms: 125_400 }],
2507
            peak_disk_mib: Some(2150),
2508
            peak_memory_mib: Some(900),
2509
        };
2510
        assert_eq!(super::timing_line(&job), "waited 12.0 s · image 850 ms · run 2 min 5 s · peak disk 2.1 GiB, memory 900 MiB");
2511
        let bare = hub_api::FlowJob { queued_ms: None, phases: vec![], peak_disk_mib: None, peak_memory_mib: None, ..job };
2512
        assert_eq!(super::timing_line(&bare), "");
2513
        assert_eq!(super::enc_path("data/frame times.csv"), "data/frame%20times.csv");
2514
2515
        let cli =
2516
            super::Cli::try_parse_from(["oh", "run", "report", "26", "performance", "--file", "data/frames.csv", "-o", "f.csv"]).unwrap();
2517
        let super::Cmd::Run { cmd: super::RunCmd::Report { number, job, pick } } = cli.cmd else { panic!("run report") };
2518
        assert_eq!((number, job.as_str(), pick.file.as_deref(), pick.list), (26, "performance", Some("data/frames.csv"), false));
2519
        assert!(super::Cli::try_parse_from(["oh", "run", "report", "26", "perf", "--list", "--file", "x"]).is_err(), "one or the other");
2520
        assert!(super::Cli::try_parse_from(["oh", "run", "report", "26", "perf", "-o", "x"]).is_err(), "-o is for --file");
2521
        let cli = super::Cli::try_parse_from(["oh", "report", "show", "performance", "--bookmark", "main", "--list"]).unwrap();
2522
        assert!(matches!(cli.cmd, super::Cmd::Report { cmd: super::ReportCmd::Show { list: true, .. } }));
2523
        assert!(super::Cli::try_parse_from(["oh", "run", "view", "3", "--timings"]).is_ok());
2524
    }
2525
2526
    #[test]
2527
    fn runner_update_scopes_resolve_by_name_or_id() {
2528
        let all = hub_api::RunnerUpdates {
2529
            repo: String::new(),
2530
            settings: vec![],
2531
            groups: vec![hub_api::RunnerGroup {
2532
                id: 4,
2533
                owner: "acme".into(),
2534
                name: "canary".into(),
2535
                percent: None,
2536
                members: vec![],
2537
                wave: None,
2538
            }],
2539
            runners: vec![],
2540
            holds: vec![],
2541
        };
2542
        assert_eq!(update_scope("site", &all).unwrap(), ("site".to_string(), String::new()));
2543
        assert_eq!(update_scope("owner:acme", &all).unwrap(), ("owner".to_string(), "acme".to_string()));
2544
        for g in ["group:canary", "group:acme/canary", "group:4"] {
2545
            assert_eq!(update_scope(g, &all).unwrap(), ("group".to_string(), "4".to_string()), "{g}");
2546
        }
2547
        assert!(update_scope("runner:plex", &all).unwrap_err().to_string().contains("no runner"));
2548
        assert!(update_scope("everyone", &all).is_err());
2549
        assert_eq!(switch(Some("inherit")).unwrap(), Some(None));
2550
        assert!(switch(Some("yes")).is_err());
2551
    }
2552
    use super::*;
2553
2554
    /// `oh drop` (oxygenhub#279): its commands and flags parse as the
2555
    /// help says, and a drop is named by its id or its address.
2556
    #[test]
2557
    fn drop_commands_parse() {
2558
        let cli = Cli::try_parse_from(["oh", "drop", "create", "a.txt", "b.md", "--secret", "-d", "Two files", "-t", "Notes"]).unwrap();
2559
        match cli.cmd {
2560
            Cmd::Drop { cmd: DropCmd::Create { files, secret, description, title } } => {
2561
                assert_eq!(files, vec![std::path::PathBuf::from("a.txt"), std::path::PathBuf::from("b.md")]);
2562
                assert!(secret);
2563
                assert_eq!((description.as_deref(), title.as_deref()), (Some("Two files"), Some("Notes")));
2564
            }
2565
            _ => panic!("not drop create"),
2566
        }
2567
        assert!(Cli::try_parse_from(["oh", "drop", "create"]).is_err(), "a drop needs a file");
2568
        match Cli::try_parse_from(["oh", "runner-updates", "set", "group:canary", "--updates", "on", "--window", "02-05"]).unwrap() {
2569
            Cli { cmd: Cmd::RunnerUpdates { cmd: Some(RunnerUpdatesCmd::Set { scope, updates, window, channel, dry_run }) }, .. } => {
2570
                assert_eq!((scope.as_str(), updates.as_deref(), window.as_deref()), ("group:canary", Some("on"), Some("02-05")));
2571
                assert!(channel.is_none() && dry_run.is_none());
2572
            }
2573
            _ => panic!("not runner-updates set"),
2574
        }
2575
        assert!(matches!(Cli::try_parse_from(["oh", "runner-updates"]).unwrap().cmd, Cmd::RunnerUpdates { cmd: None }));
2576
        match Cli::try_parse_from(["oh", "drop", "list", "--user", "bob", "--json"]).unwrap() {
2577
            Cli { cmd: Cmd::Drop { cmd: DropCmd::List { user } }, json, .. } => assert_eq!((user.as_deref(), json), (Some("bob"), true)),
2578
            _ => panic!("not drop list"),
2579
        }
2580
        match Cli::try_parse_from(["oh", "drop", "view", "0123456789abcdef01234567", "-f", "a.txt"]).unwrap().cmd {
2581
            Cmd::Drop { cmd: DropCmd::View { id, file } } => {
2582
                assert_eq!((id.as_str(), file.as_deref()), ("0123456789abcdef01234567", Some("a.txt")))
2583
            }
2584
            _ => panic!("not drop view"),
2585
        }
2586
        assert!(matches!(Cli::try_parse_from(["oh", "drop", "delete", "x"]).unwrap().cmd, Cmd::Drop { cmd: DropCmd::Delete { .. } }));
2587
        assert_eq!(drop_id("0123456789ABCDEF01234567").unwrap(), "0123456789abcdef01234567");
2588
        assert_eq!(drop_id("https://hub.example/andy/drops/0123456789abcdef01234567/").unwrap(), "0123456789abcdef01234567");
2589
        assert!(drop_id("andy/notes").is_err());
2590
    }
2591
}