alpm_mtree/
commands.rs

1use std::{
2    io::{self, IsTerminal},
3    path::PathBuf,
4};
5
6use alpm_common::MetadataFile;
7
8use crate::{Error, Mtree, MtreeSchema, cli::OutputFormat};
9
10/// A small wrapper around the parsing of an MTREE file that simply ensures that there were no
11/// errors.
12///
13/// For all possible errors, check the [parse] function.
14pub fn validate(file: Option<&PathBuf>, schema: Option<MtreeSchema>) -> Result<(), Error> {
15    parse(file, schema)?;
16
17    Ok(())
18}
19
20/// Parse a given file and output it in the specified format to stdout.
21///
22/// # Errors
23///
24/// Returns an error if the input can not be parsed and validated, or if the output can not be
25/// formatted in the selected output format.
26pub fn format(
27    file: Option<&PathBuf>,
28    schema: Option<MtreeSchema>,
29    format: OutputFormat,
30    pretty: bool,
31) -> Result<(), Error> {
32    let files = parse(file, schema)?;
33
34    match format {
35        OutputFormat::Json => {
36            let json = if pretty {
37                serde_json::to_string_pretty(&files)?
38            } else {
39                serde_json::to_string(&files)?
40            };
41            println!("{json}");
42        }
43    }
44
45    Ok(())
46}
47
48/// Parse and interpret an MTREE file.
49///
50/// 1. Reads the contents of a file or stdin.
51/// 2. Check whether the input is gzip compressed as that's how it's delivered inside of packages.
52/// 3. Parse the input
53///
54/// NOTE: If a command is piped to this process, the input is read from stdin.
55/// See [`IsTerminal`] for more information about how terminal detection works.
56///
57/// [`IsTerminal`]: https://doc.rust-lang.org/stable/std/io/trait.IsTerminal.html
58///
59/// # Errors
60///
61/// - [Error::NoInputFile] if a file is given and doesn't exist.
62/// - [Error::IoPath] if a given file cannot be opened or read.
63/// - [Error::Io] if the file is streamed via StdIn and an error occurs.
64/// - [Error::InvalidGzip] if the file is gzip compressed, but the archive is malformed.
65/// - [Error::InvalidUTF8] if the given file contains invalid UTF-8.
66/// - [Error::ParseError] if a malformed MTREE file is encountered.
67/// - [Error::InterpreterError] if expected properties for a given type aren't set.
68pub fn parse(file: Option<&PathBuf>, schema: Option<MtreeSchema>) -> Result<Mtree, Error> {
69    if let Some(file) = file {
70        Mtree::from_file_with_schema(file, schema)
71    } else if !io::stdin().is_terminal() {
72        Mtree::from_stdin_with_schema(schema)
73    } else {
74        Err(Error::NoInputFile)
75    }
76}