asimov_cli/commands/
fetch.rs

1// This is free and unencumbered software released into the public domain.
2
3use crate::{
4    StandardOptions,
5    SysexitsError::{self, *},
6    commands::External,
7    shared::{build_resolver, normalize_url},
8};
9use color_print::ceprintln;
10use miette::Result;
11
12pub fn fetch(
13    urls: &Vec<String>,
14    module: Option<&str>,
15    output: Option<&str>,
16    flags: &StandardOptions,
17) -> Result<(), SysexitsError> {
18    let resolver = build_resolver("fetcher").map_err(|e| {
19        ceprintln!("<s,r>error:</> failed to build a resolver: {e}");
20        EX_UNAVAILABLE
21    })?;
22
23    for url in urls {
24        if flags.verbose > 1 {
25            ceprintln!("<s><c>»</></> Fetching `{}`...", url);
26        }
27
28        let url = normalize_url(url);
29
30        let modules = resolver.resolve(&url)?;
31
32        let module = if let Some(want) = module {
33            modules.iter().find(|m| m.name == want).ok_or_else(|| {
34                ceprintln!("<s,r>error:</> failed to find a module named `{want}` that supports fetching the URL: `{url}`");
35                EX_SOFTWARE
36            })?
37        } else {
38            modules.first().ok_or_else(|| {
39                ceprintln!("<s,r>error:</> failed to find a module to fetch the URL: `{url}`");
40                EX_SOFTWARE
41            })?
42        };
43
44        let subcommand = format!("{}-fetcher", module.name);
45
46        let cmd = External {
47            is_debug: flags.debug,
48            pipe_output: false,
49        };
50
51        let mut args = vec![];
52        if let Some(output) = output {
53            args.push(format!("--output={}", output));
54        }
55        args.push(url.to_owned());
56
57        let code = cmd.execute(&subcommand, args).map(|result| result.code)?;
58        if code.is_failure() {
59            return Err(code);
60        }
61
62        if flags.verbose > 0 {
63            ceprintln!("<s><g>✓</></> Fetched `{}`.", url);
64        }
65    }
66
67    Ok(())
68}