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