OXYGENHUB
◆ v0.9.19 oxygenhub / crates / oh / src / main.rs
109.7 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
5c6e92fd Andy McCall ↶ 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;
b7e1be26 Andy McCall ↶ 6
mod mcp;
5c6e92fd Andy McCall ↶ 7
mod target;
8
mod ui;
9
10
use anyhow::{bail, Context, Result};
11
use clap::{Parser, Subcommand};
12
use client::Client;
fac6853c Andy McCall ↶ 13
use hub_api::{
14
    FlowJob, FlowLogLine, FlowRun, Issue, IssueStateChange, NewComment, NewIssue, NewProposal, NewRelease, Proposal, Release, Report, Tag,
15
};
5c6e92fd Andy McCall ↶ 16
use std::time::Duration;
2bbe88a8 Andy McCall ↶ 17
use target::{Choice, Config, Target};
5c6e92fd Andy McCall ↶ 18
19
#[derive(Parser)]
166f6e9b Andy McCall 20
#[command(name = "oh", version = env!("OXY_VERSION_LONG"), about = "OxygenHub from the command line: issues, proposals, Flow runs, releases and drops")]
5c6e92fd Andy McCall ↶ 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
    },
40dd3f86 Andy McCall ↶ 63
    /// Coverage: upload a report measured off the hub (oxygenhub#136)
64
    Coverage {
65
        #[command(subcommand)]
66
        cmd: CoverageCmd,
67
    },
5c6e92fd Andy McCall ↶ 68
    /// OxygenFlow runs
69
    Run {
70
        #[command(subcommand)]
71
        cmd: RunCmd,
72
    },
fac6853c Andy McCall ↶ 73
    /// Reports Flow jobs publish: the newest of each, one by name (oxygenhub#348)
74
    Report {
75
        #[command(subcommand)]
76
        cmd: ReportCmd,
77
    },
5c6e92fd Andy McCall ↶ 78
    /// Releases
79
    Release {
80
        #[command(subcommand)]
81
        cmd: ReleaseCmd,
82
    },
ba0a55bb Andy McCall ↶ 83
    /// Tags: list, create, withdraw
84
    Tag {
85
        #[command(subcommand)]
86
        cmd: TagCmd,
87
    },
2291f8cc Andy McCall ↶ 88
    /// The repository's labels
89
    Label {
90
        #[command(subcommand)]
91
        cmd: LabelCmd,
92
    },
5ea4872f Andy McCall ↶ 93
    /// Milestones: list, create, edit, close
94
    Milestone {
95
        #[command(subcommand)]
96
        cmd: MilestoneCmd,
97
    },
17a3a84b Andy McCall ↶ 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
    },
62ceb2ee Andy McCall ↶ 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
    },
8aa5ef38 Andy McCall ↶ 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
    },
166f6e9b Andy McCall 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
    },
9bbca80f Andy McCall ↶ 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
    },
b7e1be26 Andy McCall ↶ 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
    },
5c6e92fd Andy McCall ↶ 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)]
8aa5ef38 Andy McCall ↶ 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)]
166f6e9b Andy McCall 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,
9bbca80f Andy McCall ↶ 214
    },
04f9c984 Andy McCall ↶ 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
    },
9bbca80f Andy McCall ↶ 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>,
166f6e9b Andy McCall 265
    },
9bbca80f Andy McCall ↶ 266
    /// Offer a held build again (it rolled back on a runner)
267
    Lift { version: String },
166f6e9b Andy McCall 268
}
269
270
#[derive(Subcommand)]
5c6e92fd Andy McCall ↶ 271
enum AuthCmd {
df71c789 Andy McCall ↶ 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
5c6e92fd Andy McCall ↶ 274
    Login {
df71c789 Andy McCall ↶ 275
        /// The hub, e.g. https://oxygenhub.io
5c6e92fd Andy McCall ↶ 276
        #[arg(long = "with-hub", value_name = "URL")]
277
        url: String,
df71c789 Andy McCall ↶ 278
        /// An API token from the hub's Settings → Tokens, instead of
279
        /// approving a code ("-" reads it from stdin)
5c6e92fd Andy McCall ↶ 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 {
2291f8cc Andy McCall ↶ 298
    /// Put labels on an issue or take them off (triage)
299
    Label(LabelChange),
5c6e92fd Andy McCall ↶ 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>,
17a3a84b Andy McCall ↶ 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>,
1c52d940 Andy McCall ↶ 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>,
5c6e92fd Andy McCall ↶ 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 },
b5229b56 Andy McCall ↶ 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
    },
5c6e92fd Andy McCall ↶ 365
    /// Comment on an issue
366
    Comment {
367
        number: i64,
368
        #[arg(long, short)]
bd91edeb Andy McCall ↶ 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>,
1c52d940 Andy McCall ↶ 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>,
5c6e92fd Andy McCall ↶ 377
    },
378
}
379
380
#[derive(Subcommand)]
381
enum ProposalCmd {
d7e2c275 Andy McCall ↶ 382
    /// Open proposals (or --state draft|landed|closed|all), newest first
0b20f1ec Andy McCall ↶ 383
    List {
384
        #[arg(long, default_value = "open")]
385
        state: String,
d7e2c275 Andy McCall ↶ 386
        /// At most this many
387
        #[arg(long, default_value_t = 30)]
388
        limit: usize,
0b20f1ec Andy McCall ↶ 389
    },
5c6e92fd Andy McCall ↶ 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>,
739a763a Andy McCall ↶ 398
        /// Read the body from a file ("-" for stdin)
399
        #[arg(long, short = 'F', conflicts_with = "body")]
400
        body_file: Option<String>,
5c6e92fd Andy McCall ↶ 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,
739a763a Andy McCall ↶ 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>,
5c6e92fd Andy McCall ↶ 420
    },
2291f8cc Andy McCall ↶ 421
    /// Put labels on a proposal or take them off (triage)
422
    Label(LabelChange),
739a763a Andy McCall ↶ 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
    },
5c6e92fd Andy McCall ↶ 432
    /// The checks on a proposal's projected state
433
    Checks { number: i64 },
1f1eb06a Andy McCall ↶ 434
    /// Land a proposal on its target, as the page's Land button does
2a8b6216 Andy McCall ↶ 435
    Land {
436
        number: i64,
437
        /// Land before its required checks pass, saying why (maintainers;
438
        /// recorded and audited, #261)
86a69b53 Andy McCall ↶ 439
        #[arg(long, value_name = "REASON", conflicts_with = "when_ready")]
2a8b6216 Andy McCall ↶ 440
        over_checks: Option<String>,
86a69b53 Andy McCall ↶ 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,
2a8b6216 Andy McCall ↶ 447
    },
71e65fcf Andy McCall ↶ 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 },
09ffa7b6 Andy McCall ↶ 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
    },
62ceb2ee Andy McCall ↶ 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
    },
2291f8cc Andy McCall ↶ 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 },
17a3a84b Andy McCall ↶ 519
}
520
521
#[derive(Subcommand)]
522
enum ProjectCmd {
523
    /// The owner's boards
524
    List,
525
    /// One board: its columns and cards
439ecd87 Andy McCall ↶ 526
    View {
527
        number: i64,
528
        /// Its archived cards instead (#293)
529
        #[arg(long)]
530
        archived: bool,
531
    },
17a3a84b Andy McCall ↶ 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 },
b1e92a62 Andy McCall ↶ 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
    },
439ecd87 Andy McCall ↶ 553
    /// Cards on a board: add, move, archive, restore, remove
17a3a84b Andy McCall ↶ 554
    Card {
555
        #[command(subcommand)]
556
        cmd: CardCmd,
557
    },
2291f8cc Andy McCall ↶ 558
}
559
5ea4872f Andy McCall ↶ 560
#[derive(Subcommand)]
17a3a84b Andy McCall ↶ 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
    },
456f4197 Andy McCall ↶ 576
    /// Move a card to another column (by name or id), or with --from every
577
    /// card of a column at once
17a3a84b Andy McCall ↶ 578
    Move {
579
        number: i64,
456f4197 Andy McCall ↶ 580
        /// The card (its id); leave it out with --from
581
        card: Option<i64>,
17a3a84b Andy McCall ↶ 582
        #[arg(long, short)]
583
        column: String,
456f4197 Andy McCall ↶ 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")]
439ecd87 Andy McCall ↶ 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)]
456f4197 Andy McCall ↶ 614
        dry_run: bool,
17a3a84b Andy McCall ↶ 615
    },
439ecd87 Andy McCall ↶ 616
    /// Put an archived card back at the end of its column
617
    Restore { number: i64, card: i64 },
17a3a84b Andy McCall ↶ 618
    /// Take a card off a board
619
    Remove { number: i64, card: i64 },
620
}
621
622
#[derive(Subcommand)]
5ea4872f Andy McCall ↶ 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
2291f8cc Andy McCall ↶ 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
    }
40dd3f86 Andy McCall ↶ 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
    },
5c6e92fd Andy McCall ↶ 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
fac6853c Andy McCall ↶ 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
    },
5c6e92fd Andy McCall ↶ 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>,
0650d94e Andy McCall ↶ 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>,
5c6e92fd Andy McCall ↶ 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 },
fac6853c Andy McCall ↶ 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
    },
e8fa5369 Andy McCall ↶ 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
    },
745d225d Andy McCall ↶ 750
    /// Cancel a run still queued or running; its running jobs are stopped
751
    Cancel { number: i64 },
dc59d1b5 Andy McCall ↶ 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
    },
fac6853c Andy McCall ↶ 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>,
5c6e92fd Andy McCall ↶ 781
}
782
783
#[derive(Subcommand)]
fac6853c Andy McCall ↶ 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)]
ba0a55bb Andy McCall ↶ 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)]
5c6e92fd Andy McCall ↶ 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
    },
ced6d3af Andy McCall ↶ 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
    },
5c6e92fd Andy McCall ↶ 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() {
b5229b56 Andy McCall ↶ 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
    }
5c6e92fd Andy McCall ↶ 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!(),
b7e1be26 Andy McCall ↶ 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
        }
5c6e92fd Andy McCall ↶ 923
        Cmd::Api { path, method, data } => {
924
            let path = if path.starts_with('/') { path } else { format!("/{path}") };
1b770a1f Andy McCall ↶ 925
            // The method applies with or without a body (#75): without one, a
926
            // GET reads, anything else sends an empty object.
5c6e92fd Andy McCall ↶ 927
            let text = match data {
928
                Some(d) => c.send_text(
929
                    &method.to_uppercase(),
930
                    &path,
931
                    &serde_json::from_str::<serde_json::Value>(&d).context("--data is not JSON")?,
932
                )?,
1b770a1f Andy McCall ↶ 933
                None if method.eq_ignore_ascii_case("GET") => c.get_text(&path)?,
934
                None => c.send_text(&method.to_uppercase(), &path, &serde_json::json!({}))?,
5c6e92fd Andy McCall ↶ 935
            };
936
            println!("{text}");
937
            Ok(0)
938
        }
939
        Cmd::Repo { cmd: RepoCmd::View } => {
940
            let path = t.repo_path()?;
941
            if json {
942
                println!("{}", c.get_text(&path)?);
943
                return Ok(0);
944
            }
945
            let r: serde_json::Value = c.get(&path)?;
946
            println!("{} {}", ui::strong(&format!("{}/{}", t.owner, t.name)), ui::dim(r["visibility"].as_str().unwrap_or("")));
947
            if let Some(d) = r["description"].as_str().filter(|d| !d.is_empty()) {
948
                println!("{d}");
949
            }
950
            println!("{}", ui::kv("default bookmark", r["default_bookmark"].as_str().unwrap_or("")));
951
            println!("{}", ui::kv("clone", &format!("oxy clone {}/{}/{}", t.hub, t.owner, t.name)));
952
            Ok(0)
953
        }
954
        Cmd::Issue { cmd } => issue(&c, &t, cmd, json),
955
        Cmd::Proposal { cmd } => proposal(&c, &t, cmd, json),
956
        Cmd::Run { cmd } => flow(&c, &t, cmd, json),
fac6853c Andy McCall ↶ 957
        Cmd::Report { cmd } => report(&c, &t, cmd, json),
40dd3f86 Andy McCall ↶ 958
        Cmd::Coverage { cmd: CoverageCmd::Upload { file, bookmark, change } } => {
959
            let content = std::fs::read_to_string(&file).with_context(|| format!("read {}", file.display()))?;
960
            let mut body = serde_json::json!({ "content": content });
961
            if let Some(b) = bookmark {
962
                body["bookmark"] = b.into();
963
            }
964
            if let Some(ch) = change {
965
                body["change"] = ch.into();
966
            }
967
            let base = t.repo_path()?;
968
            let r: hub_api::CoverageReport = c.send("POST", &format!("{base}/coverage"), &body)?;
969
            if json {
970
                println!("{}", serde_json::to_string(&r)?);
971
            } else {
972
                let pct = r.percent.map(|p| format!("{p:.1}%")).unwrap_or_else(|| "no lines".into());
973
                let on = if r.bookmark.is_empty() { format!("state {}", &r.state[..12.min(r.state.len())]) } else { r.bookmark.clone() };
974
                println!(
975
                    "{} uploaded coverage {pct} ({} of {} lines, {} files) for {on} {}",
976
                    ui::ok("✔"),
977
                    r.lines_hit,
978
                    r.lines_found,
979
                    r.files,
980
                    ui::dim(&r.url)
981
                );
982
                if r.dropped > 0 {
983
                    println!("  {}", ui::dim(&format!("{} files it named are not in that state and were left out", r.dropped)));
984
                }
985
            }
986
            Ok(0)
987
        }
5c6e92fd Andy McCall ↶ 988
        Cmd::Release { cmd } => release(&c, &t, cmd, json),
ba0a55bb Andy McCall ↶ 989
        Cmd::Tag { cmd } => tag(&c, &t, cmd, json),
2291f8cc Andy McCall ↶ 990
        Cmd::Label { cmd } => label(&c, &t, cmd, json),
5ea4872f Andy McCall ↶ 991
        Cmd::Milestone { cmd } => milestone(&c, &t, cmd, json),
17a3a84b Andy McCall ↶ 992
        Cmd::Project { cmd, owner } => project(&c, &t, cmd, owner, json),
62ceb2ee Andy McCall ↶ 993
        Cmd::Assistant { cmd, org, site } => assistant(&c, &t, cmd, org, site, json),
8aa5ef38 Andy McCall ↶ 994
        Cmd::Agent { cmd } => agent(&c, cmd, json),
9bbca80f Andy McCall ↶ 995
        Cmd::RunnerUpdates { cmd } => runner_updates(&c, cmd.unwrap_or(RunnerUpdatesCmd::Show), json),
166f6e9b Andy McCall 996
        Cmd::Drop { cmd } => drop_cmd(&c, cmd, json),
9bbca80f Andy McCall ↶ 997
    }
998
}
999
1000
/// `on`/`off`/`inherit` as a setting: `Some(Some(b))` to set, `Some(None)` to inherit.
1001
fn switch(v: Option<&str>) -> Result<Option<Option<bool>>> {
1002
    Ok(match v {
1003
        None => None,
1004
        Some("on") => Some(Some(true)),
1005
        Some("off") => Some(Some(false)),
1006
        Some("inherit") => Some(None),
1007
        Some(other) => bail!("{other:?}: say on, off or inherit"),
1008
    })
1009
}
1010
1011
/// A scope as `oh runner-updates set` takes it, resolved to (scope, key).
1012
fn update_scope(scope: &str, all: &hub_api::RunnerUpdates) -> Result<(String, String)> {
1013
    let (kind, name) = scope.split_once(':').unwrap_or((scope, ""));
1014
    Ok(match kind {
1015
        "site" if name.is_empty() => ("site".into(), String::new()),
1016
        "owner" if !name.is_empty() => ("owner".into(), name.into()),
1017
        "group" => {
1018
            let g = all
1019
                .groups
1020
                .iter()
1021
                .find(|g| g.id.to_string() == name || g.name == name || format!("{}/{}", g.owner, g.name) == name)
1022
                .with_context(|| format!("no test group {name:?} (see `oh runner-updates`)"))?;
1023
            ("group".into(), g.id.to_string())
1024
        }
1025
        "runner" => {
1026
            let r = all
1027
                .runners
1028
                .iter()
1029
                .find(|r| r.id.to_string() == name || r.name == name)
1030
                .with_context(|| format!("no runner {name:?} (see `oh runner-updates`)"))?;
1031
            ("runner".into(), r.id.to_string())
1032
        }
1033
        _ => bail!("{scope:?}: say site, owner:NAME, group:NAME or runner:NAME"),
1034
    })
1035
}
1036
1037
fn runner_updates(c: &Client, cmd: RunnerUpdatesCmd, json: bool) -> Result<i32> {
1038
    let all: hub_api::RunnerUpdates = c.get("/admin/runner-updates")?;
1039
    match cmd {
1040
        RunnerUpdatesCmd::Show if json => println!("{}", serde_json::to_string_pretty(&all)?),
1041
        RunnerUpdatesCmd::Show => {
1042
            println!(
1043
                "{} {}",
1044
                ui::strong("Builds from"),
1045
                if all.repo.is_empty() { ui::dim("no repository: no runner is offered a build") } else { all.repo.clone() }
1046
            );
1047
            for h in &all.holds {
1048
                println!("{} flow {} held: rolled back on {} ({})", ui::warn("!"), h.version, h.runner, h.why);
1049
            }
1050
            for s in &all.settings {
1051
                let mut said = vec![];
1052
                if let Some(u) = s.updates {
1053
                    said.push(format!("updates {}", if u { "on" } else { "off" }));
1054
                }
1055
                if let Some(ch) = &s.channel {
1056
                    said.push(format!("channel {ch}"));
1057
                }
1058
                if let Some(w) = &s.window {
1059
                    said.push(format!("window {w} UTC"));
1060
                }
1061
                if let Some(d) = s.dry_run {
1062
                    said.push(format!("dry run {}", if d { "on" } else { "off" }));
1063
                }
1064
                let level = if s.scope == "site" { "site".to_string() } else { format!("{}:{}", s.scope, s.key) };
1065
                println!("  {:<18} {}", level, if said.is_empty() { ui::dim("off unless chosen") } else { said.join(", ") });
1066
            }
1067
            for g in &all.groups {
1068
                let of = if g.owner.is_empty() { "the site's runners".to_string() } else { format!("{}'s runners", g.owner) };
1ec29691 Andy McCall ↶ 1069
                let mut what = g.percent.map(|p| format!("{p}% of {of}")).unwrap_or_else(|| format!("chosen, of {of}"));
1070
                if let Some(w) = g.wave {
1071
                    what.push_str(&format!(", wave {w}"));
1072
                }
9bbca80f Andy McCall ↶ 1073
                println!(
1074
                    "  group {} ({what}): {}",
1075
                    ui::strong(&g.name),
1076
                    if g.members.is_empty() { "none".into() } else { g.members.join(", ") }
1077
                );
1078
            }
1079
            for r in &all.runners {
1080
                let on = if r.updates { ui::ok(&format!("on, {}", r.channel)) } else { ui::dim("off") };
1081
                println!("  {:<16} flow {:<22} {} ({})  {}", r.name, r.version, on, r.from[0], ui::dim(&r.now));
1082
            }
1083
        }
1084
        RunnerUpdatesCmd::Set { scope, updates, channel, window, dry_run } => {
1085
            let (scope, key) = update_scope(&scope, &all)?;
1086
            let mut s = all.settings.iter().find(|x| x.scope == scope && x.key == key).cloned().unwrap_or(hub_api::UpdateSetting {
1087
                scope: scope.clone(),
1088
                key: key.clone(),
1089
                ..Default::default()
1090
            });
1091
            if let Some(u) = switch(updates.as_deref())? {
1092
                s.updates = u;
1093
            }
1094
            if let Some(d) = switch(dry_run.as_deref())? {
1095
                s.dry_run = d;
1096
            }
1097
            if let Some(ch) = channel {
1098
                s.channel = Some(ch).filter(|c| c != "inherit");
1099
            }
1100
            if let Some(w) = window {
1101
                s.window = Some(w).filter(|w| w != "inherit");
1102
            }
1103
            let out: serde_json::Value = serde_json::from_str(&c.send_text("PUT", "/admin/runner-updates/settings", &s)?)?;
1104
            println!("{} {}", ui::ok("✔"), out["notice"].as_str().unwrap_or("saved"));
1105
        }
1106
        RunnerUpdatesCmd::Lift { version } => {
1107
            c.send_text("POST", &format!("/admin/runner-updates/holds/{version}/lift"), &serde_json::json!({}))?;
1108
            println!("{} flow {version} is offered again where the settings say so", ui::ok("✔"));
1109
        }
166f6e9b Andy McCall 1110
    }
9bbca80f Andy McCall ↶ 1111
    Ok(0)
166f6e9b Andy McCall 1112
}
1113
1114
/// A drop's id from an id or its address (`https://hub/owner/drops/ID`).
1115
fn drop_id(s: &str) -> Result<String> {
1116
    let id = s.trim().trim_end_matches('/').rsplit('/').next().unwrap_or("").to_string();
1117
    if id.len() < 16 || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
1118
        bail!("{s:?} is not a drop's id or address");
1119
    }
1120
    Ok(id.to_ascii_lowercase())
1121
}
1122
1123
fn drop_line(d: &hub_api::Drop) -> String {
1124
    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() };
1125
    let files: Vec<&str> = d.files.iter().map(|f| f.name.as_str()).collect();
1126
    format!(
1127
        "{} {} {}{}",
1128
        ui::dim(&d.id),
1129
        ui::strong(&title),
1130
        if d.visibility == "secret" { ui::warn("secret ") } else { String::new() },
1131
        ui::dim(&format!("{} · {}", files.join(", "), ui::ago(d.updated_ms)))
1132
    )
04f9c984 Andy McCall ↶ 1133
}
1134
1135
/// `oh drop star|unstar` (oxygenhub#349).
1136
fn drop_star(c: &Client, id: &str, method: &str, json: bool) -> Result<()> {
1137
    let s: hub_api::DropStars = c.send(method, &format!("/drops/{}/star", drop_id(id)?), &serde_json::json!({}))?;
1138
    if json {
1139
        println!("{}", serde_json::to_string(&s)?);
1140
    } else {
1141
        println!("{} {} · {} stars", ui::ok("✔"), if s.starred { "starred" } else { "unstarred" }, s.stars);
1142
    }
1143
    Ok(())
166f6e9b Andy McCall 1144
}
1145
1146
fn drop_cmd(c: &Client, cmd: DropCmd, json: bool) -> Result<i32> {
1147
    match cmd {
1148
        DropCmd::Create { files, secret, description, title } => {
1149
            let mut out = Vec::with_capacity(files.len());
1150
            for f in &files {
1151
                let name = f.file_name().and_then(|n| n.to_str()).with_context(|| format!("{} has no file name", f.display()))?;
1152
                let content =
1153
                    std::fs::read_to_string(f).with_context(|| format!("read {} (a drop made here holds text files)", f.display()))?;
1154
                out.push(hub_api::NewDropFile { name: name.to_string(), content });
1155
            }
1156
            let new =
1157
                hub_api::NewDrop { title: title.unwrap_or_default(), description: description.unwrap_or_default(), secret, files: out };
1158
            let d: hub_api::Drop = c.send("POST", "/drops", &new)?;
1159
            if json {
1160
                println!("{}", serde_json::to_string(&d)?);
1161
            } else {
1162
                println!("{} made {}drop {} {}", ui::ok("✔"), if secret { "secret " } else { "" }, ui::strong(&d.id), ui::dim(&d.url));
1163
                println!("  {}", ui::dim(&format!("oxy clone {}", d.clone_url)));
1164
            }
1165
        }
1166
        DropCmd::List { user } => {
1167
            let path = match &user {
1168
                Some(u) => format!("/users/{}/drops", enc(u)),
1169
                None => "/drops".to_string(),
1170
            };
1171
            if json {
1172
                println!("{}", c.get_text(&path)?);
1173
                return Ok(0);
1174
            }
1175
            let list: Vec<hub_api::Drop> = c.get(&path)?;
1176
            if list.is_empty() {
1177
                println!("{}", ui::dim("No drops."));
1178
            }
1179
            for d in &list {
1180
                println!("{}", drop_line(d));
1181
            }
1182
        }
1183
        DropCmd::View { id, file } => {
1184
            let path = format!("/drops/{}", drop_id(&id)?);
1185
            if json && file.is_none() {
1186
                println!("{}", c.get_text(&path)?);
1187
                return Ok(0);
1188
            }
1189
            let d: hub_api::Drop = c.get(&path)?;
1190
            if let Some(name) = file {
1191
                let f = d.files.iter().find(|f| f.name == name).with_context(|| format!("the drop has no file {name}"))?;
1192
                let content = f.content.as_deref().with_context(|| format!("{name} is not shown as text: download {}", f.raw_url))?;
1193
                print!("{content}");
1194
                return Ok(0);
1195
            }
1196
            println!("{}", drop_line(&d));
1197
            if !d.description.is_empty() {
1198
                println!("{}", d.description);
1199
            }
1200
            println!("{}", ui::kv("url", &d.url));
1201
            println!("{}", ui::kv("clone", &format!("oxy clone {}", d.clone_url)));
1202
            for f in &d.files {
1203
                println!("\n{} {}", ui::strong(&format!("── {}", f.name)), ui::dim(&format!("({} bytes)", f.size)));
1204
                match &f.content {
1205
                    Some(text) => {
1206
                        print!("{text}");
1207
                        if !text.ends_with('\n') && !text.is_empty() {
1208
                            println!();
1209
                        }
1210
                    }
1211
                    None => println!("{}", ui::dim(&format!("not text, or too large: {}", f.raw_url))),
1212
                }
1213
            }
1214
        }
1215
        DropCmd::Delete { id } => {
1216
            let id = drop_id(&id)?;
1217
            c.send_text("DELETE", &format!("/drops/{id}"), &serde_json::json!({}))?;
1218
            println!("{} drop {id}", ui::ok("✔ deleted"));
04f9c984 Andy McCall ↶ 1219
        }
1220
        DropCmd::Fork { id } => {
1221
            let d: hub_api::Drop = c.send("POST", &format!("/drops/{}/fork", drop_id(&id)?), &serde_json::json!({}))?;
1222
            if json {
1223
                println!("{}", serde_json::to_string(&d)?);
1224
            } else {
1225
                println!("{} forked as {} {}", ui::ok("✔"), ui::strong(&d.id), ui::dim(&d.url));
1226
            }
1227
        }
1228
        DropCmd::Star { id } => drop_star(c, &id, "PUT", json)?,
1229
        DropCmd::Unstar { id } => drop_star(c, &id, "DELETE", json)?,
1230
        DropCmd::Comments { id } => {
1231
            let path = format!("/drops/{}/comments", drop_id(&id)?);
1232
            if json {
1233
                println!("{}", c.get_text(&path)?);
1234
                return Ok(0);
1235
            }
1236
            let list: Vec<hub_api::DropComment> = c.get(&path)?;
1237
            if list.is_empty() {
1238
                println!("{}", ui::dim("No comments."));
1239
            }
1240
            for m in &list {
1241
                println!("{} {}", ui::strong(&m.author), ui::dim(&format!("#{} · {}", m.id, ui::ago(m.created_ms))));
1242
                println!("{}\n", m.body);
1243
            }
166f6e9b Andy McCall 1244
        }
04f9c984 Andy McCall ↶ 1245
        DropCmd::Comment { id, message } => {
1246
            let m: hub_api::DropComment =
1247
                c.send("POST", &format!("/drops/{}/comments", drop_id(&id)?), &hub_api::NewDropComment { body: message })?;
1248
            if json {
1249
                println!("{}", serde_json::to_string(&m)?);
1250
            } else {
1251
                println!("{} commented (#{})", ui::ok("✔"), m.id);
1252
            }
1253
        }
8aa5ef38 Andy McCall ↶ 1254
    }
166f6e9b Andy McCall 1255
    Ok(0)
8aa5ef38 Andy McCall ↶ 1256
}
1257
1258
/// `30d`, `12h`, `90m` in milliseconds.
1259
fn duration_ms(s: &str) -> Result<i64> {
1260
    let s = s.trim();
1261
    let (n, unit) = s.split_at(s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len()));
1262
    let n: i64 = n.parse().with_context(|| format!("{s:?} is not a duration such as 30d, 12h or 90m"))?;
1263
    let per = match unit {
1264
        "d" => 86_400_000,
1265
        "h" => 3_600_000,
1266
        "m" => 60_000,
1267
        _ => bail!("{s:?} is not a duration such as 30d, 12h or 90m"),
1268
    };
1269
    if n <= 0 {
1270
        bail!("a grant must last some time");
1271
    }
1272
    Ok(n * per)
1273
}
1274
1275
fn agent(c: &Client, cmd: AgentCmd, json: bool) -> Result<i32> {
1276
    use oxy_core::cert::{Grant, SignedGrant};
1277
    use oxy_core::identity::{Identity, Scope};
1278
    match cmd {
1279
        AgentCmd::Grant { name, scope, lasts } => {
1280
            let home = oxy_core::repo::default_home();
1281
            let (me_id, sk) = oxy_core::repo::home_key(&home).map_err(|e| anyhow::anyhow!("{e}"))?.with_context(|| {
1282
                format!(
1283
                    "{} names no key of yours (author.key) with its secret: the grant is signed with your own key, in your own shell",
1284
                    home.display()
1285
                )
1286
            })?;
1287
            let me: serde_json::Value = c.get("/user")?;
1288
            let username = me["username"].as_str().context("the hub did not say who you are")?;
1289
            let hub = Identity::decode(&c.get_root_bytes("/.well-known/oxyhub-key")?).map_err(|e| anyhow::anyhow!("the hub's key: {e}"))?;
1290
            let scope = Scope::parse(&scope).map_err(|e| anyhow::anyhow!("{e}"))?;
1291
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
1292
            let grant = Grant {
1293
                grantor: me_id.hash(),
1294
                subject: format!("agent:{name}@{username}"),
1295
                issuer: hub.hash(),
1296
                scope,
1297
                not_before: (now - 60_000) as u64,
1298
                expires: (now + duration_ms(&lasts)?) as u64,
1299
            };
1300
            let signed = SignedGrant::sign(grant, &me_id, &sk);
1301
            let r: serde_json::Value =
1302
                c.send("POST", "/agents/grants", &serde_json::json!({ "grant": oxy_core::dsse::base64(&signed.encode()) }))?;
1303
            if json {
1304
                println!("{r}");
1305
                return Ok(0);
1306
            }
1307
            println!(
1308
                "{} {} to act for you as {} ({}), until {}",
1309
                ui::ok("✔ granted"),
1310
                ui::strong(&name),
1311
                r["subject"].as_str().unwrap_or(""),
1312
                r["scope"].as_str().unwrap_or(""),
1313
                ui::date(r["expires_ms"].as_i64().unwrap_or(0))
1314
            );
1315
            println!("  token (shown once): {}", r["token"].as_str().unwrap_or(""));
1316
            println!(
1317
                "  {}",
1318
                ui::dim("in the agent's shell: oxy auth grant, paste the token; then oxy config --user author.signer keyless")
1319
            );
1320
            println!("  {}", ui::dim(&format!("revoke it with: oh agent revoke {}", r["id"])));
1321
            Ok(0)
1322
        }
1323
        AgentCmd::List => {
1324
            let grants: Vec<serde_json::Value> = c.get("/agents/grants")?;
1325
            if json {
1326
                println!("{}", serde_json::to_string(&grants)?);
1327
                return Ok(0);
1328
            }
1329
            if grants.is_empty() {
1330
                println!("{}", ui::dim("no agent grants"));
1331
            }
1332
            let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
1333
            for g in grants {
1334
                let state = if g["revoked_ms"].is_i64() {
1335
                    ui::bad("revoked")
1336
                } else if g["expires_ms"].as_i64().unwrap_or(0) <= now {
1337
                    ui::dim("ended")
1338
                } else {
1339
                    ui::ok("live")
1340
                };
1341
                let used = g["last_used_ms"].as_i64().map(|t| format!("used {}", ui::ago(t))).unwrap_or_else(|| "never used".into());
1342
                println!(
1343
                    "#{:<4} {:<8} {} · {} · until {} · {}",
1344
                    g["id"],
1345
                    state,
1346
                    ui::strong(g["subject"].as_str().unwrap_or("")),
1347
                    g["scope"].as_str().unwrap_or(""),
1348
                    ui::date(g["expires_ms"].as_i64().unwrap_or(0)),
1349
                    ui::dim(&used)
1350
                );
1351
            }
1352
            Ok(0)
1353
        }
1354
        AgentCmd::Revoke { id } => {
1355
            c.send_text("DELETE", &format!("/agents/grants/{id}"), &serde_json::json!({}))?;
1356
            println!("{} grant #{id}: no more certificates under it", ui::ok("✔ revoked"));
1357
            Ok(0)
1358
        }
5c6e92fd Andy McCall ↶ 1359
    }
1360
}
1361
1362
fn login(mut cfg: Config, url: &str, token: Option<String>, ca: Option<std::path::PathBuf>) -> Result<i32> {
1363
    let hub = url.trim_end_matches('/').to_string();
df71c789 Andy McCall ↶ 1364
    let token = match token.as_deref() {
1365
        Some("-") => {
5c6e92fd Andy McCall ↶ 1366
            eprintln!("Paste a token from {hub}/settings/tokens, then press Enter:");
1367
            let mut line = String::new();
1368
            std::io::stdin().read_line(&mut line)?;
1369
            line.trim().to_string()
1370
        }
df71c789 Andy McCall ↶ 1371
        Some(t) => t.to_string(),
1372
        None => device_sign_in(&hub, ca.clone())?,
5c6e92fd Andy McCall ↶ 1373
    };
1374
    if token.is_empty() {
1375
        bail!("no token given");
1376
    }
1377
    let t = Target { hub: hub.clone(), token: Some(token.clone()), ca: ca.clone(), owner: String::new(), name: String::new() };
1378
    let me: serde_json::Value = Client::new(&t)?.get("/user").context("checking the token")?;
2bbe88a8 Andy McCall ↶ 1379
    let account = me["username"].as_str().unwrap_or("?");
1380
    // One sign-in for oh and oxy alike: the token goes to oxy's store.
1381
    let key = oxy_core::credentials::hub_of(&hub).with_context(|| format!("{hub} is not a hub URL"))?;
1382
    let ca = ca.map(|c| std::fs::canonicalize(&c).unwrap_or(c));
1383
    oxy_core::credentials::Credentials::user().save(&key, &token, Some(account), ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?;
5c6e92fd Andy McCall ↶ 1384
    cfg.default_hub = Some(hub.clone());
1385
    cfg.save()?;
2bbe88a8 Andy McCall ↶ 1386
    println!("{} signed in to {hub} as {}", ui::ok("✔"), ui::strong(account));
1387
    println!("{}", ui::dim("  oxy uses this sign-in too; oxy auth status lists it, oxy auth logout ends it"));
5c6e92fd Andy McCall ↶ 1388
    Ok(0)
1389
}
1390
df71c789 Andy McCall ↶ 1391
/// Device sign-in (oxygenhub#67): the hub gives a code, the user approves
1392
/// it on the web, and the token arrives here.
1393
fn device_sign_in(hub: &str, ca: Option<std::path::PathBuf>) -> Result<String> {
1394
    let t = Target { hub: hub.to_string(), token: None, ca, owner: String::new(), name: String::new() };
1395
    let c = Client::new(&t)?;
1396
    let host = std::fs::read_to_string("/etc/hostname")
1397
        .ok()
1398
        .or_else(|| std::env::var("COMPUTERNAME").ok())
1399
        .map(|h| h.trim().to_string())
1400
        .filter(|h| !h.is_empty());
1401
    let client = match host {
1402
        Some(h) => format!("oh on {h}"),
1403
        None => "oh".to_string(),
1404
    };
1405
    let scopes = ["repo:read", "repo:write", "proposals:write", "issues:write", "user:read"];
1406
    let (code, body) = c.post_raw("/device/code", &serde_json::json!({ "client": client, "scopes": scopes }))?;
1407
    let v: serde_json::Value = serde_json::from_str(&body).context("the hub's answer to a device code request")?;
1408
    if code != 200 {
1409
        bail!("{hub} cannot sign in a device: {}", v["error_description"].as_str().or(v["detail"].as_str()).unwrap_or(&body));
1410
    }
1411
    let device = v["device_code"].as_str().context("no device code")?.to_string();
1412
    let user = v["user_code"].as_str().unwrap_or("?");
1413
    let url = v["verification_uri_complete"].as_str().or(v["verification_uri"].as_str()).unwrap_or(hub);
1414
    let mut interval = v["interval"].as_u64().unwrap_or(5).max(1);
1415
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(v["expires_in"].as_u64().unwrap_or(900));
1416
    eprintln!("Open {} and approve the code {}", ui::strong(url), ui::strong(user));
1417
    eprintln!("{}", ui::dim("Waiting for approval (Ctrl-C to give up)…"));
1418
    loop {
1419
        std::thread::sleep(std::time::Duration::from_secs(interval));
1420
        if std::time::Instant::now() > deadline {
1421
            bail!("the code expired before it was approved; run oh auth login again");
1422
        }
1423
        let (code, body) = c.post_raw("/device/token", &serde_json::json!({ "device_code": device }))?;
1424
        let v: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
1425
        if code == 200 {
1426
            return v["access_token"].as_str().map(String::from).context("no token in the hub's answer");
1427
        }
1428
        match v["error"].as_str() {
1429
            Some("authorization_pending") => {}
1430
            Some("slow_down") => interval += 5,
1431
            Some("access_denied") => bail!("the sign-in was denied on the web"),
1432
            Some("expired_token") => bail!("the code expired before it was approved; run oh auth login again"),
1433
            _ => bail!("signing in: HTTP {code}: {body}"),
1434
        }
1435
    }
1436
}
1437
5c6e92fd Andy McCall ↶ 1438
fn body_of(body: Option<String>, file: Option<String>) -> Result<String> {
1439
    match (body, file) {
1440
        (Some(b), _) => Ok(b),
1441
        (None, Some(f)) if f == "-" => {
1442
            let mut s = String::new();
1443
            std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
1444
            Ok(s)
1445
        }
1446
        (None, Some(f)) => std::fs::read_to_string(&f).with_context(|| format!("read {f}")),
1447
        (None, None) => Ok(String::new()),
1448
    }
1449
}
1450
1451
fn issue_line(i: &Issue) -> String {
1452
    let glyph = if i.state == "open" { ui::ok("●") } else { ui::dim("○") };
1453
    let labels: Vec<String> = i.labels.iter().map(|l| format!("[{}]", l.name)).collect();
1454
    format!(
1455
        "{glyph} {} {}{}{}",
1456
        ui::dim(&format!("#{}", i.number)),
1457
        i.title,
1458
        if labels.is_empty() { String::new() } else { format!(" {}", ui::dim(&labels.join(" "))) },
1459
        ui::dim(&format!(" · {} · {}", i.author, ui::ago(i.updated_ms)))
1460
    )
1461
}
1462
1463
fn issue(c: &Client, t: &Target, cmd: IssueCmd, json: bool) -> Result<i32> {
1464
    let base = t.repo_path()?;
1465
    match cmd {
1466
        IssueCmd::List { state } => {
1467
            let path = format!("{base}/issues?state={}", enc(&state));
1468
            if json {
1469
                println!("{}", c.get_text(&path)?);
1470
                return Ok(0);
1471
            }
1472
            let list: Vec<Issue> = c.get(&path)?;
1473
            if list.is_empty() {
1474
                println!("{}", ui::dim(&format!("No {state} issues.")));
1475
            }
1476
            for i in &list {
1477
                println!("{}", issue_line(i));
1478
            }
1479
        }
1480
        IssueCmd::View { number } => {
1481
            let path = format!("{base}/issues/{number}");
1482
            if json {
1483
                println!("{}", c.get_text(&path)?);
1484
                return Ok(0);
1485
            }
1486
            let i: Issue = c.get(&path)?;
1487
            println!("{}", issue_line(&i));
1488
            if !i.body.trim().is_empty() {
1489
                println!("\n{}\n", i.body.trim_end());
1490
            }
1491
            let comments: Vec<hub_api::Comment> = c.get(&format!("{path}/comments"))?;
1492
            for cm in comments {
1493
                println!("{} {}\n{}\n", ui::strong(&cm.author), ui::dim(&ui::ago(cm.created_ms)), cm.body.trim_end());
1494
            }
1495
            println!("{}", ui::dim(&i.url));
1496
        }
1c52d940 Andy McCall ↶ 1497
        IssueCmd::Create { title, body, body_file, label, project, column, attach } => {
1498
            let body = with_attachments(c, &base, body_of(body, body_file)?, &attach)?;
1499
            let new = NewIssue { title, body, labels: label, assignees: vec![], milestone: None };
5c6e92fd Andy McCall ↶ 1500
            let i: Issue = c.send("POST", &format!("{base}/issues"), &new)?;
1501
            if json {
1502
                println!("{}", serde_json::to_string(&i)?);
1503
            } else {
1504
                println!("{} opened #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
17a3a84b Andy McCall ↶ 1505
            }
1506
            if let Some(n) = project {
1507
                let card = hub_api::NewCard { column, reference: format!("{}#{}", t.name, i.number), note: String::new() };
1508
                let added: hub_api::ProjectCard = c.send("POST", &format!("/projects/{}/{n}/cards", t.owner), &card)?;
1509
                if !json {
1510
                    println!("{} on project {n} as card {}", ui::ok("✔"), added.id);
1511
                }
5c6e92fd Andy McCall ↶ 1512
            }
1513
        }
1514
        IssueCmd::Close { number, reason } => {
1515
            let i: Issue = c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "closed".into(), reason })?;
1516
            println!("{} closed #{} {}", ui::ok("✔"), i.number, i.title);
1517
        }
1518
        IssueCmd::Reopen { number } => {
1519
            let i: Issue =
1520
                c.send("POST", &format!("{base}/issues/{number}"), &IssueStateChange { state: "open".into(), reason: String::new() })?;
1521
            println!("{} reopened #{} {}", ui::ok("✔"), i.number, i.title);
b5229b56 Andy McCall ↶ 1522
        }
1523
        IssueCmd::Edit { number, title, body, body_file, label, no_labels, assignee, no_assignees, milestone } => {
1524
            let body = match (&body, &body_file) {
1525
                (None, None) => None,
1526
                _ => Some(body_of(body, body_file)?),
1527
            };
1528
            let labels = if no_labels {
1529
                Some(Vec::new())
1530
            } else if label.is_empty() {
1531
                None
1532
            } else {
1533
                Some(label)
1534
            };
1535
            let assignees = if no_assignees {
1536
                Some(Vec::new())
1537
            } else if assignee.is_empty() {
1538
                None
1539
            } else {
1540
                Some(assignee)
1541
            };
1542
            if title.is_none() && body.is_none() && labels.is_none() && assignees.is_none() && milestone.is_none() {
1543
                bail!("say what to change: --title, --body, --body-file, --label, --assignee or --milestone");
1544
            }
1545
            let edit = hub_api::IssueEdit { title, body, labels, assignees, milestone };
1546
            let i: Issue = c.send("PATCH", &format!("{base}/issues/{number}"), &edit)?;
1547
            if json {
1548
                println!("{}", serde_json::to_string(&i)?);
1549
            } else {
1550
                println!("{} edited #{} {}", ui::ok("✔"), i.number, ui::dim(&i.url));
1551
            }
2291f8cc Andy McCall ↶ 1552
        }
1553
        IssueCmd::Label(change) => {
1554
            let path = format!("{base}/issues/{}", change.number);
1555
            let now: Issue = c.get(&path)?;
1556
            let labels = change.apply(&now.labels)?;
1557
            let edit = hub_api::IssueEdit { title: None, body: None, labels: Some(labels.clone()), assignees: None, milestone: None };
1558
            let i: Issue = c.send("PATCH", &path, &edit)?;
1559
            if json {
1560
                println!("{}", serde_json::to_string(&i)?);
1561
            } else {
1562
                println!("{} #{} {}", ui::ok("✔"), i.number, label_names(&labels));
1563
            }
5c6e92fd Andy McCall ↶ 1564
        }
1c52d940 Andy McCall ↶ 1565
        IssueCmd::Comment { number, body, body_file, attach } => {
1566
            let body = with_attachments(c, &base, body_of(body, body_file)?, &attach)?;
bd91edeb Andy McCall ↶ 1567
            if body.trim().is_empty() {
1c52d940 Andy McCall ↶ 1568
                bail!("give the comment with --body, --body-file or --attach");
bd91edeb Andy McCall ↶ 1569
            }
5c6e92fd Andy McCall ↶ 1570
            c.send_text("POST", &format!("{base}/issues/{number}/comments"), &NewComment { body, path: None, line: None })?;
1571
            println!("{} commented on #{number}", ui::ok("✔"));
1572
        }
1573
    }
1574
    Ok(0)
1c52d940 Andy McCall ↶ 1575
}
1576
1577
/// `body` with each file attached to the repository and linked under it:
1578
/// an image shown in place, anything else a download (#350). Files are
1579
/// uploaded first, so a failed upload leaves nothing half made.
1580
fn with_attachments(c: &Client, base: &str, body: String, files: &[std::path::PathBuf]) -> Result<String> {
1581
    if files.is_empty() {
1582
        return Ok(body);
1583
    }
1584
    let mut links = Vec::new();
1585
    for f in files {
1586
        let bytes = std::fs::read(f).with_context(|| format!("reading {}", f.display()))?;
1587
        let name = f.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "file".into());
1588
        let answer = c.upload(&format!("{base}/attachments?name={}", enc(&name)), &bytes)?;
1589
        let a: hub_api::Attachment =
1590
            serde_json::from_str(&answer).with_context(|| format!("attaching {}: unexpected answer", f.display()))?;
1591
        links.push(a.markdown);
1592
    }
1593
    let links = links.join("\n\n");
1594
    Ok(if body.trim().is_empty() { links } else { format!("{}\n\n{links}", body.trim_end()) })
5c6e92fd Andy McCall ↶ 1595
}
1596
1597
fn source_name(s: &hub_api::ProposalSource) -> String {
1598
    match s {
1599
        hub_api::ProposalSource::Bookmark { bookmark } => bookmark.clone(),
1600
        hub_api::ProposalSource::Fork { owner, name, bookmark } => format!("{owner}/{name}:{bookmark}"),
1601
        hub_api::ProposalSource::Changes { hashes } => format!("{} changes", hashes.len()),
1602
    }
1603
}
1604
1605
fn proposal_line(p: &Proposal) -> String {
1606
    let state = serde_json::to_value(p.state).ok().and_then(|v| v.as_str().map(String::from)).unwrap_or_default();
1607
    let glyph = match state.as_str() {
1608
        "open" => ui::ok("●"),
1609
        "draft" => ui::dim("◌"),
1610
        "landed" => ui::strong("✔"),
1611
        _ => ui::dim("○"),
1612
    };
1613
    format!(
1614
        "{glyph} {} {} {}{}",
1615
        ui::dim(&format!("#{}", p.number)),
1616
        p.title,
1617
        ui::dim(&format!("{} → {}", source_name(&p.source), p.target)),
1618
        ui::dim(&format!(" · {} · {state}", p.author))
1619
    )
1620
}
1621
1622
fn proposal(c: &Client, t: &Target, cmd: ProposalCmd, json: bool) -> Result<i32> {
1623
    let base = t.repo_path()?;
1624
    match cmd {
d7e2c275 Andy McCall ↶ 1625
        ProposalCmd::List { state, limit } => {
1626
            let path = format!("{base}/proposals?state={state}&limit={limit}");
5c6e92fd Andy McCall ↶ 1627
            if json {
1628
                println!("{}", c.get_text(&path)?);
1629
                return Ok(0);
1630
            }
1631
            let list: Vec<Proposal> = c.get(&path)?;
1632
            if list.is_empty() {
0b20f1ec Andy McCall ↶ 1633
                println!("{}", ui::dim(&format!("No {} proposals.", if state == "all" { "" } else { &state }).replace("  ", " ")));
5c6e92fd Andy McCall ↶ 1634
            }
1635
            for p in &list {
1636
                println!("{}", proposal_line(p));
1637
            }
1638
        }
1639
        ProposalCmd::View { number } => {
1640
            let path = format!("{base}/proposals/{number}");
1641
            if json {
1642
                println!("{}", c.get_text(&path)?);
1643
                return Ok(0);
1644
            }
1645
            let p: Proposal = c.get(&path)?;
1646
            println!("{}", proposal_line(&p));
1647
            if !p.body.trim().is_empty() {
1648
                println!("\n{}\n", p.body.trim_end());
1649
            }
1650
            println!("{}", ui::kv("changes", &p.changes.len().to_string()));
1651
            for ch in &p.changes {
1652
                println!("  {} {}", ui::dim(&ch.hash[..12.min(ch.hash.len())]), ch.message.lines().next().unwrap_or(""));
1653
            }
1654
            println!("{}", ui::kv("approvals", &p.approvals.iter().map(|a| a.account.clone()).collect::<Vec<_>>().join(", ")));
1655
            if p.landable {
1656
                println!("{} can land", ui::ok("✔"));
1657
            } else {
1658
                for b in &p.blockers {
1659
                    println!("{} {b}", ui::bad("✘"));
1660
                }
1661
            }
1662
            if p.conflicted {
1663
                println!("{} landing it would leave conflicts", ui::bad("!"));
1664
            }
1665
            println!("{}", ui::dim(&p.url));
1666
        }
739a763a Andy McCall ↶ 1667
        ProposalCmd::Create { title, body, body_file, from, into, draft } => {
5c6e92fd Andy McCall ↶ 1668
            let target = match into {
1669
                Some(i) => i,
1670
                None => c.get::<serde_json::Value>(&base)?["default_bookmark"].as_str().unwrap_or("main").to_string(),
1671
            };
739a763a Andy McCall ↶ 1672
            let new = NewProposal { title, body: body_of(body, body_file)?, target, source: from, draft };
5c6e92fd Andy McCall ↶ 1673
            let p: Proposal = c.send("POST", &format!("{base}/proposals"), &new)?;
1674
            if json {
1675
                println!("{}", serde_json::to_string(&p)?);
1676
            } else {
1677
                println!("{} proposed #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
1f1eb06a Andy McCall ↶ 1678
            }
739a763a Andy McCall ↶ 1679
        }
1680
        ProposalCmd::Edit { number, title, body, body_file } => {
1681
            let body = match (&body, &body_file) {
1682
                (None, None) => None,
1683
                _ => Some(body_of(body, body_file)?),
1684
            };
1685
            if title.is_none() && body.is_none() {
1686
                bail!("say what to change: --title, --body or --body-file");
1687
            }
09ffa7b6 Andy McCall ↶ 1688
            let edit = hub_api::ProposalEdit { title, body, ..Default::default() };
739a763a Andy McCall ↶ 1689
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
1690
            if json {
1691
                println!("{}", serde_json::to_string(&p)?);
1692
            } else {
1693
                println!("{} edited #{} {}", ui::ok("✔"), p.number, ui::dim(&p.url));
2291f8cc Andy McCall ↶ 1694
            }
1695
        }
1696
        ProposalCmd::Label(change) => {
1697
            let path = format!("{base}/proposals/{}", change.number);
1698
            let now: Proposal = c.get(&path)?;
1699
            let labels = change.apply(&now.labels)?;
1700
            let edit = hub_api::ProposalEdit { labels: Some(labels.clone()), ..Default::default() };
1701
            let p: Proposal = c.send("PATCH", &path, &edit)?;
1702
            if json {
1703
                println!("{}", serde_json::to_string(&p)?);
1704
            } else {
1705
                println!("{} #{} {}", ui::ok("✔"), p.number, label_names(&labels));
739a763a Andy McCall ↶ 1706
            }
1707
        }
1708
        ProposalCmd::Comment { number, body, body_file } => {
1709
            let body = body_of(body, body_file)?;
1710
            if body.trim().is_empty() {
1711
                bail!("give the comment with --body or --body-file");
1712
            }
1713
            c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
1714
            println!("{} commented on #{number}", ui::ok("✔"));
86a69b53 Andy McCall ↶ 1715
        }
1716
        ProposalCmd::Land { number, when_ready: true, off, .. } => {
1717
            let path = format!("{base}/proposals/{number}/auto-land");
1718
            let p: Proposal =
1719
                if off { c.send("DELETE", &path, &serde_json::json!({}))? } else { c.send("POST", &path, &serde_json::json!({}))? };
1720
            if json {
1721
                println!("{}", serde_json::to_string(&p)?);
1722
            } else if p.landed.is_some() {
1723
                println!("{} landed #{} on {}: its checks had passed", ui::ok("✔"), p.number, p.target);
1724
            } else if p.auto_land.is_some() {
1725
                println!("{} #{} will land when its checks pass", ui::ok("✔"), p.number);
1726
            } else {
1727
                println!("{} #{} will not land by itself", ui::ok("✔"), p.number);
1728
            }
1f1eb06a Andy McCall ↶ 1729
        }
86a69b53 Andy McCall ↶ 1730
        ProposalCmd::Land { number, over_checks, .. } => {
2a8b6216 Andy McCall ↶ 1731
            let body = match &over_checks {
1732
                Some(r) => serde_json::json!({ "over_checks": r }),
1733
                None => serde_json::json!({}),
1734
            };
1735
            let p: Proposal = c.send("POST", &format!("{base}/proposals/{number}/land"), &body)?;
1f1eb06a Andy McCall ↶ 1736
            if json {
1737
                println!("{}", serde_json::to_string(&p)?);
1738
            } else {
1739
                println!("{} landed #{} on {}", ui::ok("✔"), p.number, p.target);
71e65fcf Andy McCall ↶ 1740
            }
1741
        }
1742
        ProposalCmd::Close { number, message } => {
1743
            if let Some(body) = message {
1744
                c.send_text("POST", &format!("{base}/proposals/{number}/comments"), &NewComment { body, path: None, line: None })?;
1745
            }
1746
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "closed" }))?;
1747
            if json {
1748
                println!("{}", serde_json::to_string(&p)?);
1749
            } else {
1750
                println!("{} closed #{} {}", ui::ok("✔"), p.number, p.title);
1751
            }
1752
        }
1753
        ProposalCmd::Reopen { number } => {
1754
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &serde_json::json!({ "state": "open" }))?;
1755
            if json {
1756
                println!("{}", serde_json::to_string(&p)?);
1757
            } else {
1758
                println!("{} reopened #{} {}", ui::ok("✔"), p.number, p.title);
09ffa7b6 Andy McCall ↶ 1759
            }
1760
        }
1761
        ProposalCmd::Ready { number, undo } => {
1762
            let edit = hub_api::ProposalEdit { draft: Some(undo), ..Default::default() };
1763
            let p: Proposal = c.send("PATCH", &format!("{base}/proposals/{number}"), &edit)?;
1764
            if json {
1765
                println!("{}", serde_json::to_string(&p)?);
1766
            } else if undo {
1767
                println!("{} #{} {} is a draft again", ui::ok("✔"), p.number, p.title);
1768
            } else {
1769
                println!("{} #{} {} is ready for review", ui::ok("✔"), p.number, p.title);
5c6e92fd Andy McCall ↶ 1770
            }
1771
        }
1772
        ProposalCmd::Checks { number } => {
1773
            let path = format!("{base}/proposals/{number}/checks");
1774
            if json {
1775
                println!("{}", c.get_text(&path)?);
1776
                return Ok(0);
1777
            }
1778
            let checks: Vec<hub_api::Check> = c.get(&path)?;
1779
            if checks.is_empty() {
1780
                println!("{}", ui::dim("No checks yet."));
1781
            }
1782
            for ch in checks {
1783
                println!("{} {} {}", ui::status(ch.status.as_str()), ch.name, ui::dim(&ch.summary));
1784
            }
1785
        }
1786
    }
1787
    Ok(0)
1788
}
1789
1790
fn run_line(r: &FlowRun) -> String {
1791
    let what =
1792
        if r.bookmark.is_empty() { format!("change {}", r.heads.first().map(|h| &h[..12]).unwrap_or("")) } else { r.bookmark.clone() };
1793
    format!(
1794
        "{} {} {} {}",
1795
        ui::status(&r.status),
1796
        ui::dim(&format!("#{}", r.number)),
1797
        what,
1798
        ui::dim(&format!("· {} by {} · {}", r.trigger, r.actor, ui::ago(r.created_ms)))
1799
    )
1800
}
1801
fac6853c Andy McCall ↶ 1802
fn print_run(r: &FlowRun, timings: bool) {
5c6e92fd Andy McCall ↶ 1803
    println!("{}", run_line(r));
1804
    for j in &r.jobs {
1805
        let dur = match (j.started_ms, j.finished_ms) {
1806
            (Some(a), Some(b)) => format!(" {:.1} s", (b - a) as f64 / 1000.0),
1807
            _ => String::new(),
1808
        };
1809
        let on = if j.runner.is_empty() { String::new() } else { format!(" on {}", j.runner) };
1810
        println!("  {} {}{}", ui::status(&j.status), j.name, ui::dim(&format!("{dur}{on}")));
501d8b26 Andy McCall ↶ 1811
        // Why a queued job no runner can take waits (oxygenhub#28), and
1812
        // why a job ran where it did (oxygenflow#42).
67040b15 Andy McCall ↶ 1813
        if j.status == "queued" && !j.waiting.is_empty() {
1814
            println!("    {}", ui::warn(&format!("waiting: {}", j.waiting)));
501d8b26 Andy McCall ↶ 1815
        } else if !j.placed.is_empty() {
1816
            println!("    {}", ui::dim(&format!("placed: {}", j.placed)));
67040b15 Andy McCall ↶ 1817
        }
fac6853c Andy McCall ↶ 1818
        if timings {
1819
            let t = timing_line(j);
1820
            if !t.is_empty() {
1821
                println!("    {}", ui::dim(&t));
1822
            }
1823
        }
5c6e92fd Andy McCall ↶ 1824
    }
1825
    if !r.error.is_empty() {
1826
        println!("{}", ui::bad(&r.error));
1827
    }
1828
    println!("{}", ui::dim(&r.url));
1829
}
1830
fac6853c Andy McCall ↶ 1831
/// Milliseconds as a person reads them: "850 ms", "3.1 s", "2 min 5 s".
1832
fn took(ms: i64) -> String {
1833
    match ms {
1834
        ..=999 => format!("{ms} ms"),
1835
        1000..=59_999 => format!("{:.1} s", ms as f64 / 1000.0),
1836
        _ => format!("{} min {} s", ms / 60_000, (ms % 60_000) / 1000),
1837
    }
1838
}
1839
1840
/// MiB as a person reads them.
1841
fn mib(m: i64) -> String {
1842
    if m >= 1024 {
1843
        format!("{:.1} GiB", m as f64 / 1024.0)
1844
    } else {
1845
        format!("{m} MiB")
1846
    }
1847
}
1848
1849
/// Where a job's time went (oxygenhub#348): its wait for a runner, each
1850
/// phase its runner reported, and the most disk and memory it took.
1851
fn timing_line(j: &FlowJob) -> String {
1852
    let mut parts = vec![];
1853
    if let (Some(q), Some(s)) = (j.queued_ms, j.started_ms) {
1854
        parts.push(format!("waited {}", took((s - q).max(0))));
1855
    }
1856
    parts.extend(j.phases.iter().map(|p| format!("{} {}", p.name, took(p.ms as i64))));
1857
    let peaks: Vec<String> = [("disk", j.peak_disk_mib), ("memory", j.peak_memory_mib)]
1858
        .into_iter()
1859
        .filter_map(|(what, m)| m.map(|m| format!("{what} {}", mib(m))))
1860
        .collect();
1861
    if !peaks.is_empty() {
1862
        parts.push(format!("peak {}", peaks.join(", ")));
1863
    }
1864
    parts.join(" · ")
1865
}
1866
1867
/// A report's path, its segments encoded and its slashes kept.
1868
fn enc_path(path: &str) -> String {
1869
    path.split('/').map(enc).collect::<Vec<_>>().join("/")
1870
}
1871
1872
/// `oh run report` and `oh report show`: the report at `at` (JSON), whose
1873
/// files are at `files(path)`. By default its report.toml; with `list`
1874
/// what it holds; with `file` one file, to stdout or `output`.
1875
fn show_report(
1876
    c: &Client,
1877
    at: &str,
1878
    files: impl Fn(&str) -> String,
1879
    list: bool,
1880
    file: Option<String>,
1881
    output: Option<std::path::PathBuf>,
1882
    json: bool,
1883
) -> Result<()> {
1884
    use std::io::Write;
1885
    if let Some(path) = file {
1886
        let bytes = c.get_bytes(&files(&path))?;
1887
        match output {
1888
            Some(out) => {
1889
                std::fs::write(&out, &bytes).with_context(|| format!("writing {}", out.display()))?;
1890
                eprintln!("{} {path}: {} bytes to {}", ui::ok("✔"), bytes.len(), out.display());
1891
            }
1892
            None => std::io::stdout().write_all(&bytes)?,
1893
        }
1894
        return Ok(());
1895
    }
1896
    if json {
1897
        println!("{}", c.get_text(at)?);
1898
        return Ok(());
1899
    }
1900
    if !list {
1901
        std::io::stdout().write_all(&c.get_bytes(&files("report.toml"))?)?;
1902
        return Ok(());
1903
    }
1904
    let r: Report = c.get(at)?;
1905
    print_report(&r);
1906
    if r.files_expired_ms.is_some() {
1907
        println!("{}", ui::warn("its files expired under retention; its metrics stay"));
1908
    }
1909
    for f in &r.manifest {
1910
        println!("  {:>10}  {}", ui::dim(&f.size.to_string()), f.path);
1911
    }
1912
    println!("{}", ui::dim(&r.url));
1913
    Ok(())
1914
}
1915
1916
/// A report's heading, metrics and context.
1917
fn print_report(r: &Report) {
1918
    let from = match r.run {
1919
        Some(n) => format!("run #{n} {} on {}", r.job, r.bookmark),
1920
        None => format!("upload on {}", if r.bookmark.is_empty() { "a change" } else { &r.bookmark }),
1921
    };
1922
    println!(
1923
        "{} {} {}",
1924
        ui::strong(&r.name),
1925
        ui::dim(&format!("{} · {:?}", r.kind, r.title)),
1926
        ui::dim(&format!("· {from} · {} files", r.files))
1927
    );
1928
    if !r.summary.is_empty() {
1929
        println!("  {}", r.summary);
1930
    }
1931
    for m in &r.metrics {
1932
        let unit = if m.unit.is_empty() { String::new() } else { format!(" {}", m.unit) };
1933
        let mut notes = vec![];
1934
        if !m.better.is_empty() {
1935
            notes.push(format!("{} is better", m.better));
1936
        }
1937
        if let Some(a) = m.fail_above {
1938
            notes.push(format!("fails above {a}"));
1939
        }
1940
        if let Some(b) = m.fail_below {
1941
            notes.push(format!("fails below {b}"));
1942
        }
1943
        let notes = if notes.is_empty() { String::new() } else { format!("  ({})", notes.join(", ")) };
1944
        println!("  {} {}{unit}{}", m.key, m.value, ui::dim(&notes));
1945
    }
1946
    if let Some(ctx) = r.context.as_object().filter(|m| !m.is_empty()) {
1947
        let line: Vec<String> =
1948
            ctx.iter().map(|(k, v)| format!("{k}={}", v.as_str().map(String::from).unwrap_or_else(|| v.to_string()))).collect();
1949
        println!("  {}", ui::dim(&line.join(" ")));
1950
    }
1951
}
1952
1953
/// `oh report …` (oxygenhub#348).
1954
fn report(c: &Client, t: &Target, cmd: ReportCmd, json: bool) -> Result<i32> {
1955
    let base = t.repo_path()?;
1956
    match cmd {
1957
        ReportCmd::List { bookmark } => {
1958
            let path = format!("{base}/reports{}", bookmark.map(|b| format!("?bookmark={}", enc(&b))).unwrap_or_default());
1959
            if json {
1960
                println!("{}", c.get_text(&path)?);
1961
                return Ok(0);
1962
            }
1963
            let list: Vec<Report> = c.get(&path)?;
1964
            if list.is_empty() {
1965
                println!("{}", ui::dim("No reports yet: a Flow job publishes one with `output { report \"name\" { path … } }`."));
1966
            }
1967
            for r in &list {
1968
                print_report(r);
1969
            }
1970
        }
1971
        ReportCmd::Show { report, id, bookmark, list, file, output } => {
1972
            let at = format!("{base}/reports/{}", enc(&report));
1973
            let query = match (id, bookmark) {
1974
                (Some(id), _) => format!("?id={id}"),
1975
                (None, Some(b)) => format!("?bookmark={}", enc(&b)),
1976
                (None, None) => String::new(),
1977
            };
1978
            let files = |path: &str| format!("{at}/files/{}{query}", enc_path(path));
1979
            show_report(c, &format!("{at}{query}"), files, list, file, output, json)?;
1980
        }
1981
    }
1982
    Ok(0)
1983
}
1984
5c6e92fd Andy McCall ↶ 1985
fn live(status: &str) -> bool {
1986
    matches!(status, "queued" | "running")
dc59d1b5 Andy McCall ↶ 1987
}
1988
1989
/// `oh run approve|reject N --job NAME` (oxygenflow#57).
1990
fn decide_job(c: &Client, base: &str, number: i64, job: &str, verb: &str, json: bool) -> Result<()> {
1991
    let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/{verb}"), &serde_json::json!({}))?;
1992
    if json {
1993
        println!("{done}");
1994
    } else {
1995
        println!("{} run #{number}: {}", ui::ok("✔"), done["said"].as_str().unwrap_or(""));
1996
    }
1997
    Ok(())
5c6e92fd Andy McCall ↶ 1998
}
1999
2000
fn watch(c: &Client, base: &str, number: i64, json: bool) -> Result<i32> {
2001
    let path = format!("{base}/flow/runs/{number}");
2002
    let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
2003
    loop {
2004
        let r: FlowRun = c.get(&path)?;
2005
        if !json {
2006
            for j in &r.jobs {
67040b15 Andy McCall ↶ 2007
                let shown = format!("{}\u{0}{}", j.status, j.waiting);
2008
                if seen.get(&j.name) != Some(&shown) {
5c6e92fd Andy McCall ↶ 2009
                    println!("{} {}", ui::status(&j.status), j.name);
67040b15 Andy McCall ↶ 2010
                    if j.status == "queued" && !j.waiting.is_empty() {
2011
                        println!("  {}", ui::warn(&format!("waiting: {}", j.waiting)));
2012
                    }
2013
                    seen.insert(j.name.clone(), shown);
5c6e92fd Andy McCall ↶ 2014
                }
2015
            }
2016
        }
2017
        if !live(&r.status) {
2018
            if json {
2019
                println!("{}", serde_json::to_string(&r)?);
2020
            } else {
2021
                println!("{} run #{} {}", ui::status(&r.status), r.number, r.status);
2022
            }
2023
            return Ok(if r.status == "passed" { 0 } else { 1 });
2024
        }
2025
        std::thread::sleep(Duration::from_secs(3));
2026
    }
2027
}
2028
2029
fn flow(c: &Client, t: &Target, cmd: RunCmd, json: bool) -> Result<i32> {
2030
    let base = t.repo_path()?;
2031
    match cmd {
2032
        RunCmd::List { limit } => {
2033
            let path = format!("{base}/flow/runs?limit={limit}");
2034
            if json {
2035
                println!("{}", c.get_text(&path)?);
2036
                return Ok(0);
2037
            }
2038
            let runs: Vec<FlowRun> = c.get(&path)?;
2039
            if runs.is_empty() {
2040
                println!("{}", ui::dim("No runs yet."));
2041
            }
2042
            for r in &runs {
2043
                println!("{}", run_line(r));
2044
            }
2045
        }
fac6853c Andy McCall ↶ 2046
        RunCmd::View { number, timings } => {
5c6e92fd Andy McCall ↶ 2047
            let path = format!("{base}/flow/runs/{number}");
2048
            if json {
2049
                println!("{}", c.get_text(&path)?);
2050
                return Ok(0);
2051
            }
fac6853c Andy McCall ↶ 2052
            print_run(&c.get(&path)?, timings);
5c6e92fd Andy McCall ↶ 2053
        }
0650d94e Andy McCall ↶ 2054
        RunCmd::Start { bookmark, change, jobs, watch: follow } => {
2055
            let mut body = match (bookmark, change) {
5c6e92fd Andy McCall ↶ 2056
                (_, Some(ch)) => serde_json::json!({ "change": ch }),
2057
                (Some(b), None) => serde_json::json!({ "bookmark": b }),
2058
                (None, None) => serde_json::json!({}),
2059
            };
0650d94e Andy McCall ↶ 2060
            if !jobs.is_empty() {
2061
                body["jobs"] = serde_json::json!(jobs);
2062
            }
5c6e92fd Andy McCall ↶ 2063
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs"), &body)?;
2064
            let n = started["number"].as_i64().context("the hub named no run")?;
2065
            if !json || !follow {
2066
                if json {
2067
                    println!("{started}");
2068
                } else {
2069
                    println!("{} started run #{n} {}", ui::ok("✔"), ui::dim(started["url"].as_str().unwrap_or("")));
2070
                }
2071
            }
2072
            if follow {
2073
                return watch(c, &base, n, json);
2074
            }
2075
        }
2076
        RunCmd::Watch { number } => return watch(c, &base, number, json),
2077
        RunCmd::Log { number, job } => {
2078
            let mut after = 0;
2079
            loop {
2080
                let path = format!("{base}/flow/runs/{number}/jobs/{}/log?after={after}&limit=5000", enc(&job));
2081
                let lines: Vec<FlowLogLine> = c.get(&path)?;
2082
                if lines.is_empty() {
2083
                    break;
2084
                }
2085
                for l in &lines {
2086
                    if json {
2087
                        println!("{}", serde_json::to_string(l)?);
2088
                    } else if l.stream == "flow" {
2089
                        println!("{}", ui::dim(&l.text));
2090
                    } else {
2091
                        println!("{}", l.text);
2092
                    }
2093
                }
2094
                after = lines.last().map(|l| l.seq).unwrap_or(after);
e8fa5369 Andy McCall ↶ 2095
            }
fac6853c Andy McCall ↶ 2096
        }
2097
        RunCmd::Report { number, job, pick } => {
2098
            let at = format!("{base}/flow/runs/{number}/jobs/{}/report", enc(&job));
2099
            let query = pick.name.as_deref().map(|n| format!("?name={}", enc(n))).unwrap_or_default();
2100
            let files = |path: &str| format!("{at}/{}{query}", enc_path(path));
2101
            show_report(c, &format!("{at}{query}"), files, pick.list, pick.file, pick.output, json)?;
e8fa5369 Andy McCall ↶ 2102
        }
2103
        RunCmd::Rerun { number, job: Some(job) } => {
2104
            let queued: serde_json::Value =
2105
                c.send("POST", &format!("{base}/flow/runs/{number}/jobs/{job}/rerun"), &serde_json::json!({}))?;
2106
            if json {
2107
                println!("{queued}");
2108
            } else {
2109
                let n = queued["queued"].as_i64().unwrap_or(1);
2110
                let with = if n > 1 { format!(" with the {} that depend on it", n - 1) } else { String::new() };
2111
                println!("{} queued {job} of run #{number} again{with}", ui::ok("✔"));
5c6e92fd Andy McCall ↶ 2112
            }
2113
        }
e8fa5369 Andy McCall ↶ 2114
        RunCmd::Rerun { number, job: None } => {
5c6e92fd Andy McCall ↶ 2115
            let started: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/rerun"), &serde_json::json!({}))?;
2116
            if json {
2117
                println!("{started}");
2118
            } else {
2119
                println!("{} started run #{} {}", ui::ok("✔"), started["number"], ui::dim(started["url"].as_str().unwrap_or("")));
2291f8cc Andy McCall ↶ 2120
            }
2121
        }
dc59d1b5 Andy McCall ↶ 2122
        RunCmd::Approve { number, job } => decide_job(c, &base, number, &job, "approve", json)?,
2123
        RunCmd::Reject { number, job } => decide_job(c, &base, number, &job, "reject", json)?,
745d225d Andy McCall ↶ 2124
        RunCmd::Cancel { number } => {
2125
            let done: serde_json::Value = c.send("POST", &format!("{base}/flow/runs/{number}/cancel"), &serde_json::json!({}))?;
2126
            if json {
2127
                println!("{done}");
2128
            } else {
2129
                println!("{} cancelled run #{number}", ui::ok("✔"));
2130
            }
2131
        }
2291f8cc Andy McCall ↶ 2132
    }
2133
    Ok(0)
2134
}
2135
2136
fn label(c: &Client, t: &Target, cmd: LabelCmd, json: bool) -> Result<i32> {
2137
    let base = t.repo_path()?;
2138
    match cmd {
2139
        LabelCmd::List => {
2140
            let path = format!("{base}/labels");
2141
            if json {
2142
                println!("{}", c.get_text(&path)?);
2143
                return Ok(0);
2144
            }
2145
            let labels: Vec<hub_api::Label> = c.get(&path)?;
2146
            if labels.is_empty() {
2147
                println!("{}", ui::dim("No labels."));
5c6e92fd Andy McCall ↶ 2148
            }
2291f8cc Andy McCall ↶ 2149
            for l in labels {
2150
                println!("{} {}  {}", ui::dim(&l.colour), l.name, ui::dim(&l.description));
2151
            }
2152
        }
2153
        LabelCmd::Create { name, colour, description } => {
2154
            let l: hub_api::Label = c.send("POST", &format!("{base}/labels"), &hub_api::NewLabel { name, colour, description })?;
2155
            if json {
2156
                println!("{}", serde_json::to_string(&l)?);
2157
            } else {
2158
                println!("{} label {} {}", ui::ok("✔"), l.name, ui::dim(&l.colour));
2159
            }
2160
        }
2161
        LabelCmd::Delete { name } => {
2162
            c.send_text("DELETE", &format!("{base}/labels/{}", enc(&name)), &serde_json::json!({}))?;
2163
            println!("{} deleted label {name}", ui::ok("✔"));
62ceb2ee Andy McCall ↶ 2164
        }
2165
    }
2166
    Ok(0)
2167
}
2168
2169
fn assistant(c: &Client, t: &Target, cmd: AssistantCmd, org: Option<String>, site: bool, json: bool) -> Result<i32> {
2170
    let base = match (&org, site) {
2171
        (Some(o), _) => format!("/orgs/{}/assistants", enc(o)),
2172
        (None, true) => "/admin/assistants".to_string(),
2173
        (None, false) => format!("{}/assistants", t.repo_path()?),
2174
    };
2175
    match cmd {
2176
        AssistantCmd::List => {
2177
            if json {
2178
                println!("{}", c.get_text(&base)?);
2179
                return Ok(0);
2180
            }
2181
            let list: Vec<hub_api::Assistant> = c.get(&base)?;
2182
            if list.is_empty() {
2183
                println!("{}", ui::dim("No assistants."));
2184
            }
2185
            for a in list {
2186
                let state = if a.enabled && !a.off_above {
2187
                    ui::ok("on")
2188
                } else if a.off_above {
2189
                    ui::dim("off above")
2190
                } else {
2191
                    ui::dim("off")
2192
                };
2193
                let from = if a.from.is_empty() { String::new() } else { ui::dim(&format!(" · from {}", a.from)) };
2194
                println!("{} {}  {} {}{}", state, a.name, ui::dim(&a.model), ui::dim(&a.endpoint), from);
2195
            }
2196
        }
2197
        AssistantCmd::Add { name, preset, endpoint, api, model, token_env, off } => {
2198
            let token = match token_env {
2199
                Some(var) => std::env::var(&var).map_err(|_| anyhow::anyhow!("${var} is not set"))?,
2200
                None => String::new(),
2201
            };
2202
            let body =
2203
                hub_api::NewAssistant { name, preset, endpoint, api, model, token, headers: String::new(), enabled: !off, budget: None };
2204
            let r: serde_json::Value = c.send("POST", &base, &body)?;
2205
            println!("{} {}", ui::ok("✔"), r["ok"].as_str().unwrap_or("saved"));
2206
        }
2207
        AssistantCmd::Remove { name } => {
2208
            c.send_text("DELETE", &format!("{base}/{}", enc(&name)), &serde_json::json!({}))?;
2209
            println!("{} removed {name}", ui::ok("✔"));
2210
        }
2211
        AssistantCmd::Prompt { set } => {
2212
            let p: hub_api::AssistantPrompt = match set {
2213
                Some(path) => {
2214
                    let text = if path.as_os_str() == "-" {
2215
                        let mut s = String::new();
2216
                        std::io::Read::read_to_string(&mut std::io::stdin(), &mut s)?;
2217
                        s
2218
                    } else {
2219
                        std::fs::read_to_string(&path)?
2220
                    };
2221
                    c.send("PUT", &format!("{base}/prompt"), &hub_api::AssistantPrompt { prompt: text, inherited: vec![] })?
2222
                }
2223
                None => c.get(&format!("{base}/prompt"))?,
2224
            };
2225
            if json {
2226
                println!("{}", serde_json::to_string(&p)?);
2227
                return Ok(0);
2228
            }
2229
            for (from, text) in &p.inherited {
2230
                println!("{}\n{}\n", ui::dim(&format!("── from {from}")), text);
2231
            }
2232
            if p.prompt.is_empty() {
2233
                println!("{}", ui::dim("No prompt of its own."));
2234
            } else {
2235
                println!("{}\n{}", ui::dim("── this level"), p.prompt);
2236
            }
17a3a84b Andy McCall ↶ 2237
        }
2238
    }
2239
    Ok(0)
2240
}
2241
2242
fn project_line(p: &hub_api::Project) -> String {
2243
    let glyph = if p.closed { ui::dim("▢") } else { ui::ok("▣") };
2244
    let private = if p.public { "" } else { " · private" };
2245
    format!("{glyph} {} {}  {}", ui::dim(&p.number.to_string()), p.title, ui::dim(&format!("updated {}{private}", ui::ago(p.updated_ms))))
2246
}
2247
2248
fn project(c: &Client, t: &Target, cmd: ProjectCmd, owner: Option<String>, json: bool) -> Result<i32> {
2249
    let owner = match owner {
2250
        Some(o) => o,
2251
        None => t.repo()?.0.to_string(),
2252
    };
2253
    let base = format!("/projects/{}", enc(&owner));
2254
    let state = |number: i64, closed: bool, verb: &str| -> Result<()> {
2255
        let p: hub_api::Project =
2256
            c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { closed: Some(closed), ..Default::default() })?;
2257
        if json {
2258
            println!("{}", serde_json::to_string(&p)?);
2259
        } else {
2260
            println!("{} {verb} project {} {}", ui::ok("✔"), p.number, p.title);
2261
        }
2262
        Ok(())
2263
    };
2264
    match cmd {
2265
        ProjectCmd::List => {
2266
            if json {
2267
                println!("{}", c.get_text(&base)?);
2268
                return Ok(0);
2269
            }
2270
            let list: Vec<hub_api::Project> = c.get(&base)?;
2271
            if list.is_empty() {
2272
                println!("{}", ui::dim(&format!("No projects for {owner}: oh project create TITLE")));
2273
            }
2274
            for p in &list {
2275
                println!("{}", project_line(p));
2276
            }
2277
        }
439ecd87 Andy McCall ↶ 2278
        ProjectCmd::View { number, archived } => {
17a3a84b Andy McCall ↶ 2279
            let path = format!("{base}/{number}");
439ecd87 Andy McCall ↶ 2280
            let cards = format!("{path}/cards?archived=true");
17a3a84b Andy McCall ↶ 2281
            if json {
439ecd87 Andy McCall ↶ 2282
                println!("{}", c.get_text(if archived { &cards } else { &path })?);
17a3a84b Andy McCall ↶ 2283
                return Ok(0);
2284
            }
439ecd87 Andy McCall ↶ 2285
            let mut b: hub_api::Board = c.get(&path)?;
2286
            if archived {
2287
                b.columns = c.get(&cards)?;
2288
            }
17a3a84b Andy McCall ↶ 2289
            println!("{}", project_line(&b.project));
2290
            if !b.project.description.is_empty() {
2291
                println!("{}", b.project.description);
2292
            }
2293
            for col in &b.columns {
2294
                println!();
2295
                println!("{} {}", ui::strong(&col.name), ui::dim(&format!("{} · column {}", col.cards.len(), col.id)));
2296
                if col.cards.is_empty() {
2297
                    println!("  {}", ui::dim("(empty)"));
2298
                }
2299
                for card in &col.cards {
2300
                    let what = if card.reference.is_empty() { ui::dim("note") } else { card.reference.clone() };
2301
                    let st = if card.state.is_empty() { String::new() } else { format!(" {}", ui::dim(&card.state)) };
6a306cd0 Andy McCall ↶ 2302
                    let mut tags: Vec<String> = card.labels.iter().map(|l| format!("[{l}]")).collect();
2303
                    tags.extend(card.assignees.iter().map(|a| format!("@{a}")));
2304
                    let tags = if tags.is_empty() { String::new() } else { format!("  {}", ui::dim(&tags.join(" "))) };
2305
                    println!("  {} {what}{st}  {}{tags}", ui::dim(&format!("{:>4}", card.id)), card.title);
17a3a84b Andy McCall ↶ 2306
                }
2307
            }
2308
            println!("{}", ui::dim(&format!("\n{}", b.project.url)));
2309
        }
2310
        ProjectCmd::Create { title, description, private } => {
2311
            let p: hub_api::Project = c.send("POST", &base, &hub_api::NewProject { title, description, private })?;
2312
            if json {
2313
                println!("{}", serde_json::to_string(&p)?);
2314
            } else {
2315
                println!("{} project {} {} {}", ui::ok("✔"), p.number, p.title, ui::dim(&p.url));
2316
            }
2317
        }
2318
        ProjectCmd::Close { number } => state(number, true, "closed")?,
2319
        ProjectCmd::Reopen { number } => state(number, false, "reopened")?,
b1e92a62 Andy McCall ↶ 2320
        ProjectCmd::Transfer { number, to } => {
2321
            let p: hub_api::Project =
2322
                c.send("PATCH", &format!("{base}/{number}"), &hub_api::ProjectEdit { owner: Some(to.clone()), ..Default::default() })?;
2323
            if json {
2324
                println!("{}", serde_json::to_string(&p)?);
2325
            } else {
2326
                println!("{} transferred project {} to {to}: now {} {}", ui::ok("✔"), number, p.number, p.url);
2327
            }
2328
        }
17a3a84b Andy McCall ↶ 2329
        ProjectCmd::Card { cmd: CardCmd::Add { number, reference, note, column } } => {
2330
            // The hub names a card's issue as `repo#N` among the owner's
2331
            // repositories.
2332
            let reference = match reference {
2333
                None => String::new(),
2334
                Some(r) if r.contains('#') && !r.starts_with('#') => match r.split_once('/') {
2335
                    Some((o, rest)) if o == owner => rest.to_string(),
2336
                    Some(_) => bail!("{r}: a project holds only {owner}'s issues and proposals"),
2337
                    None => r,
2338
                },
2339
                Some(r) => {
2340
                    let n = r.trim_start_matches('#');
2341
                    if n.parse::<i64>().is_err() {
2342
                        bail!("{r}: give an issue or proposal number, or NAME#N");
2343
                    }
2344
                    format!("{}#{n}", t.repo()?.1)
2345
                }
2346
            };
2347
            let note = note.unwrap_or_default();
2348
            if reference.is_empty() && note.is_empty() {
2349
                bail!("say what to add: an issue or proposal (12, #12, owner/name#12) or --note TEXT");
2350
            }
2351
            let card: hub_api::ProjectCard =
2352
                c.send("POST", &format!("{base}/{number}/cards"), &hub_api::NewCard { column, reference, note })?;
2353
            if json {
2354
                println!("{}", serde_json::to_string(&card)?);
2355
            } else {
2356
                println!("{} card {} {}", ui::ok("✔"), card.id, if card.reference.is_empty() { &card.title } else { &card.reference });
2357
            }
2358
        }
456f4197 Andy McCall ↶ 2359
        ProjectCmd::Card { cmd: CardCmd::Move { number, card, column, from, except, state, dry_run } } => match (card, from) {
2360
            (Some(card), None) => {
2361
                c.send_text("PATCH", &format!("{base}/{number}/cards/{card}"), &hub_api::CardMove { column: column.clone() })?;
2362
                println!("{} card {card} moved to {column}", ui::ok("✔"));
2363
            }
2364
            (None, Some(from)) => {
2365
                let r: hub_api::CardsMoved = c.send(
2366
                    "POST",
2367
                    &format!("{base}/{number}/cards/move"),
2368
                    &hub_api::CardsMove { from: from.clone(), column: column.clone(), except, state, dry_run },
2369
                )?;
2370
                if json {
2371
                    println!("{}", serde_json::to_string(&r)?);
2372
                    return Ok(0);
2373
                }
2374
                let name = |c: &hub_api::ProjectCard| if c.reference.is_empty() { c.title.clone() } else { c.reference.clone() };
2375
                for m in &r.moved {
2376
                    println!("  {} {}  {}", if dry_run { "would move" } else { "moved" }, name(m), ui::dim(&m.title));
2377
                }
2378
                let verb = if dry_run { "would move" } else { "moved" };
2379
                println!("{} {verb} {} card(s) from {from} to {column}; {} left in {from}", ui::ok("✔"), r.moved.len(), r.kept.len());
2380
            }
2381
            _ => bail!("name a card, or --from COLUMN to move every card of a column"),
2382
        },
439ecd87 Andy McCall ↶ 2383
        ProjectCmd::Card { cmd: CardCmd::Archive { number, from, older, except, state, dry_run } } => {
2384
            let older_days = match older.as_deref().map(|o| o.trim().trim_end_matches('d')) {
2385
                None => None,
2386
                Some(d) => Some(d.parse::<i64>().map_err(|_| anyhow::anyhow!("--older takes days: 14d, or 14"))?),
2387
            };
2388
            let r: hub_api::CardsArchived = c.send(
2389
                "POST",
2390
                &format!("{base}/{number}/cards/archive"),
2391
                &hub_api::CardsArchive { from: from.clone(), older_days, except, state, dry_run },
2392
            )?;
2393
            if json {
2394
                println!("{}", serde_json::to_string(&r)?);
2395
                return Ok(0);
2396
            }
2397
            let verb = if dry_run { "would archive" } else { "archived" };
2398
            for a in &r.archived {
2399
                let name = if a.reference.is_empty() { a.title.clone() } else { a.reference.clone() };
2400
                println!("  {verb} {name}  {}", ui::dim(&a.title));
2401
            }
2402
            println!("{} {verb} {} card(s) from {from}; {} left on the board", ui::ok("✔"), r.archived.len(), r.kept.len());
2403
        }
2404
        ProjectCmd::Card { cmd: CardCmd::Restore { number, card } } => {
2405
            c.send_text("POST", &format!("{base}/{number}/cards/{card}/restore"), &serde_json::json!({}))?;
2406
            println!("{} card {card} restored", ui::ok("✔"));
2407
        }
17a3a84b Andy McCall ↶ 2408
        ProjectCmd::Card { cmd: CardCmd::Remove { number, card } } => {
2409
            c.send_text("DELETE", &format!("{base}/{number}/cards/{card}"), &serde_json::json!({}))?;
2410
            println!("{} card {card} removed", ui::ok("✔"));
5ea4872f Andy McCall ↶ 2411
        }
2412
    }
2413
    Ok(0)
2414
}
2415
2416
fn milestone_line(m: &hub_api::Milestone) -> String {
2417
    let glyph = if m.state == "open" { ui::ok("◆") } else { ui::dim("◇") };
2418
    let due = m.due_ms.map(|d| format!(" · due {}", ui::ago(d))).unwrap_or_default();
2419
    format!("{glyph} {}  {}{}", m.title, ui::dim(&format!("{} open, {} closed", m.open, m.closed)), ui::dim(&due))
2420
}
2421
2422
fn milestone(c: &Client, t: &Target, cmd: MilestoneCmd, json: bool) -> Result<i32> {
2423
    let base = t.repo_path()?;
2424
    let edit = |title: &str, e: hub_api::MilestoneEdit, verb: &str| -> Result<()> {
2425
        let m: hub_api::Milestone = c.send("PATCH", &format!("{base}/milestones/{}", enc(title)), &e)?;
2426
        if json {
2427
            println!("{}", serde_json::to_string(&m)?);
2428
        } else {
2429
            println!("{} {verb} milestone {}", ui::ok("✔"), m.title);
2430
        }
2431
        Ok(())
2432
    };
2433
    match cmd {
2434
        MilestoneCmd::List => {
2435
            let path = format!("{base}/milestones");
2436
            if json {
2437
                println!("{}", c.get_text(&path)?);
2438
                return Ok(0);
2439
            }
2440
            let list: Vec<hub_api::Milestone> = c.get(&path)?;
2441
            if list.is_empty() {
2442
                println!("{}", ui::dim("No milestones."));
2443
            }
2444
            for m in &list {
2445
                println!("{}", milestone_line(m));
2446
            }
2447
        }
2448
        MilestoneCmd::Create { title, description, due } => {
2449
            let m: hub_api::Milestone =
2450
                c.send("POST", &format!("{base}/milestones"), &hub_api::NewMilestone { title, description, due })?;
2451
            if json {
2452
                println!("{}", serde_json::to_string(&m)?);
2453
            } else {
2454
                println!("{} milestone {}", ui::ok("✔"), m.title);
2455
            }
2456
        }
2457
        MilestoneCmd::Edit { title, rename, description, due } => {
2458
            if rename.is_none() && description.is_none() && due.is_none() {
2459
                bail!("say what to change: --rename, --description or --due");
2460
            }
2461
            edit(&title, hub_api::MilestoneEdit { title: rename, description, due, state: None }, "edited")?;
2462
        }
2463
        MilestoneCmd::Close { title } => {
2464
            edit(&title, hub_api::MilestoneEdit { state: Some("closed".into()), ..Default::default() }, "closed")?;
2465
        }
2466
        MilestoneCmd::Reopen { title } => {
2467
            edit(&title, hub_api::MilestoneEdit { state: Some("open".into()), ..Default::default() }, "reopened")?;
ba0a55bb Andy McCall ↶ 2468
        }
2469
    }
2470
    Ok(0)
2471
}
2472
2473
fn tag(c: &Client, t: &Target, cmd: TagCmd, json: bool) -> Result<i32> {
2474
    let base = t.repo_path()?;
2475
    match cmd {
2476
        TagCmd::List => {
2477
            let path = format!("{base}/tags");
2478
            if json {
2479
                println!("{}", c.get_text(&path)?);
2480
                return Ok(0);
2481
            }
2482
            let tags: Vec<Tag> = c.get(&path)?;
2483
            if tags.is_empty() {
2484
                println!("{}", ui::dim("no tags"));
2485
            }
2486
            for t in tags {
2487
                let heads: Vec<&str> = t.heads.iter().map(|h| &h[..h.len().min(12)]).collect();
2488
                let signer = t.signer.map(|s| format!("signed by {s}")).unwrap_or_else(|| "unsigned".into());
2489
                println!("{}  {}  {}", t.name, ui::dim(&heads.join(" ")), ui::dim(&signer));
2490
            }
2491
        }
2492
        TagCmd::Create { name, target, message } => {
2493
            let new = hub_api::NewTag { name, target, message };
2494
            let made: Tag = c.send("POST", &format!("{base}/tags"), &new)?;
2495
            if json {
2496
                println!("{}", serde_json::to_string(&made)?);
2497
            } else {
2498
                println!("{} tagged {} {}", ui::ok("✔"), made.name, ui::dim(&format!("{} head(s)", made.heads.len())));
2499
            }
2500
        }
2501
        TagCmd::Delete { name, reason } => {
2502
            let reason = reason.unwrap_or_default();
2503
            c.send_text("DELETE", &format!("{base}/tags/{}?reason={}", enc(&name), enc(&reason)), &serde_json::json!({}))?;
2504
            if json {
2505
                println!("{}", serde_json::json!({ "withdrawn": name }));
2506
            } else {
2507
                println!("{} withdrew {} {}", ui::ok("✔"), name, ui::dim("(clones drop it on their next fetch)"));
2508
            }
5c6e92fd Andy McCall ↶ 2509
        }
2510
    }
2511
    Ok(0)
2512
}
2513
2514
fn release(c: &Client, t: &Target, cmd: ReleaseCmd, json: bool) -> Result<i32> {
2515
    let base = t.repo_path()?;
2516
    match cmd {
2517
        ReleaseCmd::List => {
2518
            let path = format!("{base}/releases");
2519
            if json {
2520
                println!("{}", c.get_text(&path)?);
2521
                return Ok(0);
2522
            }
2523
            let list: Vec<Release> = c.get(&path)?;
2524
            if list.is_empty() {
2525
                println!("{}", ui::dim("No releases."));
2526
            }
2527
            for r in &list {
2528
                println!(
2529
                    "{} {} {}{}",
2530
                    if r.latest { ui::ok("●") } else { ui::dim("○") },
2531
                    ui::strong(&r.tag),
2532
                    r.title,
2533
                    ui::dim(&format!(
2534
                        " · {} asset{} · {}",
2535
                        r.assets.len(),
2536
                        if r.assets.len() == 1 { "" } else { "s" },
2537
                        ui::ago(r.created_ms)
2538
                    ))
2539
                );
2540
            }
2541
        }
2542
        ReleaseCmd::Create { tag, title, notes, prerelease } => {
2543
            let new = NewRelease { title: title.unwrap_or_else(|| tag.clone()), tag, notes, prerelease };
2544
            let r: Release = c.send("POST", &format!("{base}/releases"), &new)?;
2545
            if json {
2546
                println!("{}", serde_json::to_string(&r)?);
2547
            } else {
2548
                println!("{} released {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
ced6d3af Andy McCall ↶ 2549
            }
2550
        }
2551
        ReleaseCmd::Edit { tag, title, notes, prerelease } => {
2552
            let notes = match notes.as_deref() {
2553
                Some("-") => Some(body_of(None, Some("-".into()))?),
2554
                _ => notes,
2555
            };
2556
            if title.is_none() && notes.is_none() && prerelease.is_none() {
2557
                bail!("say what to change: --title, --notes or --prerelease");
2558
            }
2559
            let edit = hub_api::ReleaseEdit { title, notes, prerelease };
2560
            let r: Release = c.send("PATCH", &format!("{base}/releases/{tag}"), &edit)?;
2561
            if json {
2562
                println!("{}", serde_json::to_string(&r)?);
2563
            } else {
2564
                println!("{} edited {} {}", ui::ok("✔"), r.tag, ui::dim(&r.url));
5c6e92fd Andy McCall ↶ 2565
            }
2566
        }
2567
        ReleaseCmd::Upload { tag, files } => {
2568
            if files.is_empty() {
2569
                bail!("name the files to attach");
2570
            }
2571
            for f in files {
2572
                let name = f.file_name().and_then(|n| n.to_str()).context("a file name")?.to_string();
2573
                let bytes = std::fs::read(&f).with_context(|| format!("read {}", f.display()))?;
2574
                c.upload(&format!("{base}/releases/{}/assets?name={}", enc(&tag), enc(&name)), &bytes)?;
2575
                println!("{} attached {name} to {tag}", ui::ok("✔"));
2576
            }
2577
        }
2578
        ReleaseCmd::Trust { tag } => {
2579
            let path = format!("{base}/releases/trust/{}", enc(&tag));
2580
            if json {
2581
                println!("{}", c.get_text(&path)?);
2582
                return Ok(0);
2583
            }
2584
            let r: serde_json::Value = c.get(&path)?;
2585
            println!("{} {}", ui::strong(&format!("Trust report for {tag}")), ui::dim(&format!("{} changes", r["changes"])));
2586
            let mut worst = 0;
2587
            for ch in r["audit"].as_array().into_iter().flatten() {
2588
                let v = ch["verdict"].as_str().unwrap_or("");
2589
                worst = worst.max(match v {
2590
                    "fail" => 2,
2591
                    "warn" => 1,
2592
                    _ => 0,
2593
                });
2594
                let g = match v {
2595
                    "pass" => ui::ok("✔"),
2596
                    "warn" => ui::warn("!"),
2597
                    _ => ui::bad("✘"),
2598
                };
2599
                println!("{g} {} {}", ch["title"].as_str().unwrap_or(""), ui::dim(ch["detail"].as_str().unwrap_or("")));
2600
            }
2601
            return Ok(if worst == 2 { 1 } else { 0 });
2602
        }
2603
    }
2604
    Ok(0)
166f6e9b Andy McCall 2605
}
2606
2607
#[cfg(test)]
2608
mod tests {
fac6853c Andy McCall ↶ 2609
2610
    #[test]
2611
    fn job_timings_and_report_commands_read_plainly() {
2612
        use clap::Parser;
2613
        let job = hub_api::FlowJob {
2614
            name: "perf".into(),
2615
            status: "passed".into(),
2616
            depends_on: vec![],
2617
            runner: "earth-1".into(),
2618
            exit_code: Some(0),
2619
            error: String::new(),
2620
            started_ms: Some(13_000),
2621
            finished_ms: Some(200_000),
2622
            log_lines: 10,
2623
            waiting: String::new(),
2624
            placed: String::new(),
2625
            approval: String::new(),
2626
            queued_ms: Some(1_000),
2627
            ready_ms: Some(12_500),
2628
            phases: vec![hub_api::FlowPhase { name: "image".into(), ms: 850 }, hub_api::FlowPhase { name: "run".into(), ms: 125_400 }],
2629
            peak_disk_mib: Some(2150),
2630
            peak_memory_mib: Some(900),
2631
        };
2632
        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");
2633
        let bare = hub_api::FlowJob { queued_ms: None, phases: vec![], peak_disk_mib: None, peak_memory_mib: None, ..job };
2634
        assert_eq!(super::timing_line(&bare), "");
2635
        assert_eq!(super::enc_path("data/frame times.csv"), "data/frame%20times.csv");
2636
2637
        let cli =
2638
            super::Cli::try_parse_from(["oh", "run", "report", "26", "performance", "--file", "data/frames.csv", "-o", "f.csv"]).unwrap();
2639
        let super::Cmd::Run { cmd: super::RunCmd::Report { number, job, pick } } = cli.cmd else { panic!("run report") };
2640
        assert_eq!((number, job.as_str(), pick.file.as_deref(), pick.list), (26, "performance", Some("data/frames.csv"), false));
2641
        assert!(super::Cli::try_parse_from(["oh", "run", "report", "26", "perf", "--list", "--file", "x"]).is_err(), "one or the other");
2642
        assert!(super::Cli::try_parse_from(["oh", "run", "report", "26", "perf", "-o", "x"]).is_err(), "-o is for --file");
2643
        let cli = super::Cli::try_parse_from(["oh", "report", "show", "performance", "--bookmark", "main", "--list"]).unwrap();
2644
        assert!(matches!(cli.cmd, super::Cmd::Report { cmd: super::ReportCmd::Show { list: true, .. } }));
2645
        assert!(super::Cli::try_parse_from(["oh", "run", "view", "3", "--timings"]).is_ok());
2646
    }
9bbca80f Andy McCall ↶ 2647
2648
    #[test]
2649
    fn runner_update_scopes_resolve_by_name_or_id() {
2650
        let all = hub_api::RunnerUpdates {
2651
            repo: String::new(),
2652
            settings: vec![],
1ec29691 Andy McCall ↶ 2653
            groups: vec![hub_api::RunnerGroup {
2654
                id: 4,
2655
                owner: "acme".into(),
2656
                name: "canary".into(),
2657
                percent: None,
2658
                members: vec![],
2659
                wave: None,
2660
            }],
9bbca80f Andy McCall ↶ 2661
            runners: vec![],
2662
            holds: vec![],
2663
        };
2664
        assert_eq!(update_scope("site", &all).unwrap(), ("site".to_string(), String::new()));
2665
        assert_eq!(update_scope("owner:acme", &all).unwrap(), ("owner".to_string(), "acme".to_string()));
2666
        for g in ["group:canary", "group:acme/canary", "group:4"] {
2667
            assert_eq!(update_scope(g, &all).unwrap(), ("group".to_string(), "4".to_string()), "{g}");
2668
        }
2669
        assert!(update_scope("runner:plex", &all).unwrap_err().to_string().contains("no runner"));
2670
        assert!(update_scope("everyone", &all).is_err());
2671
        assert_eq!(switch(Some("inherit")).unwrap(), Some(None));
2672
        assert!(switch(Some("yes")).is_err());
2673
    }
166f6e9b Andy McCall 2674
    use super::*;
2675
2676
    /// `oh drop` (oxygenhub#279): its commands and flags parse as the
2677
    /// help says, and a drop is named by its id or its address.
2678
    #[test]
2679
    fn drop_commands_parse() {
2680
        let cli = Cli::try_parse_from(["oh", "drop", "create", "a.txt", "b.md", "--secret", "-d", "Two files", "-t", "Notes"]).unwrap();
2681
        match cli.cmd {
2682
            Cmd::Drop { cmd: DropCmd::Create { files, secret, description, title } } => {
2683
                assert_eq!(files, vec![std::path::PathBuf::from("a.txt"), std::path::PathBuf::from("b.md")]);
2684
                assert!(secret);
2685
                assert_eq!((description.as_deref(), title.as_deref()), (Some("Two files"), Some("Notes")));
2686
            }
2687
            _ => panic!("not drop create"),
2688
        }
2689
        assert!(Cli::try_parse_from(["oh", "drop", "create"]).is_err(), "a drop needs a file");
9bbca80f Andy McCall ↶ 2690
        match Cli::try_parse_from(["oh", "runner-updates", "set", "group:canary", "--updates", "on", "--window", "02-05"]).unwrap() {
2691
            Cli { cmd: Cmd::RunnerUpdates { cmd: Some(RunnerUpdatesCmd::Set { scope, updates, window, channel, dry_run }) }, .. } => {
2692
                assert_eq!((scope.as_str(), updates.as_deref(), window.as_deref()), ("group:canary", Some("on"), Some("02-05")));
2693
                assert!(channel.is_none() && dry_run.is_none());
2694
            }
2695
            _ => panic!("not runner-updates set"),
2696
        }
2697
        assert!(matches!(Cli::try_parse_from(["oh", "runner-updates"]).unwrap().cmd, Cmd::RunnerUpdates { cmd: None }));
166f6e9b Andy McCall 2698
        match Cli::try_parse_from(["oh", "drop", "list", "--user", "bob", "--json"]).unwrap() {
2699
            Cli { cmd: Cmd::Drop { cmd: DropCmd::List { user } }, json, .. } => assert_eq!((user.as_deref(), json), (Some("bob"), true)),
2700
            _ => panic!("not drop list"),
2701
        }
2702
        match Cli::try_parse_from(["oh", "drop", "view", "0123456789abcdef01234567", "-f", "a.txt"]).unwrap().cmd {
2703
            Cmd::Drop { cmd: DropCmd::View { id, file } } => {
2704
                assert_eq!((id.as_str(), file.as_deref()), ("0123456789abcdef01234567", Some("a.txt")))
2705
            }
2706
            _ => panic!("not drop view"),
2707
        }
2708
        assert!(matches!(Cli::try_parse_from(["oh", "drop", "delete", "x"]).unwrap().cmd, Cmd::Drop { cmd: DropCmd::Delete { .. } }));
04f9c984 Andy McCall ↶ 2709
        for (verb, ok) in [("fork", true), ("star", true), ("unstar", true), ("comments", true)] {
2710
            assert_eq!(Cli::try_parse_from(["oh", "drop", verb, "x"]).is_ok(), ok, "{verb}");
2711
        }
2712
        assert!(Cli::try_parse_from(["oh", "drop", "comment", "x"]).is_err(), "a comment says something");
2713
        match Cli::try_parse_from(["oh", "drop", "comment", "x", "-m", "Nice"]).unwrap().cmd {
2714
            Cmd::Drop { cmd: DropCmd::Comment { message, .. } } => assert_eq!(message, "Nice"),
2715
            _ => panic!("not drop comment"),
2716
        }
166f6e9b Andy McCall 2717
        assert_eq!(drop_id("0123456789ABCDEF01234567").unwrap(), "0123456789abcdef01234567");
2718
        assert_eq!(drop_id("https://hub.example/andy/drops/0123456789abcdef01234567/").unwrap(), "0123456789abcdef01234567");
2719
        assert!(drop_id("andy/notes").is_err());
2720
    }
5c6e92fd Andy McCall ↶ 2721
}