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
97
98
99
use std::process::exit;
use anyhow::*;
use async_trait::async_trait;
use clap::Parser;
use serde::Serialize;
pub type CliResult = Result<String, String>;
pub type CliTypedResult<T> = Result<T, Error>;
#[async_trait]
pub trait CliTool<T: Serialize + Send>: Sized + Send + Parser {
async fn execute(self) -> CliTypedResult<T>;
async fn execute_serialized(self) -> CliResult {
to_common_result(self.execute().await).await
}
async fn execute_serialized_success(self) -> CliResult {
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>) -> CliResult {
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<CliTypedResult<T>> for ResultWrapper<T> {
fn from(result: CliTypedResult<T>) -> Self {
match result {
CliTypedResult::Ok(inner) => ResultWrapper::Result(inner),
CliTypedResult::Err(inner) => ResultWrapper::Error(inner.to_string()),
}
}
}
pub async fn to_common_result<T: Serialize>(result: Result<T>) -> CliResult {
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 {
CliResult::Err(string)
} else {
CliResult::Ok(string)
}
}