aboutsummaryrefslogtreecommitdiffstats
path: root/rust/fatcat-cli/src/main.rs
blob: 046a8256ecad0846f778cf282e9af8e44324ffca (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
use anyhow::{anyhow, Context, Result};
use fatcat_cli::ApiModelSer;
use fatcat_cli::*;
use fatcat_openapi::models;
#[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(
        long = "--api-host",
        env = "FATCAT_API_HOST",
        default_value = "https://api.fatcat.wiki"
    )]
    api_host: String,

    #[structopt(
        long = "--api-token",
        env = "FATCAT_API_AUTH_TOKEN",
        hide_env_values = true
    )]
    api_token: Option<String>,

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

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

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

#[derive(StructOpt)]
enum EditgroupCommand {
    Create {
        #[structopt(long, short)]
        description: String,
    },
    List {
        #[structopt(long = "--editor-id", short)]
        editor_id: Option<String>,

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

        #[structopt(long)]
        json: bool,
    },
    Reviewable {
        #[structopt(long, short = "-n", default_value = "20")]
        limit: i64,

        #[structopt(long)]
        json: bool,
    },
    Accept {
        #[structopt(env = "FATCAT_EDITGROUP", hide_env_values = true)]
        editgroup_id: String,
    },
    Submit {
        #[structopt(env = "FATCAT_EDITGROUP", hide_env_values = true)]
        editgroup_id: String,
    },
    Unsubmit {
        #[structopt(env = "FATCAT_EDITGROUP", hide_env_values = true)]
        editgroup_id: String,
    },
}

#[derive(StructOpt)]
enum Command {
    Status {
        #[structopt(long)]
        json: bool,
    },
    Get {
        specifier: Specifier,

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

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

        #[structopt(long)]
        toml: bool,
    },
    Create {
        entity_type: EntityType,

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

        #[structopt(
            long = "--editgroup-id",
            short,
            env = "FATCAT_EDITGROUP",
            hide_env_values = true
        )]
        editgroup_id: String,
    },
    Update {
        specifier: Specifier,

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

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

        mutations: Vec<Mutation>,
    },
    Edit {
        specifier: Specifier,

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

        #[structopt(long)]
        json: bool,

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

        #[structopt(
            long = "--editgroup-id",
            short,
            env = "FATCAT_EDITGROUP",
            hide_env_values = true
        )]
        editgroup_id: String,
    },
    Editgroup {
        #[structopt(subcommand)]
        cmd: EditgroupCommand,
    },
    //Changelog
    //Download
    //History
    Search {
        entity_type: EntityType,

        terms: Vec<String>,

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

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

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

        #[structopt(long = "--search-schema")]
        search_schema: 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::from_env(env_logger::Env::default().default_filter_or(log_filter))
        .format_timestamp(None)
        .init();

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

    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 {
            toml,
            specifier,
            expand,
            hide,
        } => {
            let result = specifier.get_from_api(&mut api_client, expand, hide)?;
            if toml {
                writeln!(&mut std::io::stdout(), "{}", result.to_toml_string()?)?
            } else {
                writeln!(&mut std::io::stdout(), "{}", result.to_json_string()?)?
            }
        }
        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)?;
            println!("{}", serde_json::to_string(&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)?;
            println!("{}", serde_json::to_string(&ee)?);
        }
        Command::Edit {
            specifier,
            editgroup_id,
            json,
            editing_command,
        } => {
            // TODO: fetch editgroup, check if this entity is already being updated in it. If so,
            // need to fetch that revision, do the edit, parse that synatx is good, then delete the
            // existing edit and update with the new one.
            let original_entity = specifier.get_from_api(&mut api_client, None, None)?;
            let exact_specifier = original_entity.specifier();
            let tmp_file = tempfile::Builder::new()
                .suffix(if json { ".json" } else { ".toml" })
                .tempfile()?;
            if json {
                writeln!(&tmp_file, "{}", original_entity.to_json_string()?)?
            } else {
                writeln!(&tmp_file, "{}", original_entity.to_toml_string()?)?
            }
            let mut editor_cmd = std::process::Command::new(&editing_command)
                .arg(tmp_file.path())
                .spawn()
                .expect("failed to execute process");
            let cmd_status = editor_cmd.wait()?;
            if !cmd_status.success() {
                return Err(anyhow!(
                    "editor ({}) exited with non-success status code ({}), bailing on edit",
                    editing_command,
                    cmd_status
                        .code()
                        .map(|v| v.to_string())
                        .unwrap_or_else(|| "N/A".to_string())
                ));
            };
            let json_str = read_entity_file(Some(tmp_file.path().to_path_buf()))?;
            // for whatever reason api_client's TCP connection is broken after spawning, so try a
            // dummy call, expected to fail, but connection should re-establish after this
            specifier
                .get_from_api(&mut api_client, None, None)
                .context("re-fetch")
                .ok();
            let ee = api_client
                .update_entity_from_json(exact_specifier, &json_str, editgroup_id)
                .context("updating after edit")?;
            println!("{}", serde_json::to_string(&ee)?);
        }
        Command::Search {
            entity_type,
            terms,
            limit,
            search_schema,
            expand,
            hide,
        } => {
            let limit: Option<u64> = match limit {
                l if l < 0 => None,
                l => Some(l as u64),
            };
            let results = fatcat_cli::crude_search(&opt.search_host, entity_type, limit, terms)
                .with_context(|| format!("searching for {:?}", entity_type))?;
            eprintln!("Got {} hits in {}ms", results.count, results.took_ms);
            for hit in results {
                let hit = hit?;
                match (search_schema, entity_type) {
                    (true, _) => writeln!(&mut std::io::stdout(), "{}", hit.to_string())?,
                    (false, EntityType::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, _) => unimplemented!("searching other entity types"),
                }
            }
        }
        Command::Delete {
            specifier,
            editgroup_id,
        } => {
            let result = api_client
                .delete_entity(specifier.clone(), editgroup_id)
                .with_context(|| format!("delete entity: {:?}", specifier))?;
            println!("{}", serde_json::to_string(&result)?);
        }
        Command::Editgroup {
            cmd:
                EditgroupCommand::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::Editgroup {
            cmd: EditgroupCommand::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::Editgroup {
            cmd: EditgroupCommand::Create { description },
        } => {
            let mut eg = models::Editgroup::new();
            eg.description = Some(description);
            eg.extra = Some({
                let mut extra = std::collections::HashMap::new();
                extra.insert(
                    "agent".to_string(),
                    serde_json::Value::String("fatcat-cli".to_string()),
                );
                extra
            });
            let result = api_client
                .rt
                .block_on(api_client.api.create_editgroup(eg))?;
            match result {
                fatcat_openapi::CreateEditgroupResponse::SuccessfullyCreated(eg) => {
                    println!("{}", serde_json::to_string(&eg)?)
                }
                other => return Err(anyhow!("{:?}", other)).context("failed to create editgroup"),
            }
        }
        Command::Editgroup {
            cmd: EditgroupCommand::Accept { editgroup_id },
        } => {
            let result = api_client
                .rt
                .block_on(api_client.api.accept_editgroup(editgroup_id.clone()))
                .context("accept editgroup")?;
            match result {
                fatcat_openapi::AcceptEditgroupResponse::MergedSuccessfully(msg) => {
                    println!("{}", serde_json::to_string(&msg)?)
                }
                other => {
                    return Err(anyhow!(
                        "failed to accept editgroup {}: {:?}",
                        editgroup_id,
                        other
                    ))
                }
            }
        }
        Command::Editgroup {
            cmd: EditgroupCommand::Submit { editgroup_id },
        } => {
            let eg = api_client.update_editgroup_submit(editgroup_id, true)?;
            println!("{}", eg.to_json_string()?);
        }
        Command::Editgroup {
            cmd: EditgroupCommand::Unsubmit { editgroup_id },
        } => {
            let eg = api_client.update_editgroup_submit(editgroup_id, false)?;
            println!("{}", eg.to_json_string()?);
        }
        Command::Status { json } => {
            let status = api_client.status()?;
            if json {
                println!("{}", serde_json::to_string(&status)?)
            } else {
                status.pretty_print()?;
            }
        }
    }
    Ok(())
}