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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
|
#[cfg(feature = "comp")]
use crate::{ShellContext, Suggest};
#[cfg(feature = "general_renderer")]
use crate::error::GeneralRendererSerializeError;
#[cfg(not(windows))]
use std::env;
use crate::{
AnyOutput, ChainProcess, GlobalResources, Groupped, RenderResult,
asset::dispatcher::Dispatcher,
error::{ChainProcessError, ProgramExecuteError},
};
use std::{
collections::HashMap,
fmt::Display,
sync::{Arc, Mutex, OnceLock},
};
#[cfg(feature = "async")]
use std::pin::Pin;
#[doc(hidden)]
pub mod exec;
#[doc(hidden)]
pub mod setup;
mod config;
pub use config::*;
mod flag;
pub use flag::*;
mod string_vec;
pub use string_vec::*;
/// Global static reference to the current program instance
static THIS_PROGRAM: OnceLock<Option<Box<dyn std::any::Any + Send + Sync>>> = OnceLock::new();
/// Returns a reference to the current program instance, panics if not set.
pub fn this<C>() -> &'static Program<C>
where
C: ProgramCollect + 'static,
{
try_get_this_program().expect("Program not initialized")
}
/// Returns a reference to the current program instance, if set.
fn try_get_this_program<C>() -> Option<&'static Program<C>>
where
C: ProgramCollect + 'static,
{
THIS_PROGRAM.get()?.as_ref()?.downcast_ref::<Program<C>>()
}
/// Program, used to define the behavior of the entire command-line program
#[derive(Default)]
pub struct Program<C>
where
C: ProgramCollect,
{
pub(crate) collect: std::marker::PhantomData<C>,
pub(crate) args: Vec<String>,
#[cfg(not(feature = "dispatch_tree"))]
pub(crate) dispatcher: Vec<Box<dyn Dispatcher<C> + Send + Sync>>,
pub stdout_setting: ProgramStdoutSetting,
pub user_context: ProgramUserContext,
#[cfg(feature = "general_renderer")]
pub general_renderer_name: GeneralRendererSetting,
pub(crate) resources: GlobalResources,
}
impl<C> Program<C>
where
C: ProgramCollect<Enum = C>,
{
/// Creates a new Program instance, initializing command-line arguments from the environment.
pub fn new() -> Self {
#[cfg(not(windows))]
return Self::new_with_args(env::args().collect::<Vec<String>>());
#[cfg(windows)]
return Self::new_with_args({
std::env::args_os()
.map(|arg| {
use std::os::windows::ffi::OsStrExt;
let wide: Vec<u16> = arg.encode_wide().collect();
String::from_utf16_lossy(&wide)
})
.collect::<Vec<_>>()
});
}
/// Creates a new Program instance with the provided command-line arguments.
pub fn new_with_args(args: impl Into<StringVec>) -> Self {
Program {
collect: std::marker::PhantomData,
args: args.into().into(),
#[cfg(not(feature = "dispatch_tree"))]
dispatcher: Vec::new(),
stdout_setting: Default::default(),
user_context: Default::default(),
#[cfg(feature = "general_renderer")]
general_renderer_name: GeneralRendererSetting::Disable,
resources: Arc::new(Mutex::new(HashMap::new())),
}
}
/// Returns a reference to the current program instance, if set.
pub fn this_program() -> &'static Program<C>
where
C: 'static,
{
THIS_PROGRAM
.get()
.unwrap()
.as_ref()
.unwrap()
.downcast_ref::<Program<C>>()
.unwrap()
}
/// Get all registered dispatcher names from the program
pub fn get_nodes(
&'static self,
) -> Vec<(String, &'static (dyn Dispatcher<C> + Send + Sync + 'static))> {
get_nodes(self)
}
/// Dynamically dispatch input arguments to registered entry types
pub fn dispatch_args_dynamic(
&'static self,
args: impl Into<StringVec>,
) -> Result<AnyOutput<C>, ChainProcessError> {
match exec::dispatch_args_dynamic(self, &args.into().into()) {
Ok(ok) => Ok(ok),
Err(e) => Err(e.into()),
}
}
/// Use a prefix tree to quickly match arguments and dispatch to an Entry
#[cfg(feature = "dispatch_tree")]
pub fn dispatch_args_trie(
&'static self,
args: impl Into<StringVec>,
) -> Result<AnyOutput<C>, ChainProcessError> {
let string_vec: Vec<String> = args.into().into();
match C::dispatch_args_trie(&string_vec) {
Ok(ok) => Ok(ok),
Err(e) => Err(e.into()),
}
}
}
// Async program
#[cfg(feature = "async")]
impl<C> Program<C>
where
C: ProgramCollect<Enum = C>,
{
/// Sets the current program instance and runs the provided async function.
async fn set_instance_and_run<F, Fut>(self, f: F) -> Fut::Output
where
C: 'static + Send + Sync,
F: FnOnce(&'static Program<C>) -> Fut + Send + Sync,
Fut: Future + Send,
{
THIS_PROGRAM.get_or_init(|| Some(Box::new(self)));
let program = THIS_PROGRAM
.get()
.unwrap()
.as_ref()
.unwrap()
.downcast_ref::<Program<C>>()
.unwrap();
f(program).await
}
/// Run the command line program
pub async fn exec_without_render(mut self) -> Result<RenderResult, ProgramExecuteError>
where
C: 'static + Send + Sync,
{
self.args = self.args.iter().skip(1).cloned().collect();
self.set_instance_and_run(|p| async { crate::exec::exec(p).await.map_err(|e| e.into()) })
.await
}
/// Run the command line program
pub async fn exec(self)
where
C: 'static + Send + Sync,
{
let stdout_setting = self.stdout_setting.clone();
let result = match self.exec_without_render().await {
Ok(r) => r,
Err(e) => match e {
ProgramExecuteError::DispatcherNotFound => {
eprintln!("Dispatcher not found");
return;
}
ProgramExecuteError::RendererNotFound(renderer_name) => {
eprintln!("Renderer `{}` not found", renderer_name);
return;
}
ProgramExecuteError::Other(e) => {
eprintln!("{}", e);
return;
}
},
};
// Render result
if stdout_setting.render_output && !result.is_empty() {
print!("{}", result);
if let Err(e) = std::io::Write::flush(&mut std::io::stdout())
&& stdout_setting.error_output
{
eprintln!("{}", e);
}
}
}
}
// Sync program
#[cfg(not(feature = "async"))]
impl<C> Program<C>
where
C: ProgramCollect<Enum = C>,
{
/// Sets the current program instance and runs the provided function.
fn set_instance_and_run<F, R>(self, f: F) -> R
where
C: 'static + Send + Sync,
F: FnOnce(&'static Program<C>) -> R + Send + Sync,
{
THIS_PROGRAM.get_or_init(|| Some(Box::new(self)));
let program = THIS_PROGRAM
.get()
.unwrap()
.as_ref()
.unwrap()
.downcast_ref::<Program<C>>()
.unwrap();
f(program)
}
/// Run the command line program
pub fn exec_without_render(mut self) -> Result<RenderResult, ProgramExecuteError>
where
C: 'static + Send + Sync,
{
self.args = self.args.iter().skip(1).cloned().collect();
self.set_instance_and_run(|p| crate::exec::exec(p).map_err(|e| e.into()))
}
/// Run the command line program
pub fn exec(self)
where
C: 'static + Send + Sync,
{
let stdout_setting = self.stdout_setting.clone();
let result = match self.exec_without_render() {
Ok(r) => r,
Err(e) => match e {
ProgramExecuteError::DispatcherNotFound => {
eprintln!("Dispatcher not found");
return;
}
ProgramExecuteError::RendererNotFound(renderer_name) => {
eprintln!("Renderer `{}` not found", renderer_name);
return;
}
ProgramExecuteError::Other(e) => {
eprintln!("{}", e);
return;
}
},
};
// Render result
if stdout_setting.render_output && !result.is_empty() {
print!("{}", result);
if let Err(e) = std::io::Write::flush(&mut std::io::stdout())
&& stdout_setting.error_output
{
eprintln!("{}", e);
}
}
}
}
/// Collected program context
///
/// Note: It is recommended to use the `gen_program!()` macro from [mingling_macros](https://crates.io/crates/mingling_macros) to automatically create this type
pub trait ProgramCollect {
/// Enum type representing internal IDs for the program
type Enum: Display;
type DispatcherNotFound: Groupped<Self::Enum>;
type RendererNotFound: Groupped<Self::Enum>;
/// Use a prefix tree to quickly match arguments and dispatch to an Entry
#[cfg(feature = "dispatch_tree")]
fn dispatch_args_trie(
raw: &Vec<String>,
) -> Result<AnyOutput<Self::Enum>, crate::error::ProgramInternalExecuteError>;
/// Get all registered dispatcher names from the program
#[cfg(feature = "dispatch_tree")]
fn get_nodes() -> Vec<(String, &'static (dyn Dispatcher<Self::Enum> + Send + Sync))>;
/// Build an [AnyOutput](./struct.AnyOutput.html) to indicate that a renderer was not found
fn build_renderer_not_found(member_id: Self::Enum) -> AnyOutput<Self::Enum>;
/// Build an [AnyOutput](./struct.AnyOutput.html) to indicate that a dispatcher was not found
fn build_dispatcher_not_found(args: Vec<String>) -> AnyOutput<Self::Enum>;
/// Render the input [AnyOutput](./struct.AnyOutput.html)
fn render(any: AnyOutput<Self::Enum>, r: &mut RenderResult);
/// Render help for Entry
fn render_help(any: AnyOutput<Self::Enum>, r: &mut RenderResult);
/// Find a matching chain to continue execution based on the input [AnyOutput](./struct.AnyOutput.html), returning a new [AnyOutput](./struct.AnyOutput.html)
#[cfg(feature = "async")]
fn do_chain(
any: AnyOutput<Self::Enum>,
) -> Pin<Box<dyn Future<Output = ChainProcess<Self::Enum>> + Send>>;
/// Find a matching chain to continue execution based on the input [AnyOutput](./struct.AnyOutput.html), returning a new [AnyOutput](./struct.AnyOutput.html)
#[cfg(not(feature = "async"))]
fn do_chain(any: AnyOutput<Self::Enum>) -> ChainProcess<Self::Enum>;
/// Match and execute specific completion logic based on any Entry
#[cfg(feature = "comp")]
fn do_comp(any: &AnyOutput<Self::Enum>, ctx: &ShellContext) -> Suggest;
/// Whether the program has a renderer that can handle the current [AnyOutput](./struct.AnyOutput.html)
fn has_renderer(any: &AnyOutput<Self::Enum>) -> bool;
/// Whether the program has a chain that can handle the current [AnyOutput](./struct.AnyOutput.html)
fn has_chain(any: &AnyOutput<Self::Enum>) -> bool;
/// Perform general rendering and presentation of any type
#[cfg(feature = "general_renderer")]
fn general_render(
any: AnyOutput<Self::Enum>,
setting: &GeneralRendererSetting,
) -> Result<RenderResult, GeneralRendererSerializeError>;
}
#[macro_export]
#[doc(hidden)]
macro_rules! __dispatch_program_renderers {
(
$( $render_ty:ty => $prev_ty:ident, )*
) => {
fn render(any: mingling::AnyOutput<Self::Enum>, r: &mut mingling::RenderResult) {
match any.member_id {
$(
Self::$prev_ty => {
// SAFETY: The `type_id` check ensures that `any` contains a value of type `$prev_ty`,
// so downcasting to `$prev_ty` is safe.
let value = unsafe { any.downcast::<$prev_ty>().unwrap_unchecked() };
<$render_ty as mingling::Renderer>::render(value, r);
}
)*
_ => (),
}
}
};
}
#[macro_export]
#[doc(hidden)]
#[cfg(feature = "async")]
macro_rules! __dispatch_program_chains {
(
$( $chain_ty:ty => $chain_prev:ident, )*
) => {
fn do_chain(
any: mingling::AnyOutput<Self::Enum>,
) -> std::pin::Pin<Box<dyn Future<Output = mingling::ChainProcess<Self::Enum>> + Send>> {
match any.member_id {
$(
Self::$chain_prev => {
// SAFETY: The `type_id` check ensures that `any` contains a value of type `$chain_prev`,
// so downcasting to `$chain_prev` is safe.
let value = unsafe { any.downcast::<$chain_prev>().unwrap_unchecked() };
let fut = async { <$chain_ty as mingling::Chain<Self::Enum>>::proc(value).await };
Box::pin(fut)
}
)*
_ => panic!("No chain found for type id: {:?}", any.type_id),
}
}
};
}
#[macro_export]
#[doc(hidden)]
#[cfg(not(feature = "async"))]
macro_rules! __dispatch_program_chains {
(
$( $chain_ty:ty => $chain_prev:ident, )*
) => {
fn do_chain(
any: mingling::AnyOutput<Self::Enum>,
) -> mingling::ChainProcess<Self::Enum> {
match any.member_id {
$(
Self::$chain_prev => {
// SAFETY: The `type_id` check ensures that `any` contains a value of type `$chain_prev`,
// so downcasting to `$chain_prev` is safe.
let value = unsafe { any.downcast::<$chain_prev>().unwrap_unchecked() };
<$chain_ty as mingling::Chain<Self::Enum>>::proc(value)
}
)*
_ => panic!("No chain found for type id: {:?}", any.type_id),
}
}
};
}
/// Get all registered dispatcher names from the program
#[allow(unused_variables)]
pub fn get_nodes<C: ProgramCollect<Enum = C>>(
program: &'static Program<C>,
) -> Vec<(String, &'static (dyn Dispatcher<C> + Send + Sync + 'static))> {
#[cfg(feature = "dispatch_tree")]
let r = C::get_nodes();
#[cfg(feature = "dispatch_tree")]
{
#[cfg(feature = "debug")]
{
let node_strs: Vec<String> = r.iter().map(|v| v.0.clone()).collect();
crate::info!("All Nodes: [{}]", node_strs.join(", "));
}
}
#[cfg(not(feature = "dispatch_tree"))]
let r: Vec<_> = program
.dispatcher
.iter()
.map(|disp| {
let node_str = disp
.node()
.to_string()
.split('.')
.collect::<Vec<_>>()
.join(" ");
(node_str, &**disp)
})
.collect();
#[cfg(not(feature = "dispatch_tree"))]
{
#[cfg(feature = "debug")]
{
let node_strs: Vec<String> = r.iter().map(|v| v.0.clone()).collect();
crate::info!("All Nodes: [{}]", node_strs.join(", "));
}
}
r
}
|