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