1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
//! Command handler.

use anyhow::*;
use clap::Parser;
use errmap::ErrorMapping;
use serde::{Deserialize, Serialize};
use std::io::{self, Read};

macro_rules! format_info {
    ($name:ident::$ty:ident) => {
        concat!(
            "A [move_core_types::",
            stringify!($name),
            "::",
            stringify!($ty),
            "]. (see <https://docs.rs/mv-core-types/latest/move_core_types/",
            stringify!($name),
            "/struct.",
            stringify!($ty),
            ".html>)",
        )
    };
}

fn render_json<'a, I, O>(bytes: &'a [u8]) -> Result<String>
where
    I: Deserialize<'a>,
    O: From<I> + ?Sized + Serialize,
{
    let result: I = bcs::from_bytes(bytes)?;
    let output: O = result.into();
    serde_json::to_string_pretty(&output).with_context(|| "could not render input")
}

/// The format of the data.
#[derive(clap::Subcommand, Copy, Clone, Debug, PartialEq, Eq)]
pub enum KnownFormat {
    #[clap(name = "errmap", about = format_info!(errmap::ErrorMapping))]
    ErrorMapping,
}

impl KnownFormat {
    fn render(self, input: &[u8]) -> Result<String> {
        match self {
            KnownFormat::ErrorMapping => {
                render_json::<move_core_types::errmap::ErrorMapping, ErrorMapping>(input)
            }
        }
    }
}

/// Reads a BCS-encoded file from stdin and prints it.
#[derive(Clone, Debug, clap::Parser)]
#[clap(
    about,
    version,
    author,
    arg_required_else_help = true,
    disable_help_subcommand = true,
    subcommand_help_heading = "FORMATS"
)]
pub struct Opts {
    /// Format of the input data.
    #[clap(subcommand)]
    pub format: KnownFormat,
}

impl Opts {
    pub fn run() -> Result<()> {
        let opts = Opts::parse();

        let mut buf = vec![];
        io::stdin().read_to_end(&mut buf)?;

        let out = opts.format.render(&buf)?;
        println!("{}", &out);

        Ok(())
    }
}