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