Skip to main content

stellar_xdr/cli/
compare.rs

1use std::{
2    fmt::Debug,
3    fs::File,
4    io::{stdout, Write},
5    path::PathBuf,
6    str::FromStr,
7};
8
9use clap::{Args, ValueEnum};
10
11#[derive(thiserror::Error, Debug)]
12pub enum Error {
13    #[error("unknown type {0}, choose one of {1:?}")]
14    UnknownType(String, &'static [&'static str]),
15    #[error("error decoding XDR: {0}")]
16    ReadXdr(#[from] crate::Error),
17    #[error("error reading file: {0}")]
18    ReadFile(std::io::Error),
19    #[error("error writing output: {0}")]
20    WriteOutput(std::io::Error),
21}
22
23/// Compare two XDR values with each other
24///
25/// Outputs:
26///   `-1` when the left XDR value is less than the right XDR value,
27///   `0` when the left XDR value is equal to the right XDR value,
28///   `1` when the left XDR value is greater than the right XDR value
29#[derive(Args, Debug, Clone)]
30#[command()]
31pub struct Cmd {
32    /// XDR file to decode and compare with the right value
33    #[arg()]
34    pub left: PathBuf,
35
36    /// XDR file to decode and compare with the left value
37    #[arg()]
38    pub right: PathBuf,
39
40    /// XDR type of both inputs
41    #[arg(long)]
42    pub r#type: String,
43
44    // Input format of the XDR
45    #[arg(long, value_enum, default_value_t)]
46    pub input: InputFormat,
47}
48
49#[derive(Default, Clone, Copy, Debug, Eq, Hash, PartialEq, ValueEnum)]
50pub enum InputFormat {
51    Single,
52    #[default]
53    SingleBase64,
54}
55
56// TODO: Remove run_x macro, it exists only to reduce the diff from when curr/next
57// channels existed and each had their own run_curr/run_next invocation.
58macro_rules! run_x {
59    ($f:ident) => {
60        fn $f(&self) -> Result<(), Error> {
61            let f1 = File::open(&self.left).map_err(Error::ReadFile)?;
62            let f2 = File::open(&self.right).map_err(Error::ReadFile)?;
63            let r#type = crate::TypeVariant::from_str(&self.r#type).map_err(|_| {
64                Error::UnknownType(self.r#type.clone(), &crate::TypeVariant::VARIANTS_STR)
65            })?;
66            let (t1, t2) = match self.input {
67                InputFormat::Single => {
68                    let t1 = {
69                        let mut l1 = crate::Limited::new(f1, crate::Limits::none());
70                        crate::Type::read_xdr_to_end(r#type, &mut l1)?
71                    };
72                    let t2 = {
73                        let mut l = crate::Limited::new(f2, crate::Limits::none());
74                        crate::Type::read_xdr_to_end(r#type, &mut l)?
75                    };
76                    (t1, t2)
77                }
78                InputFormat::SingleBase64 => {
79                    let t1 = {
80                        let mut l = crate::Limited::new(f1, crate::Limits::none());
81                        crate::Type::read_xdr_base64_to_end(r#type, &mut l)?
82                    };
83                    let t2 = {
84                        let mut l = crate::Limited::new(f2, crate::Limits::none());
85                        crate::Type::read_xdr_base64_to_end(r#type, &mut l)?
86                    };
87                    (t1, t2)
88                }
89            };
90            let cmp = t1.cmp(&t2) as i8;
91            writeln!(stdout(), "{cmp}").map_err(Error::WriteOutput)?;
92            Ok(())
93        }
94    };
95}
96
97impl Cmd {
98    /// Run the CLIs decode command.
99    ///
100    /// ## Errors
101    ///
102    /// If the command is configured with state that is invalid.
103    pub fn run(&self) -> Result<(), Error> {
104        let result = self.run_inner();
105        match result {
106            Ok(()) => Ok(()),
107            Err(Error::WriteOutput(e)) if e.kind() == std::io::ErrorKind::BrokenPipe => Ok(()),
108            Err(e) => Err(e),
109        }
110    }
111
112    run_x!(run_inner);
113}