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