wca 0.46.0

The tool to make CLI ( commands user interface ). It is able to aggregate external binary applications, as well as functions, which are written in your language.
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
#[ allow( clippy ::std_instead_of_alloc, clippy ::std_instead_of_core ) ]
mod private
{

  use crate :: *;
  use ca ::
  {
  Type,
  Order,
  formatter ::
  {
   HelpFormat,
   md_generator
 },
  tool ::table ::format_table,
 };
  use verifier ::VerifiedCommand;
  use grammar :: { Command, Dictionary };
  use executor ::Routine;

  use iter_tools ::Itertools;
  use std ::rc ::Rc;
  use error_tools ::untyped ::format_err;
  use former ::Former;

  // aaa: for Bohdan: it should transparent mechanist which patch list of commands, not a stand-alone mechanism
  // aaa: it is

  /// Enum `LevelOfDetail` specifies the granularity of detail for rendering or processing :
  #[ derive( Debug, Default, Copy, Clone, PartialEq, Eq ) ]
  pub enum LevelOfDetail
  {
  /// No detail (default).
  #[ default ]
  None,
  /// Basic level of detail.
  Simple,
  /// High level of detail.
  Detailed,
 }

  /// Container for arguments passed to a help generator function.
  #[ derive( Debug, Former ) ]
  pub struct HelpGeneratorOptions< 'a >
  {
  /// Prefix that will be shown before command name
  #[ former( default = String ::new() ) ]
  pub command_prefix: String,
  /// Show help for the specified commands
  pub for_commands: Vec< &'a Command >,
  /// Reresents how much information to display for the subjects
  ///
  /// - `None` - nothing
  /// - `Simple` - < subjects >
  /// - `Detailed` - each subject with information about it. E.g. `< String >`
  pub subject_detailing: LevelOfDetail,
  /// Reresents how much information to display for the properties
  ///
  /// - `None` - nothing
  /// - `Simple` - < properties >
  /// - `Detailed` - each property with information about it. E.g. `< property_name: String >`
  pub property_detailing: LevelOfDetail,
  /// Reresents how much information to display for the properties
  ///
  /// - `None` - nothing
  /// - `Simple` - short hint
  /// - `Detailed` - long hint
  pub description_detailing: LevelOfDetail,
  /// If enabled - shows complete description of subjects and properties
  pub with_footer: bool,
  /// Order of property and commands.
  #[ former( default = Order ::default() ) ]
  pub order: Order,
 }

  // aaa: for Barsik: make possible to change properties order
  // aaa: order option

  /// Generates help content as a formatted string based on a given dictionary and options.
  ///
  /// This function takes a `Dictionary` of terms or commands and a `HelpGeneratorOptions`
  /// struct to customize the help output, generating a user-friendly help message
  /// or guide in `String` format.
  /// # Panics
  /// qqq: doc
  #[ must_use ]
  #[ allow( clippy ::match_same_arms ) ]
  pub fn generate_help_content( dictionary: &Dictionary, o: HelpGeneratorOptions< '_ > ) -> String
  {
  struct Row
  {
   name: String,
   args: String,
   hint: String,
   footer: String,
 }
  let for_single_command = | command: &Command |
  {
   let name = &command.phrase;
   let hint = match o.description_detailing
   {
  LevelOfDetail ::None => "",
  _ if command.hint.is_empty() && command.long_hint.is_empty() => "",
  LevelOfDetail ::Simple if !command.hint.is_empty() => command.hint.as_str(),
  LevelOfDetail ::Detailed if !command.long_hint.is_empty() => command.long_hint.as_str(),
  _ if !command.long_hint.is_empty() => command.long_hint.as_str(),
  _ if !command.hint.is_empty() => command.hint.as_str(),
  _ => unreachable!(),
 };
   let subjects = match o.subject_detailing
   {
  LevelOfDetail ::None => String ::new(),
  _ if command.subjects.is_empty() => String ::new(),
  LevelOfDetail ::Simple => "< subjects >".into(),
  LevelOfDetail ::Detailed => command.subjects.iter().map( | v |
  {
   format!( "< {}{:?} >", if v.optional { "?" } else { "" }, v.kind )
 }).collect :: < Vec< _ > >().join( " " ),
 };
   let properties = match o.property_detailing
   {
  LevelOfDetail ::None => String ::new(),
  _ if command.subjects.is_empty() => String ::new(),
  LevelOfDetail ::Simple => "< properties >".into(),
  LevelOfDetail ::Detailed => command.properties( o.order ).iter().map( | ( n, v ) |
  {
   format!( "< {} : {}{:?} >", if v.optional { "?" } else { "" }, n, v.kind )
 }).collect :: < Vec< _ > >().join( " " ),
 };

   let footer = if o.with_footer
   {
  let full_subjects = command.subjects.iter().map( | subj |
  {
   format!( "- {} [{}{:?}]", subj.hint, if subj.optional { "?" } else { "" }, subj.kind )
 }).join( "\n\t" );
  let full_properties = format_table( command.properties( o.order ).into_iter().map( | ( name, value ) |
  {
   [ name.clone(), format!( "- {} [{}{:?}]", value.hint, if value.optional { "?" } else { "" }, value.kind ) ]
 })).unwrap().replace( '\n', "\n\t" );

  format!
  (
   "{}{}",
   if command.subjects.is_empty() 
   { String ::new() } else { format!( "\nSubjects: \n\t{}", &full_subjects ) },
   if command.properties.is_empty() 
   { String ::new() } else { format!( "\nProperties: \n\t{}",&full_properties ) }
 )
 } else { String ::new() };

   Row
   {
  name: format!( "{}{name}", o.command_prefix ),
  args: format!( "{subjects}{}{properties}", if !subjects.is_empty() || !properties.is_empty() { " " } else { "" } ),
  hint: format!( "{}{hint}", if hint.is_empty() { "" } else { "- " } ),
  footer,
 }
 };
  if o.for_commands.len() == 1 || !o.for_commands.is_empty() && !o.with_footer
  {
   o.for_commands.into_iter().map( | command |
   {
  let row = for_single_command( command );
  format!
  (
   "{}{}{}",
   format_table( [ [ row.name, row.args, row.hint ] ] ).unwrap(),
   if row.footer.is_empty() 
   { "" } else { "\n" },
   row.footer
 )
 })
   .join( "\n" )
 }
  else
  {
   let commands_iter = match o.order
   {
  Order ::Nature => dictionary.commands.iter().collect :: < Vec< _ > >(),
  Order ::Lexicography => dictionary.commands.iter().sorted_by_key( | ( key, _ ) | *key ).collect :: < Vec< _ > >(),
 };
   let rows = commands_iter
   .into_iter()
   .map( | ( _, cmd ) | cmd )
   .map( for_single_command )
   .map( | row | [ row.name, row.args, row.hint ] );
   format_table( rows ).unwrap()
 }
 }

  /// Available help commands variants
  #[ derive( Debug, Hash, Eq, PartialEq, Ord, PartialOrd ) ]
  pub enum HelpVariants
  {
  /// Make all available variants
  All,
  /// Help for whole program. E.g. `.help`
  General,
  /// Detailed help for one command as subject in help command. E.g. `.help command_name`
  SubjectCommand,
  /// Detailed help for one command as separate help command. E.g. `.help.command_name`
  DotCommand,
 }

  impl HelpVariants
  {
  /// Generates help commands
  #[ allow( clippy ::match_wildcard_for_single_variants ) ]
  pub fn generate( &self, helper: &HelpGeneratorFn, dictionary: &mut Dictionary, order: Order )
  {
   match self
   {
  HelpVariants ::All =>
  {
   // Register unified help command that handles both cases without mutual delegation
   self.unified_help( helper, dictionary, order );
   // self.dot_command_help( helper, dictionary );
 },
  HelpVariants ::General => self.general_help( helper, dictionary, order ),
  HelpVariants ::SubjectCommand => self.subject_command_help( helper, dictionary, order ),
  _ => unimplemented!()
  // HelpVariants ::DotCommand => self.dot_command_help( helper, dictionary ),
 }
 }

  // Unified .help command (handles both with and without subject)
  #[ allow( clippy ::unused_self ) ]
  fn unified_help( &self, helper: &HelpGeneratorFn, dictionary: &mut Dictionary, order: Order )
  {
   let phrase = "help".to_string();

   let grammar = dictionary.clone();
   let generator = helper.clone();

   let routine = move | o: VerifiedCommand |
   {
  // If no subject provided, show general help
  if o.args.0.is_empty()
  {
   let format_prop: String = o.props.get_owned( "format" ).unwrap_or_default();
   let format = match format_prop.as_str()
   {
    "md" | "markdown" => HelpFormat ::Markdown,
    _ => HelpFormat ::Another,
  };
   if format == HelpFormat ::Markdown
   {
    println!( "Help command\n{text}", text = md_generator( &grammar, order ) );
  }
   else
   {
    let options = HelpGeneratorOptions ::former()
    .command_prefix( "." )
    .description_detailing( LevelOfDetail ::Simple )
    .subject_detailing( LevelOfDetail ::Simple )
    .property_detailing( LevelOfDetail ::Simple )
    .order( order );
    println!
    (
   "Help command\n\n{text}",
   text = generator.exec
   (
    &grammar,
    options.form()
  )
  );
  }
  }
  // If subject provided, show help for that specific command
  else
  {
   let command = o.args.get_owned :: < String >( 0 ).unwrap();
   let cmd = grammar.commands
   .get( &command )
   .ok_or_else( || format_err!( "Can not found help for command `{command}`" ) )?;

   let args = HelpGeneratorOptions ::former()
   .command_prefix( "." )
   .for_commands( [ cmd ] )
   .description_detailing( LevelOfDetail ::Detailed )
   .subject_detailing( LevelOfDetail ::Simple )
   .property_detailing( LevelOfDetail ::Simple )
   .with_footer( true )
   .order( order );

   let text = generator.exec( &grammar, args.form() );

   println!( "Help command\n\n{text}" );
  }

  Ok :: < _, error_tools ::untyped ::Error >( () )
 };

   let help = Command ::former()
   .hint( "prints full information about a specified command" )
   .subject()
   .hint( "command name" )
   .kind( Type ::String )
   .optional( true )
   .end()
   .property( "format" )
   .hint( "help generates in format witch you write" )
   .kind( Type ::String )
   .optional( true )
   .end()
   .phrase( &phrase )
   .routine( routine )
   .form();

   dictionary.register( help );
 }

  // .help
  #[ allow( clippy ::unused_self ) ]
  fn general_help( &self, helper: &HelpGeneratorFn, dictionary: &mut Dictionary, order: Order )
  {
   let phrase = "help".to_string();

   let grammar = dictionary.clone();
   let generator = helper.clone();

   let moved_phrase = phrase.clone();
   let routine = move | o: VerifiedCommand |
   {
  let subject_help = grammar.command( &moved_phrase );
  match &subject_help
  {
   Some( Command { routine: Routine ::WithoutContext( help ), .. } )
   if !o.args.0.is_empty() => help( o )?,
   _ =>
   {
  let format_prop: String = o.props.get_owned( "format" ).unwrap_or_default();
  let format = match format_prop.as_str()
  {
   "md" | "markdown" => HelpFormat ::Markdown,
   _ => HelpFormat ::Another,
 };
  if format == HelpFormat ::Markdown
  {
   println!( "Help command\n{text}", text = md_generator( &grammar, order ) );
 }
  else
  {
   let options = HelpGeneratorOptions ::former()
   .command_prefix( "." )
   .description_detailing( LevelOfDetail ::Simple )
   .subject_detailing( LevelOfDetail ::Simple )
   .property_detailing( LevelOfDetail ::Simple )
   .order( order );
   println!
   (
  "Help command\n\n{text}",
  text = generator.exec
  (
   &grammar,
   options.form()
 )
 );
 }
 }
 }

  Ok :: < _, error_tools ::untyped ::Error >( () )
 };
   let help = Command ::former()
   .hint( "prints information about existing commands" )
   .property( "format" )
   .hint( "help generates in format witch you write" )
   .kind( Type ::String )
   .optional( true )
   .end()
   .phrase( &phrase )
   .routine( routine )
   .form();

   dictionary.register( help );
 }

  // .help command_name
  #[ allow( clippy ::unused_self ) ]
  fn subject_command_help( &self, helper: &HelpGeneratorFn, dictionary: &mut Dictionary, order: Order )
  {
   let phrase = "help".to_string();

   let grammar = dictionary.clone();
   let generator = helper.clone();

   let moved_phrase = phrase.clone();
   let routine = move | o: VerifiedCommand |
   {
  let full_help = grammar.command( &moved_phrase );
  match &full_help
  {
   Some( Command { routine: Routine ::WithoutContext( help ), .. } )
   if o.args.0.is_empty() => help( o )?,
   _ =>
   {
  let command = o.args.get_owned :: < String >( 0 ).unwrap();
  let cmd = grammar.commands
  .get( &command )
  .ok_or_else( || format_err!( "Can not found help for command `{command}`" ) )?;

  let args = HelpGeneratorOptions ::former()
  .command_prefix( "." )
  .for_commands( [ cmd ] )
  .description_detailing( LevelOfDetail ::Detailed )
  .subject_detailing( LevelOfDetail ::Simple )
  .property_detailing( LevelOfDetail ::Simple )
  .with_footer( true )
  .order( order );

  let text = generator.exec( &grammar, args.form() );

  println!( "Help command\n\n{text}" );
 }
 }

  Ok :: < _, error_tools ::untyped ::Error >( () )
 };

   let help = Command ::former()
   .hint( "prints full information about a specified command" )
   .subject()
   .hint( "command name" )
   .kind( Type ::String )
   .optional( true )
   .end()
   .property( "format" )
   .hint( "help generates in format witch you write" )
   .kind( Type ::String )
   .optional( true )
   .end()
   .phrase( &phrase )
   .routine( routine )
   .form();

   dictionary.register( help );
 }

  // .help.command_name
  // fn dot_command_help( &self, helper: &HelpGeneratorFn, grammar: &mut Dictionary )
  // {
  //   // generate commands names
  //   let commands: Vec< _ > = grammar.commands.iter().map( |( name, cmd )| ( format!( "help.{name}" ), cmd.clone() ) ).collect();
  //
  //   // generate Commands grammar
  //   let grammar_helps = commands
  //   .iter()
  //   .map( |( help_name, _ )| Command ::former().hint( "prints full information about a specified command" ).phrase( help_name ).form() )
  //   .collect :: < Vec< _ > >();
  //
  //   // add commands to Verifier
  //   for cmd in grammar_helps
  //   {
  //     let command_variants = grammar.commands.entry( cmd.phrase.to_owned() ).or_insert_with( Vec ::new );
  //     command_variants.push( cmd );
  // }
  //
  //   // generate Commands routines
  //   let executable = commands
  //   .into_iter()
  //   .fold( vec![], | mut acc, ( help_name, cmds ) |
  //   {
  //     let generator = helper.clone();
  //     // TODO: Will be static
  //     let grammar = grammar.clone();
  //
  //     let routine = Routine ::new( move | _ |
  //     {
  //       let text = cmds.iter()
  //       .map
  //       (
  //         | cmd | generator.exec( &grammar, Some( cmd ) )
  // )
  //       .join( "\n\n" );
  //
  //       println!( "Help for command\n\n{text}" );
  //
  //       Ok( () )
  // });
  //     acc.push(( help_name, routine ));
  //
  //     acc
  // });
  //
  //   // add commands to ExecutorConverter
  //   for ( phrase, routine ) in executable
  //   {
  //     executor.routines.insert( phrase, routine );
  // }
  // }
 }

  type HelpFunctionFn = Rc< dyn Fn( &Dictionary, HelpGeneratorOptions< '_ > ) -> String >;

  /// Container for function that generates help string for any command
  ///
  /// ```
  /// # use wca ::ca ::help :: { HelpGeneratorOptions, HelpGeneratorFn };
  /// use wca ::grammar :: { Command, Dictionary };
  ///
  /// fn my_help_generator( dictionary: &Dictionary, args: HelpGeneratorOptions< '_ > ) -> String
  /// {
  ///   format!( "Help content based on grammar and command" )
  /// }
  ///
  /// let help_fn = HelpGeneratorFn ::new( my_help_generator );
  /// # let grammar = &Dictionary ::former().form();
  ///
  /// help_fn.exec( grammar, HelpGeneratorOptions ::former().form() );
  /// // or
  /// # let cmd = Command ::former().form();
  /// help_fn.exec( grammar, HelpGeneratorOptions ::former().for_commands( [ &cmd ] ).form() );
  /// ```
  #[ derive( Clone ) ]
  pub struct HelpGeneratorFn( HelpFunctionFn );

  impl Default for HelpGeneratorFn
  {
  fn default() -> Self
  {
   Self( Rc ::new( generate_help_content ) )
 }
 }

  impl HelpGeneratorFn
  {
  /// Wrap a help function
  pub fn new< HelpFunction >( func: HelpFunction ) -> Self
  where
   HelpFunction: Fn( &Dictionary, HelpGeneratorOptions< '_ > ) -> String + 'static
  {
   Self( Rc ::new( func ) )
 }
 }

  impl HelpGeneratorFn
  {
  /// Executes the function to generate help content
  #[ must_use ]
  pub fn exec( &self, dictionary: &Dictionary, args: HelpGeneratorOptions< '_ > ) -> String
  {
   self.0( dictionary, args )
 }
 }

  impl core ::fmt ::Debug for HelpGeneratorFn
  {
  fn fmt( &self, f: &mut core ::fmt ::Formatter< '_ > ) -> core ::fmt ::Result
  {
   f.write_str( "HelpGenerator" )
 }
 }
}

//

crate ::mod_interface!
{
  own use HelpGeneratorFn;
  own use HelpGeneratorOptions;
  own use LevelOfDetail;
  own use generate_help_content;

  prelude use HelpVariants;

}