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