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