Skip to main content

dce_cli/
lib.rs

1use bytes::Bytes;
2use std::{collections::HashMap, env::args, io::{self, Read}, ops::{Deref, DerefMut}, sync::{Arc, LazyLock, RwLock}, vec};
3
4#[cfg(not(feature = "sync"))]
5use async_trait::async_trait;
6
7use dce_router::{context::Context, protocol::{RoutableProtocol, RpMeta}, router::{RouteMatch, Router}};
8use dce_util::result::{DceError, DceResult};
9
10const MARK_PASSED_SEPARATOR: &str   = "--";
11const MARK_ASSIGNMENT: &str         = "=";
12const MARK_ARG_PREFIX: &str         = "-";
13
14enum ArgType {
15    AssignExpr(String, String),
16    PrefixName,
17    Path,
18    PassedSeparator,
19}
20
21impl ArgType {
22    fn parse(arg: &str) -> Self {
23        let mut parts = arg.splitn(2, MARK_ASSIGNMENT);
24        if let (Some(left), Some(right)) = (parts.next(), parts.next()) {
25            ArgType::AssignExpr(left.to_string(), right.to_string())
26        } else if arg.starts_with(MARK_ARG_PREFIX) {
27            if arg == MARK_PASSED_SEPARATOR { return ArgType::PassedSeparator }
28            ArgType::PrefixName
29        } else {
30            ArgType::Path
31        }
32    }
33}
34
35struct CliArgs(HashMap<String, Vec<String>>);
36
37impl CliArgs {
38    fn set_value(&mut self, key: String, value: String) {
39        if let Some(vectors) = self.0.get_mut(key.as_str()) {
40            vectors.push(value);
41        } else {
42            self.0.insert(key, vec![value]);
43        }
44    }
45}
46
47pub struct CliProtocol {
48    meta: RpMeta<()>,
49    script_path: String,
50    forward_args: Vec<String>,
51	path: String,
52	args: CliArgs,
53}
54
55impl Deref for CliProtocol {
56    type Target = RpMeta<()>;
57
58    fn deref(&self) -> &Self::Target {
59        &self.meta
60    }
61}
62
63impl DerefMut for CliProtocol {
64    fn deref_mut(&mut self) -> &mut Self::Target {
65        &mut self.meta
66    }
67}
68
69impl CliProtocol {
70    pub fn script_path(&self) -> &str {
71        &self.script_path
72    }
73
74    pub fn forward_args(&self) -> &Vec<String> {
75        &self.forward_args
76    }
77
78    pub fn args_map(&self) -> &HashMap<String, Vec<String>> {
79        &self.args.0
80    }
81
82    pub fn args(&self, key: &str) -> Vec<&str> {
83        self.args.0.get(key).map_or_else(|| vec![], |vs| vs.iter().map(|v| v.as_str()).collect::<Vec<_>>())
84    }
85
86    pub fn bool(&self, key: &str) -> bool {
87	    self.args.0.get(key).map(|vs| vs.first()
88            .map(|v| v.eq_ignore_ascii_case("true") || v.eq_ignore_ascii_case("1")))
89            .flatten().unwrap_or(false)
90    }
91
92    pub fn arg(&self, key: &str) -> Option<&str> {
93        self.args.0.get(key).map(|vs| vs.first().map(|s| s.as_str())).flatten()
94    }
95
96    pub fn arg_or<'a>(&'a self, key: &str, def: &'a str) -> &'a str {
97        self.arg(key).unwrap_or(def)
98    }
99
100    pub fn new() -> Self {
101        let mut forward_args: Vec<_> = args().collect();
102        let script_path = forward_args.remove(0);
103        let mut paths: Vec<String> = vec![];
104        let mut cli_args = CliArgs(Default::default());
105        while forward_args.len() > 0 {
106            let arg = forward_args.remove(0);
107            match ArgType::parse(&arg) {
108                ArgType::AssignExpr(left, right) => cli_args.set_value(left, right),
109                ArgType::PrefixName => {
110                    if let Some(next) = forward_args.get(0) {
111                        if matches!(ArgType::parse(next), ArgType::Path) {
112                            cli_args.set_value(arg, forward_args.remove(0));
113                            continue;
114                        }
115                    }
116                    cli_args.set_value(arg, "true".to_string());
117                },
118                ArgType::Path => paths.push(arg),
119                ArgType::PassedSeparator => break,
120            }
121        };
122        CliProtocol { meta: RpMeta::new((), None), script_path, forward_args, path: paths.join("/"), args: cli_args }
123    }
124
125    fn response(mut ctx: Context<CliProtocol>, err: Option<DceError>) {
126        ctx.try_print_err(&err);
127        if ctx.api().iter().any(|a| a.responsive) {
128            if let Some(resp_sid) = ctx.resp_sid() {
129                let prepend = format!("\n\nNew sid: {}", resp_sid);
130                ctx.write_string(prepend);
131            }
132            let resp = ctx.clear_buffer();
133            println!("{}", String::from_utf8_lossy(&resp));
134        }
135    }
136
137    pub fn sync_handle(self, routed: DceResult<RouteMatch<'_, CliProtocol>>) {
138        let mut ctx = Context::new(self, routed.as_ref().ok().map(|r| r.api));
139        let err = match routed {
140            Ok(routed) => routed.api.sync_handle(&mut ctx, routed).err(),
141            err => err.err(),
142        };
143        Self::response(ctx, err);
144    }
145
146    pub async fn handle(self, routed: DceResult<RouteMatch<'_, CliProtocol>>) {
147        let mut ctx = Context::new(self, routed.as_ref().ok().map(|r| r.api));
148        let err = match routed {
149            Ok(routed) => routed.api.handle(&mut ctx, routed).await.err(),
150            err => err.err(),
151        };
152        Self::response(ctx, err);
153    }
154}
155
156#[cfg_attr(not(feature = "sync"), async_trait)]
157impl RoutableProtocol for CliProtocol {
158    type Req = ();
159
160    fn path(&self) -> &str {
161        &self.path
162    }
163
164    fn sync_body(&mut self) -> DceResult<Bytes> {
165        let mut buf = vec![];
166        io::stdin().read_to_end(&mut buf)?;
167        Ok(Bytes::copy_from_slice(&buf))
168    }
169
170    #[cfg(not(feature = "sync"))]
171    async fn body(&mut self) -> DceResult<Bytes> {
172        self.sync_body()
173    }
174}
175
176#[allow(non_snake_case, non_upper_case_globals)]
177pub static CliRouter: LazyLock<Arc<RwLock<Router<CliProtocol>>>> = LazyLock::new(|| Arc::new(RwLock::new(Router::<CliProtocol>::new())));
178
179pub async fn cli_route(){
180    let router = CliRouter.clone();
181    let router = router.read().unwrap();
182    let rp = CliProtocol::new();
183    let routed = router.lookup(&rp);
184    rp.handle(routed).await;
185}