Skip to main content

stellar_xdr/cli/
mod.rs

1pub mod compare;
2pub mod decode;
3pub mod encode;
4pub mod generate;
5pub mod guess;
6pub mod types;
7mod util;
8mod version;
9pub mod xfile;
10
11use clap::{Parser, Subcommand};
12use std::{ffi::OsString, fmt::Debug};
13
14#[derive(Parser, Debug, Clone)]
15#[command(
16    author,
17    version,
18    about,
19    long_about = None,
20    disable_help_subcommand = true,
21    disable_version_flag = true,
22    disable_colored_help = true,
23    infer_subcommands = true,
24)]
25pub struct Root {
26    #[command(subcommand)]
27    cmd: Cmd,
28}
29
30impl Root {
31    /// Run the CLIs root command.
32    ///
33    /// ## Errors
34    ///
35    /// If the root command is configured with state that is invalid.
36    pub fn run(&self) -> Result<(), Error> {
37        match &self.cmd {
38            Cmd::Types(c) => c.run()?,
39            Cmd::Guess(c) => c.run()?,
40            Cmd::Decode(c) => c.run()?,
41            Cmd::Encode(c) => c.run()?,
42            Cmd::Generate(c) => c.run()?,
43            Cmd::Compare(c) => c.run()?,
44            Cmd::Xfile(c) => c.run()?,
45            Cmd::Version => version::Cmd::run(),
46        }
47        Ok(())
48    }
49}
50
51#[derive(Subcommand, Debug, Clone)]
52pub enum Cmd {
53    /// View information about types
54    Types(types::Cmd),
55    /// Guess the XDR type.
56    ///
57    /// Prints a list of types that the XDR values can be decoded into.
58    Guess(guess::Cmd),
59    /// Decode XDR
60    Decode(decode::Cmd),
61    /// Encode XDR
62    Encode(encode::Cmd),
63    Compare(compare::Cmd),
64    Generate(generate::Cmd),
65    /// Preprocess XDR .x files
66    Xfile(xfile::Cmd),
67    /// Print version information
68    Version,
69}
70
71#[derive(thiserror::Error, Debug)]
72#[allow(clippy::enum_variant_names)]
73pub enum Error {
74    #[error("{0}")]
75    Clap(#[from] clap::Error),
76    #[error("{0}")]
77    Types(#[from] types::Error),
78    #[error(transparent)]
79    Guess(#[from] guess::Error),
80    #[error(transparent)]
81    Decode(#[from] decode::Error),
82    #[error(transparent)]
83    Encode(#[from] encode::Error),
84    #[error(transparent)]
85    Generate(#[from] generate::Error),
86    #[error(transparent)]
87    Compare(#[from] compare::Error),
88    #[error(transparent)]
89    Xfile(#[from] xfile::Error),
90}
91
92/// Run the CLI with the given args.
93///
94/// ## Errors
95///
96/// If the input cannot be parsed.
97pub fn run<I, T>(args: I) -> Result<(), Error>
98where
99    I: IntoIterator<Item = T>,
100    T: Into<OsString> + Clone,
101{
102    let root = Root::try_parse_from(args)?;
103    root.run()
104}