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