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