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