aboutsummaryrefslogtreecommitdiffstats
path: root/fatcat-cli/src/main.rs
blob: 1d5172960e999496e78d97acfac9a8b6718c0c25 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
use crate::{path_or_stdin, BatchGrouper, BatchOp};
use anyhow::{anyhow, Context, Result};
use colored_json::to_colored_json_auto;
use fatcat_cli::*;
#[allow(unused_imports)]
use log::{self, debug, info};
use std::io::Write;
use std::path::PathBuf;
use structopt::StructOpt;
use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor};

#[derive(StructOpt)]
#[structopt(rename_all = "kebab-case", about = "CLI interface to Fatcat API")]
struct Opt {
    #[structopt(
        global = true,
        long = "--api-host",
        env = "FATCAT_API_HOST",
        default_value = "https://api.fatcat.wiki"
    )]
    api_host: String,

    // API auth tokens can be generated from the account page in the fatcat.wiki web interface
    #[structopt(
        global = true,
        long = "--api-token",
        env = "FATCAT_API_AUTH_TOKEN",
        hide_env_values = true
    )]
    api_token: Option<String>,

    #[structopt(
        global = true,
        long = "--search-host",
        env = "FATCAT_SEARCH_HOST",
        default_value = "https://search.fatcat.wiki"
    )]
    search_host: String,

    /// Log more messages. Pass multiple times for ever more verbosity
    ///
    /// By default, it'll only report errors. Passing `-v` one time also prints
    /// warnings, `-vv` enables info logging, `-vvv` debug, and `-vvvv` trace.
    #[structopt(global = true, long, short = "v", parse(from_occurrences))]
    verbose: i8,

    #[structopt(long = "--shell-completions", hidden = true)]
    shell_completions: Option<structopt::clap::Shell>,

    #[structopt(long = "--meow", hidden = true)]
    meow: bool,

    #[structopt(subcommand)]
    cmd: Command,
}

#[derive(StructOpt)]
enum EditgroupsCommand {
    /// Create a new editgroup
    Create {
        #[structopt(long, short)]
        description: String,
    },
    /// Print editgroups for current user
    List {
        #[structopt(long = "--editor-id", short)]
        editor_id: Option<String>,

        #[structopt(long, short = "-n", default_value = "20")]
        limit: i64,

        #[structopt(long)]
        json: bool,
    },
    /// Print recent editgroups from any user which need review
    Reviewable {
        #[structopt(long, short = "-n", default_value = "20")]
        limit: i64,

        #[structopt(long)]
        json: bool,
    },
    /// Accept (merge) a single editgroup
    Accept {
        #[structopt(env = "FATCAT_EDITGROUP", hide_env_values = true)]
        editgroup_id: EditgroupSpecifier,
    },
    /// Submit a single editgroup for review
    Submit {
        #[structopt(env = "FATCAT_EDITGROUP", hide_env_values = true)]
        editgroup_id: EditgroupSpecifier,
    },
    /// Un-submit a single editgroup (for more editing)
    Unsubmit {
        #[structopt(env = "FATCAT_EDITGROUP", hide_env_values = true)]
        editgroup_id: EditgroupSpecifier,
    },
}

#[derive(StructOpt)]
enum BatchCommand {
    /// Create new entities in batches
    Create {
        entity_type: EntityType,

        #[structopt(long, default_value = "50", global = true)]
        batch_size: u64,

        #[structopt(long, global = true)]
        auto_accept: bool,

        /// Editgroup description
        #[structopt(long, short)]
        description: Option<String>,
    },

    /// Update existing entities in batches
    Update {
        entity_type: EntityType,
        mutations: Vec<Mutation>,

        #[structopt(long, default_value = "50")]
        batch_size: u64,

        #[structopt(long)]
        auto_accept: bool,

        /// Editgroup description
        #[structopt(long, short)]
        description: Option<String>,
    },

    /// Delete entities in batches
    Delete {
        entity_type: EntityType,

        #[structopt(long, default_value = "50")]
        batch_size: u64,

        #[structopt(long)]
        auto_accept: bool,

        /// Editgroup description
        #[structopt(long, short)]
        description: Option<String>,
    },

    /// Download multiple files
    Download {
        #[structopt(long, short = "-o", parse(from_os_str))]
        output_dir: Option<PathBuf>,

        #[structopt(long, short = "-j", default_value = "1")]
        jobs: u64,
    },
}

#[derive(StructOpt)]
enum Command {
    /// Fetch a single entity, by "ident" or external identifier
    Get {
        specifier: Specifier,

        #[structopt(long = "--expand")]
        expand: Option<String>,

        #[structopt(long = "--hide")]
        hide: Option<String>,

        #[allow(dead_code)]
        #[structopt(long)]
        json: bool,

        #[structopt(long)]
        toml: bool,
    },

    /// Create a single new entity, from a file, in an existing editgroup
    Create {
        entity_type: EntityType,

        /// Input file, "-" for stdin.
        #[structopt(long = "--input-file", short = "-i", parse(from_os_str))]
        input_path: Option<PathBuf>,

        #[structopt(
            long = "--editgroup-id",
            short,
            env = "FATCAT_EDITGROUP",
            hide_env_values = true
        )]
        editgroup_id: EditgroupSpecifier,
    },

    /// Update an existing editgroup, either from file or updating specified fields
    Update {
        specifier: Specifier,

        /// Input file, "-" for stdin.
        #[structopt(long = "--input-file", short = "-i", parse(from_os_str))]
        input_path: Option<PathBuf>,

        #[structopt(
            long = "--editgroup-id",
            short,
            env = "FATCAT_EDITGROUP",
            hide_env_values = true
        )]
        editgroup_id: EditgroupSpecifier,

        mutations: Vec<Mutation>,
    },

    /// Delete a single entity
    Delete {
        specifier: Specifier,

        #[structopt(
            long = "--editgroup-id",
            short,
            env = "FATCAT_EDITGROUP",
            hide_env_values = true
        )]
        editgroup_id: EditgroupSpecifier,
    },

    /// Use a text editor to update entity; fetches and uploads automatically
    Edit {
        specifier: Specifier,

        #[structopt(
            long = "--editgroup-id",
            short,
            env = "FATCAT_EDITGROUP",
            hide_env_values = true
        )]
        editgroup_id: EditgroupSpecifier,

        #[structopt(long)]
        json: bool,

        #[allow(dead_code)]
        #[structopt(long)]
        toml: bool,

        #[structopt(long = "--editing-command", env = "EDITOR")]
        editing_command: String,
    },

    /// Fetch full-text file corresponding to an entity
    Download {
        specifier: Specifier,

        #[structopt(long = "--output-dir", short = "-o", parse(from_os_str))]
        output_path: Option<PathBuf>,
    },

    /// List edit history for a single entity
    History {
        specifier: Specifier,

        #[structopt(long, short = "-n", default_value = "100")]
        limit: u64,

        #[structopt(long)]
        json: bool,
    },

    /// Query catalog index
    Search {
        entity_type: SearchEntityType,

        query: Vec<String>,

        #[structopt(long = "--expand")]
        expand: Option<String>,

        #[structopt(long = "--hide")]
        hide: Option<String>,

        #[structopt(long = "--count")]
        count: bool,

        #[structopt(long, short = "-n", default_value = "20")]
        limit: i64,

        #[structopt(long = "--entity-json")]
        entity_json: bool,

        #[structopt(long = "--index-json")]
        index_json: bool,
    },

    /// Sub-commands for managing editgroups
    Editgroups {
        #[structopt(subcommand)]
        cmd: EditgroupsCommand,
    },

    /// List recent accepted edits to the catalog
    Changelog {
        #[structopt(long, short = "-n", default_value = "20")]
        limit: i64,

        /* TODO: follow (streaming) mode for changelog
        #[structopt(long, short = "-f")]
        follow: bool,
        */
        #[structopt(long)]
        json: bool,
    },

    /// Operations on multiple entities
    Batch {
        #[structopt(subcommand)]
        cmd: BatchCommand,

        /// Input file, "-" for stdin.
        #[structopt(long = "--input-file", short = "-i", parse(from_os_str))]
        input_path: Option<PathBuf>,

        #[structopt(long, short = "-n")]
        limit: Option<u64>,
    },

    /// Summarize connection and authentication with API
    Status {
        #[structopt(long)]
        json: bool,
    },
}

fn main() -> Result<()> {
    let opt = Opt::from_args();

    let log_level = match opt.verbose {
        std::i8::MIN..=-1 => "none",
        0 => "error",
        1 => "warn",
        2 => "info",
        3 => "debug",
        4..=std::i8::MAX => "trace",
    };
    // hyper logging is very verbose, so crank that down even if everything else is more verbose
    let log_filter = format!("{},hyper=error", log_level);
    env_logger::Builder::from_env(env_logger::Env::default().default_filter_or(log_filter))
        .format_timestamp(None)
        .init();

    debug!("Args parsed, starting up");

    #[cfg(windows)]
    colored_json::enable_ansi_support();

    if let Some(shell) = opt.shell_completions {
        Opt::clap().gen_completions_to("fatcat-cli", shell, &mut std::io::stdout());
        std::process::exit(0);
    }
    if opt.meow {
        println!("meow meow");
        std::process::exit(0);
    }

    if let Err(err) = run(opt) {
        // Be graceful about some errors
        if let Some(io_err) = err.root_cause().downcast_ref::<std::io::Error>() {
            if let std::io::ErrorKind::BrokenPipe = io_err.kind() {
                // presumably due to something like writing to stdout and piped to `head -n10` and
                // stdout was closed
                debug!("got BrokenPipe error, assuming stdout closed as expected and exiting with success");
                std::process::exit(0);
            }
        }
        let mut color_stderr = StandardStream::stderr(if atty::is(atty::Stream::Stderr) {
            ColorChoice::Auto
        } else {
            ColorChoice::Never
        });
        color_stderr.set_color(ColorSpec::new().set_fg(Some(Color::Red)).set_bold(true))?;
        eprintln!("Error: {:?}", err);
        color_stderr.set_color(&ColorSpec::new())?;
        std::process::exit(1);
    }
    Ok(())
}

fn run(opt: Opt) -> Result<()> {
    let mut api_client = FatcatApiClient::new(opt.api_host.clone(), opt.api_token.clone())?;

    match opt.cmd {
        Command::Get {
            specifier,
            expand,
            hide,
            json: _,
            toml,
        } => {
            let result = specifier.get_from_api(&mut api_client, expand, hide)?;
            if toml {
                writeln!(&mut std::io::stdout(), "{}", result.to_toml_string()?)?
            } else {
                // "if json"
                writeln!(
                    &mut std::io::stdout(),
                    "{}",
                    to_colored_json_auto(&result.to_json_value()?)?
                )?
            }
        }
        Command::Create {
            entity_type,
            input_path,
            editgroup_id,
        } => {
            let json_str = read_entity_file(input_path)?;
            let ee = api_client.create_entity_from_json(
                entity_type,
                &json_str,
                editgroup_id.into_string(),
            )?;
            writeln!(
                &mut std::io::stdout(),
                "{}",
                to_colored_json_auto(&serde_json::to_value(&ee)?)?
            )?
        }
        Command::Update {
            specifier,
            input_path,
            editgroup_id,
            mutations,
        } => {
            let (json_str, exact_specifier): (String, Specifier) =
                match (&input_path, mutations.len()) {
                    // input path or no mutations: read from path or stdin
                    (Some(_), _) | (None, 0) => (
                        read_entity_file(input_path)?,
                        specifier.into_entity_specifier(&mut api_client)?,
                    ),
                    // no input path *and* mutations: fetch from API
                    (None, _) => {
                        let mut entity = specifier.get_from_api(&mut api_client, None, None)?;
                        entity.mutate(mutations)?;
                        (entity.to_json_string()?, entity.specifier())
                    }
                };
            let ee = api_client.update_entity_from_json(
                exact_specifier,
                &json_str,
                editgroup_id.into_string(),
            )?;
            writeln!(
                &mut std::io::stdout(),
                "{}",
                to_colored_json_auto(&serde_json::to_value(&ee)?)?
            )?
        }
        Command::Edit {
            specifier,
            editgroup_id,
            json,
            toml: _,
            editing_command,
        } => {
            let ee = edit_entity_locally(
                &mut api_client,
                specifier,
                editgroup_id.into_string(),
                json,
                editing_command,
            )?;
            writeln!(
                &mut std::io::stdout(),
                "{}",
                to_colored_json_auto(&serde_json::to_value(&ee)?)?
            )?
        }
        Command::Changelog { limit, json } => {
            let resp = api_client
                .rt
                .block_on(api_client.api.get_changelog(Some(limit)))
                .context("fetch recent changelogs")?;
            match resp {
                fatcat_openapi::GetChangelogResponse::Success(change_list) => {
                    print_changelog_entries(change_list, json)?;
                }
                other => {
                    return Err(anyhow!("{:?}", other))
                        .with_context(|| "failed to fetch changelogs".to_string())
                }
            }
        }
        Command::Batch {
            cmd:
                BatchCommand::Create {
                    entity_type,
                    batch_size,
                    auto_accept,
                    description,
                },
            input_path,
            limit,
        } => {
            let input_path = path_or_stdin(input_path);
            let mut batch =
                BatchGrouper::new(entity_type, batch_size, limit, auto_accept, description);
            batch.run(&mut api_client, input_path, BatchOp::Create, None)?;
        }
        Command::Batch {
            cmd:
                BatchCommand::Update {
                    entity_type,
                    mutations,
                    batch_size,
                    auto_accept,
                    description,
                },
            input_path,
            limit,
        } => {
            let input_path = path_or_stdin(input_path);
            let mut batch =
                BatchGrouper::new(entity_type, batch_size, limit, auto_accept, description);
            batch.run(
                &mut api_client,
                input_path,
                BatchOp::Update,
                Some(mutations),
            )?;
        }
        Command::Batch {
            cmd:
                BatchCommand::Delete {
                    entity_type,
                    batch_size,
                    auto_accept,
                    description,
                },
            input_path,
            limit,
        } => {
            let input_path = path_or_stdin(input_path);
            let mut batch =
                BatchGrouper::new(entity_type, batch_size, limit, auto_accept, description);
            batch.run(&mut api_client, input_path, BatchOp::Delete, None)?;
        }
        Command::Batch {
            cmd: BatchCommand::Download { jobs, output_dir },
            input_path,
            limit,
        } => {
            let input_path = path_or_stdin(input_path);
            if let Some(ref dir) = output_dir {
                if !dir.is_dir() {
                    return Err(anyhow!("output directory doesn't exist"));
                }
            }
            if jobs == 0 {
                return Err(anyhow!("--jobs=0 not implemented"));
            }
            if jobs > 12 {
                return Err(anyhow!(
                    "please don't download more than 12 parallel requests"
                ));
            }
            download_batch(input_path, output_dir, limit, jobs)?;
        }
        Command::Download {
            specifier,
            output_path,
        } => {
            // run lookups if necessary (inefficient)
            let specifier = match specifier {
                Specifier::ReleaseLookup(_, _) | Specifier::FileLookup(_, _) => {
                    specifier.into_entity_specifier(&mut api_client)?
                }
                _ => specifier,
            };
            if let Some(ref path) = output_path {
                if path.exists() {
                    return Err(anyhow!("refusing to over-write output file"));
                }
            }
            let status = match specifier {
                Specifier::Release(ident) => {
                    let result = api_client.rt.block_on(api_client.api.get_release(
                        ident.clone(),
                        Some("files".to_string()),
                        Some("abstracts,refs".to_string()),
                    ))?;
                    let release_entity = match result {
                        fatcat_openapi::GetReleaseResponse::FoundEntity(model) => Ok(model),
                        resp => Err(anyhow!("{:?}", resp))
                            .with_context(|| format!("API GET failed: {:?}", ident)),
                    }?;
                    download_release(&release_entity, output_path, true)
                }
                Specifier::File(ident) => {
                    let result = api_client.rt.block_on(api_client.api.get_file(
                        ident.clone(),
                        None,
                        None,
                    ))?;
                    let file_entity = match result {
                        fatcat_openapi::GetFileResponse::FoundEntity(model) => Ok(model),
                        resp => Err(anyhow!("{:?}", resp))
                            .with_context(|| format!("API GET failed: {:?}", ident)),
                    }?;
                    download_file(&file_entity, &file_entity.specifier(), output_path, true)
                }
                other => Err(anyhow!("Don't know how to download: {:?}", other)),
            }?;
            if let Some(detail) = status.details() {
                println!("{}: {}", status, detail);
            } else {
                println!("{}", status);
            }
        }
        Command::Search {
            entity_type,
            query,
            limit,
            count,
            entity_json,
            index_json,
            expand,
            hide,
        } => {
            let limit: Option<u64> = match (count, limit) {
                (true, _) => Some(0),
                (false, l) if l <= 0 => None,
                (false, l) => Some(l as u64),
            };
            let results = fatcat_cli::crude_search(&opt.search_host, entity_type, limit, query)
                .with_context(|| format!("searching for {:?}", entity_type))?;
            if count {
                println!("{}", results.count);
            } else {
                eprintln!("Got {} hits in {}ms", results.count, results.took_ms);
                if !(index_json || entity_json) {
                    print_search_table(results, entity_type)?;
                } else {
                    for hit in results {
                        let hit = hit?;
                        match (index_json, entity_json, entity_type) {
                            (false, false, _) => unreachable!("case handled above"),
                            (true, _, _) => writeln!(&mut std::io::stdout(), "{}", hit)?,
                            (false, true, SearchEntityType::Release) => {
                                let specifier =
                                    Specifier::Release(hit["ident"].as_str().unwrap().to_string());
                                let entity = specifier.get_from_api(
                                    &mut api_client,
                                    expand.clone(),
                                    hide.clone(),
                                )?;
                                writeln!(&mut std::io::stdout(), "{}", entity.to_json_string()?)?
                            }
                            (false, true, SearchEntityType::Container) => {
                                let specifier = Specifier::Container(
                                    hit["ident"].as_str().unwrap().to_string(),
                                );
                                let entity = specifier.get_from_api(
                                    &mut api_client,
                                    expand.clone(),
                                    hide.clone(),
                                )?;
                                writeln!(&mut std::io::stdout(), "{}", entity.to_json_string()?)?
                            }
                            (false, true, SearchEntityType::File) => {
                                let specifier =
                                    Specifier::File(hit["ident"].as_str().unwrap().to_string());
                                let entity = specifier.get_from_api(
                                    &mut api_client,
                                    expand.clone(),
                                    hide.clone(),
                                )?;
                                writeln!(&mut std::io::stdout(), "{}", entity.to_json_string()?)?
                            }
                            (false, true, SearchEntityType::Scholar) => {
                                if !hit["biblio"]["release_ident"].is_string() {
                                    continue;
                                }
                                let specifier = Specifier::Release(
                                    hit["biblio"]["release_ident"].as_str().unwrap().to_string(),
                                );
                                let entity = specifier.get_from_api(
                                    &mut api_client,
                                    expand.clone(),
                                    hide.clone(),
                                )?;
                                writeln!(&mut std::io::stdout(), "{}", entity.to_json_string()?)?
                            }
                            (false, true, SearchEntityType::Reference) => {
                                return Err(anyhow!(
                                    "entity schema output not supported for references index"
                                ));
                            }
                            (false, true, SearchEntityType::ReferenceIn) => {
                                if !hit["source_release_ident"].is_string() {
                                    continue;
                                }
                                let specifier = Specifier::Release(
                                    hit["source_release_ident"].as_str().unwrap().to_string(),
                                );
                                let entity = specifier.get_from_api(
                                    &mut api_client,
                                    expand.clone(),
                                    hide.clone(),
                                )?;
                                writeln!(&mut std::io::stdout(), "{}", entity.to_json_string()?)?
                            }
                            (false, true, SearchEntityType::ReferenceOut) => {
                                if !hit["target_release_ident"].is_string() {
                                    continue;
                                }
                                let specifier = Specifier::Release(
                                    hit["target_release_ident"].as_str().unwrap().to_string(),
                                );
                                let entity = specifier.get_from_api(
                                    &mut api_client,
                                    expand.clone(),
                                    hide.clone(),
                                )?;
                                writeln!(&mut std::io::stdout(), "{}", entity.to_json_string()?)?
                            }
                        }
                    }
                }
            }
        }
        Command::Delete {
            specifier,
            editgroup_id,
        } => {
            let result = api_client
                .delete_entity(specifier.clone(), editgroup_id.into_string())
                .with_context(|| format!("delete entity: {:?}", specifier))?;
            println!("{}", serde_json::to_string(&result)?);
        }
        Command::History {
            specifier,
            limit,
            json,
        } => {
            let specifier = specifier.into_entity_specifier(&mut api_client)?;
            let history_entries = specifier.get_history(&mut api_client, Some(limit))?;
            print_entity_histories(history_entries, json)?;
        }
        Command::Editgroups {
            cmd:
                EditgroupsCommand::List {
                    editor_id,
                    limit,
                    json,
                },
        } => {
            let editor_id = match editor_id.or(api_client.editor_id) {
                Some(eid) => eid,
                None => return Err(anyhow!("require either working auth token or --editor-id")),
            };
            let result = api_client
                .rt
                .block_on(api_client.api.get_editor_editgroups(
                    editor_id.clone(),
                    Some(limit),
                    None,
                    None,
                ))
                .context("fetch editgroups")?;
            match result {
                fatcat_openapi::GetEditorEditgroupsResponse::Found(eg_list) => {
                    print_editgroups(eg_list, json)?;
                }
                other => {
                    return Err(anyhow!("{:?}", other)).with_context(|| {
                        format!("failed to fetch editgroups for editor_{}", editor_id)
                    })
                }
            }
        }
        Command::Editgroups {
            cmd: EditgroupsCommand::Reviewable { limit, json },
        } => {
            let result = api_client
                .rt
                .block_on(api_client.api.get_editgroups_reviewable(
                    Some("editors".to_string()),
                    Some(limit),
                    None,
                    None,
                ))
                .context("fetch reviewable editgroups")?;
            match result {
                fatcat_openapi::GetEditgroupsReviewableResponse::Found(eg_list) => {
                    print_editgroups(eg_list, json)?;
                }
                other => {
                    return Err(anyhow!("{:?}", other))
                        .context("failed to fetch reviewable editgroups")
                }
            }
        }
        Command::Editgroups {
            cmd: EditgroupsCommand::Create { description },
        } => {
            let eg = api_client.create_editgroup(Some(description))?;
            writeln!(
                &mut std::io::stdout(),
                "{}",
                to_colored_json_auto(&serde_json::to_value(&eg)?)?
            )?
        }
        Command::Editgroups {
            cmd: EditgroupsCommand::Accept { editgroup_id },
        } => {
            let msg = api_client.accept_editgroup(editgroup_id.into_string())?;
            writeln!(
                &mut std::io::stdout(),
                "{}",
                to_colored_json_auto(&serde_json::to_value(&msg)?)?
            )?
        }
        Command::Editgroups {
            cmd: EditgroupsCommand::Submit { editgroup_id },
        } => {
            let msg = api_client.update_editgroup_submit(editgroup_id.into_string(), true)?;
            writeln!(
                &mut std::io::stdout(),
                "{}",
                to_colored_json_auto(&serde_json::to_value(&msg)?)?
            )?
        }
        Command::Editgroups {
            cmd: EditgroupsCommand::Unsubmit { editgroup_id },
        } => {
            let msg = api_client.update_editgroup_submit(editgroup_id.into_string(), false)?;
            writeln!(
                &mut std::io::stdout(),
                "{}",
                to_colored_json_auto(&serde_json::to_value(&msg)?)?
            )?
        }
        Command::Status { json } => {
            let status = ClientStatus::generate(&mut api_client)?;
            if json {
                println!("{}", serde_json::to_string(&status)?)
            } else {
                status.pretty_print()?;
            }
        }
    }
    Ok(())
}