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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
use std::process::exit;
use anyhow::*;
use async_trait::async_trait;
use clap::Parser;
use serde::Serialize;
pub type UserResult = Result<String, String>;
#[async_trait]
pub trait CliTool<T: Serialize + Send>: Sized + Send + Parser {
    
    async fn execute(self) -> Result<T>;
    
    async fn execute_serialized(self) -> UserResult {
        to_common_result(self.execute().await).await
    }
    
    async fn execute_serialized_success(self) -> UserResult {
        to_common_success_result(self.execute().await).await
    }
    
    async fn execute_main() -> Result<()> {
        let tool = Self::parse();
        let result = tool.execute_serialized().await;
        match result {
            Result::Ok(val) => println!("{}", val),
            Result::Err(err) => {
                println!("{}", err);
                exit(1);
            }
        };
        Ok(())
    }
}
pub async fn to_common_success_result<T>(result: Result<T>) -> UserResult {
    to_common_result(result.map(|_| "Success")).await
}
#[derive(Debug, Serialize)]
enum ResultWrapper<T> {
    #[serde(rename = "result")]
    Result(T),
    #[serde(rename = "error")]
    Error(String),
}
impl<T> From<Result<T>> for ResultWrapper<T> {
    fn from(result: Result<T>) -> Self {
        match result {
            Result::Ok(inner) => ResultWrapper::Result(inner),
            Result::Err(inner) => ResultWrapper::Error(inner.to_string()),
        }
    }
}
pub async fn to_common_result<T: Serialize>(result: Result<T>) -> UserResult {
    let is_err = result.is_err();
    let result: ResultWrapper<T> = result.into();
    let string = serde_json::to_string_pretty(&result)
        .map_err(|e| format!("could not serialize command output: {}", e))?;
    if is_err {
        UserResult::Err(string)
    } else {
        UserResult::Ok(string)
    }
}