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