stellar_xdr/cli/generate/
default.rs1use clap::{Args, ValueEnum};
2use std::{
3 io::{stdout, Write},
4 str::FromStr,
5};
6
7use crate::cli::util;
8
9#[derive(thiserror::Error, Debug)]
10pub enum Error {
11 #[error("unknown type {0}, choose one of {1:?}")]
12 UnknownType(String, &'static [&'static str]),
13 #[error("error reading file: {0}")]
14 ReadFile(#[from] std::io::Error),
15 #[error("error generating XDR: {0}")]
16 WriteXdr(#[from] crate::Error),
17 #[error("error generating JSON: {0}")]
18 GenerateJson(#[from] serde_json::Error),
19 #[error("type doesn't have a text representation, use 'json' as output")]
20 TextUnsupported,
21}
22
23#[derive(Args, Debug, Clone)]
25#[command()]
26pub struct Cmd {
27 #[arg(long)]
29 pub r#type: String,
30
31 #[arg(long = "output", value_enum, default_value_t)]
33 pub output_format: OutputFormat,
34}
35
36#[derive(Default, Clone, Copy, Debug, Eq, Hash, PartialEq, ValueEnum)]
37pub enum OutputFormat {
38 Single,
39 #[default]
40 SingleBase64,
41 Json,
45 JsonFormatted,
46 Text,
47}
48
49macro_rules! run_x {
52 ($f:ident) => {
53 fn $f(&self) -> Result<(), Error> {
54 use crate::WriteXdr;
55 let r#type = crate::TypeVariant::from_str(&self.r#type).map_err(|_| {
56 Error::UnknownType(self.r#type.clone(), &crate::TypeVariant::VARIANTS_STR)
57 })?;
58 let v = crate::Type::default(r#type);
59 match self.output_format {
60 OutputFormat::Single => {
61 let l = crate::Limits::none();
62 stdout().write_all(&v.to_xdr(l)?)?
63 }
64 OutputFormat::SingleBase64 => {
65 let l = crate::Limits::none();
66 println!("{}", v.to_xdr_base64(l)?)
67 }
68 OutputFormat::Json => {
69 println!("{}", serde_json::to_string(&v)?);
70 }
71 OutputFormat::JsonFormatted => {
72 println!("{}", serde_json::to_string_pretty(&v)?);
73 }
74 OutputFormat::Text => {
75 let v = serde_json::to_value(v)?;
76 let text = util::serde_json_value_to_text(v).ok_or(Error::TextUnsupported)?;
77 println!("{text}")
78 }
79 }
80 Ok(())
81 }
82 };
83}
84
85impl Cmd {
86 pub fn run(&self) -> Result<(), Error> {
92 self.run_inner()
93 }
94
95 run_x!(run_inner);
96}