codegenr 0.0.2

Fast json/yaml/openapi code generator based on handlebars templating.
Documentation
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
use crate::helpers::handlebars_ext::HandlebarsExt;
use crate::helpers::string_ext::StringExt;
use handlebars::{BlockContext, HelperDef, RenderError, Renderable, StringOutput};
use serde_json::Value;

pub const TRIM_HELPER: &str = "trim";
pub const SPLIT_GET_FIRST_HELPER: &str = "split_get_first";
pub const SPLIT_GET_LAST_HELPER: &str = "split_get_last";
pub const TRIM_START_HELPER: &str = "trim_start";
pub const TRIM_END_HELPER: &str = "trim_end";
pub const START_WITH_HELPER: &str = "start_with";
pub const WITH_MATCHING_HELPER: &str = "with_matching";
pub const IF_ARRAY_CONTAINS: &str = "if_array_contains";
pub const EACH_WITH_SORT_HELPER: &str = "each_with_sort";
pub const TRIM_BLOCK_HELPER: &str = "trim_block";
pub const TRIM_BLOCK_START_HELPER: &str = "trim_block_start";
pub const TRIM_BLOCK_END_HELPER: &str = "trim_block_end";
pub const ONE_LINE_HELPER: &str = "one_line";
pub const NO_EMPTY_LINES_HELPER: &str = "no_empty_lines";
/// Returns a string slice with leading and trailing whitespace removed.
/// ```
/// # use codegenr_lib::helpers::*;
/// # use serde_json::json;
/// assert_eq!(
///   exec_template(json!({ "value": " test " }), "{{trim value}}"),
///   "test"
/// );
/// assert_eq!(
///   exec_template(json!({ "value": "-test-" }), "{{trim value \"-\"}}"),
///   "test"
/// );
/// ```
pub struct TrimHelper;

impl HelperDef for TrimHelper {
  fn call_inner<'reg: 'rc, 'rc>(
    &self,
    h: &handlebars::Helper<'reg, 'rc>,
    _: &'reg handlebars::Handlebars<'reg>,
    _: &'rc handlebars::Context,
    _: &mut handlebars::RenderContext<'reg, 'rc>,
  ) -> Result<handlebars::ScopedJson<'reg, 'rc>, handlebars::RenderError> {
    h.ensure_arguments_count_min(1, TRIM_HELPER)?;
    h.ensure_arguments_count_max(2, TRIM_HELPER)?;

    let to_trim = h.get_param_as_str_or_fail(0, TRIM_HELPER)?.to_string();
    let trimmer = h.get_param_as_str(1).map(|s| s.to_string());

    Ok(Value::String(to_trim.trim_char(trimmer)).into())
  }
}

/// Return the first part of a String splited by a definable parameter ('/' by default)
///
/// ```
/// # use codegenr_lib::helpers::*;
/// # use serde_json::json;
/// assert_eq!(
///   exec_template(json!({ "temp": "test/value" }), "{{split_get_first temp}}"),
///   "test"
/// );
///  assert_eq!(
///   exec_template(json!({ "temp": "-test-123-" }), "{{split_get_first temp \"-\"}}"),
///   "test"
/// );
///
/// ```
pub struct SplitGetFirstHelper;

impl HelperDef for SplitGetFirstHelper {
  fn call_inner<'reg: 'rc, 'rc>(
    &self,
    h: &handlebars::Helper<'reg, 'rc>,
    _: &'reg handlebars::Handlebars<'reg>,
    _: &'rc handlebars::Context,
    _: &mut handlebars::RenderContext<'reg, 'rc>,
  ) -> Result<handlebars::ScopedJson<'reg, 'rc>, handlebars::RenderError> {
    h.ensure_arguments_count_min(1, SPLIT_GET_FIRST_HELPER)?;
    h.ensure_arguments_count_max(2, SPLIT_GET_FIRST_HELPER)?;

    let to_split = h.get_param_as_str_or_fail(0, SPLIT_GET_FIRST_HELPER)?;
    let splitter = h.get_param_as_str(1).map(|s| s.to_string());

    Ok(handlebars::ScopedJson::Derived(Value::String(to_split.split_get_first(splitter))))
  }
}

/// Return the last value of a String splited by a definable parameter ('/' by default)
///
/// ```
/// # use codegenr_lib::helpers::*;
/// # use serde_json::json;
/// assert_eq!(
///   exec_template(json!({ "temp": "test/value" }), "{{split_get_last temp}}"),
///   "value"
/// );
///  assert_eq!(
///   exec_template(json!({ "temp": "-test-123-" }), "{{split_get_last temp \"-\"}}"),
///   "123"
/// );
/// ```
pub struct SplitGetLastHelper;

impl HelperDef for SplitGetLastHelper {
  fn call_inner<'reg: 'rc, 'rc>(
    &self,
    h: &handlebars::Helper<'reg, 'rc>,
    _: &'reg handlebars::Handlebars<'reg>,
    _: &'rc handlebars::Context,
    _: &mut handlebars::RenderContext<'reg, 'rc>,
  ) -> Result<handlebars::ScopedJson<'reg, 'rc>, handlebars::RenderError> {
    h.ensure_arguments_count_min(1, SPLIT_GET_LAST_HELPER)?;
    h.ensure_arguments_count_max(2, SPLIT_GET_LAST_HELPER)?;

    let to_split = h.get_param_as_str_or_fail(0, SPLIT_GET_LAST_HELPER)?;
    let splitter = h.get_param_as_str(1).map(|s| s.to_string());

    Ok(handlebars::ScopedJson::Derived(Value::String(to_split.split_get_last(splitter))))
  }
}

/// Return a string trim only at the beggining by a definable parameter (' ' by default)
///
/// ```
/// # use codegenr_lib::helpers::*;
/// # use serde_json::json;
/// assert_eq!(
///   exec_template(json!({ "temp": " test " }), "{{trim_start temp}}"),
///   "test "
/// );
/// assert_eq!(
///   exec_template(json!({ "temp": "/test/" }), "{{trim_start temp \"/\"}}"),
///   "test/"
/// );
/// ```
pub struct TrimStartHelper;

impl HelperDef for TrimStartHelper {
  fn call_inner<'reg: 'rc, 'rc>(
    &self,
    h: &handlebars::Helper<'reg, 'rc>,
    _: &'reg handlebars::Handlebars<'reg>,
    _: &'rc handlebars::Context,
    _: &mut handlebars::RenderContext<'reg, 'rc>,
  ) -> Result<handlebars::ScopedJson<'reg, 'rc>, handlebars::RenderError> {
    h.ensure_arguments_count_min(1, TRIM_START_HELPER)?;
    h.ensure_arguments_count_max(2, TRIM_START_HELPER)?;

    let to_trim = h.get_param_as_str_or_fail(0, TRIM_START_HELPER)?;
    let splitter = h.get_param_as_str(1).map(|s| s.to_string());
    Ok(handlebars::ScopedJson::Derived(Value::String(to_trim.trim_start_char(splitter))))
  }
}

/// Return a string trim only at the end by a definable parameter (' ' by default)
///
/// ```
/// # use codegenr_lib::helpers::*;
/// # use serde_json::json;
/// assert_eq!(
///   exec_template(json!({ "temp": " test " }), "{{trim_end temp}}"),
///   " test"
/// );
/// assert_eq!(
///   exec_template(json!({ "temp": "/test/" }), "{{trim_end temp \"/\"}}"),
///   "/test"
/// );
/// ```
pub struct TrimEndHelper;

impl HelperDef for TrimEndHelper {
  fn call_inner<'reg: 'rc, 'rc>(
    &self,
    h: &handlebars::Helper<'reg, 'rc>,
    _: &'reg handlebars::Handlebars<'reg>,
    _: &'rc handlebars::Context,
    _: &mut handlebars::RenderContext<'reg, 'rc>,
  ) -> Result<handlebars::ScopedJson<'reg, 'rc>, handlebars::RenderError> {
    h.ensure_arguments_count_min(1, TRIM_START_HELPER)?;
    h.ensure_arguments_count_max(2, TRIM_START_HELPER)?;

    let to_trim = h.get_param_as_str_or_fail(0, TRIM_END_HELPER)?;
    let splitter = h.get_param_as_str(1).map(|s| s.to_string());
    Ok(handlebars::ScopedJson::Derived(Value::String(to_trim.trim_end_char(splitter))))
  }
}

/// Determines whether the beginning of the second argumentmatches the second one
///```
/// # use codegenr_lib::helpers::*;
/// # use serde_json::json;
/// assert_eq!(
///   exec_template(json!({"one": "test-one", "two": "one-test"}), r#"{{#start_with "test" one}}OK{{else}}{{/start_with}}"#),
///   "OK"
/// );
/// assert_eq!(
///   exec_template(json!({"one": "test-one", "two": "one-test"}), r#"{{#start_with "test" two}}OK{{else}}NOK{{/start_with}}"#),
///   "NOK"
/// );
///```
pub struct StartWithHelper;

impl HelperDef for StartWithHelper {
  fn call<'reg: 'rc, 'rc>(
    &self,
    h: &handlebars::Helper<'reg, 'rc>,
    handle: &'reg handlebars::Handlebars<'reg>,
    ctx: &'rc handlebars::Context,
    render_ctx: &mut handlebars::RenderContext<'reg, 'rc>,
    out: &mut dyn handlebars::Output,
  ) -> handlebars::HelperResult {
    h.ensure_arguments_count(2, START_WITH_HELPER)?;
    let start = h.get_param_as_str_or_fail(0, START_WITH_HELPER)?;
    let with = h.get_param_as_str_or_fail(1, START_WITH_HELPER)?;

    let temp = if with.starts_with(start) { h.template() } else { h.inverse() };
    if let Some(t) = temp {
      t.render(handle, ctx, render_ctx, out)?
    };
    Ok(())
  }
}

/// Execute the inner template with the matching parameter, when matching key is equal to the first parameter
/// {{#with_matching some_value matching_key1 context1 mateching_key2 context2 ... }}
/// Render the inverse template if no matching key was found
///```
/// # use codegenr_lib::helpers::*;
/// # use serde_json::json;
///
/// assert_eq!(
///   exec_template(json!({}), r#"{{#with_matching "test" "1" "1" "2" "2"}}{{else}}NOT FOUND{{/with_matching}}"#),
///   "NOT FOUND"
/// );
/// assert_eq!(
///   exec_template(json!({}), r#"{{#with_matching "2" "1" "01" "2" "02"}}{{this}}{{else}}NOT FOUND{{/with_matching}}"#),
///   "02"
/// );
/// assert_eq!(
///   exec_template(json!({ "value": "42" }), r#"{{#with_matching value "42" "toto"}}{{this}}{{else}}NOT FOUND{{/with_matching}}"#),
///   "toto"
/// );
/// assert_eq!(
///   exec_template(json!({ "value": "42" }), r#"{{#with_matching value "43" "toto"}}{{this}}{{else}}NOT FOUND{{/with_matching}}"#),
///   "NOT FOUND"
/// );
/// assert_eq!(
///   exec_template(json!({ "value": "42" }), r#"{{#with_matching value "42" "toto"}}{{this}}{{else}}NOT FOUND{{/with_matching}}_and_{{value}}"#),
///   "toto_and_42"
/// );
///```
pub struct WithMatchingHelper;

impl HelperDef for WithMatchingHelper {
  fn call<'reg: 'rc, 'rc>(
    &self,
    h: &handlebars::Helper<'reg, 'rc>,
    handle: &'reg handlebars::Handlebars<'reg>,
    ctx: &'rc handlebars::Context,
    render_ctx: &mut handlebars::RenderContext<'reg, 'rc>,
    out: &mut dyn handlebars::Output,
  ) -> handlebars::HelperResult {
    h.ensure_arguments_count_min(3, WITH_MATCHING_HELPER)?;
    let arguments_count = h.params().len();
    if arguments_count % 2 != 1 {
      return Err(RenderError::new(format!(
        "Arguments number for the `{}` helper must be an odd number.",
        WITH_MATCHING_HELPER
      )));
    }

    let key = h.get_param_as_json_or_fail(0, WITH_MATCHING_HELPER)?;

    let mut pair_position = 1;
    while pair_position < arguments_count {
      let match_key = h.get_param_as_json_or_fail(pair_position, WITH_MATCHING_HELPER)?;
      // todo: for strings, be case insensitive : value.to_lowercase() == match_key.unwrap().to_lowercase()
      if key == match_key {
        if let Some(t) = h.template() {
          let match_value = h.get_param_as_json_or_fail(pair_position + 1, WITH_MATCHING_HELPER)?;
          let mut block = BlockContext::new();
          block.set_base_value(match_value.clone());
          render_ctx.push_block(block);
          t.render(handle, ctx, render_ctx, out)?;
          render_ctx.pop_block();
        };
        return Ok(());
      }
      pair_position += 2;
    }

    if let Some(t) = h.inverse() {
      t.render(handle, ctx, render_ctx, out)?
    };
    Ok(())
  }
}

/// Write the template if the second argument is found in the array passed as first argument
/// (values are compared with string insensitive comparison)
/// (Pas completement fonctionnelle)
///```
/// # use codegenr_lib::helpers::*;
/// # use serde_json::json;
/// let json_array = json!({ "type": "object", "required": [ "errorMeSSage", "test" ], "properties": {"errorMessage": {"type": "string"}, "non_required_prop" : {"type" : "int"}}});
/// assert_eq!(
///   exec_template(json_array.clone(), r#"{{#if_array_contains required "errorMeSSage"}}OK{{else}}NOK{{/if_array_contains}}"#),
///   "OK"
/// );
/// //assert_eq!(
///   //exec_template(json_array.clone(), r#"{{#if_array_contains required "errormessage"}}OK{{else}}NOK{{/if_array_contains}}"#),
///   //"OK"
/// //);
/// assert_eq!(
///   exec_template(json_array.clone(), r#"{{#if_array_contains required "test"}}OK{{else}}NOK{{/if_array_contains}}"#),
///   "OK"
/// );
/// assert_eq!(
///   exec_template(json_array.clone(), r#"{{#if_array_contains required "notFound"}}OK{{else}}NOK{{/if_array_contains}}"#),
///   "NOK"
/// );
///```
pub struct IfArrayContainsHelper;

impl HelperDef for IfArrayContainsHelper {
  fn call<'reg: 'rc, 'rc>(
    &self,
    h: &handlebars::Helper<'reg, 'rc>,
    handle: &'reg handlebars::Handlebars<'reg>,
    ctx: &'rc handlebars::Context,
    render_ctx: &mut handlebars::RenderContext<'reg, 'rc>,
    out: &mut dyn handlebars::Output,
  ) -> handlebars::HelperResult {
    h.ensure_arguments_count(2, IF_ARRAY_CONTAINS)?;
    let value = h.get_param_as_array_or_fail(0, IF_ARRAY_CONTAINS)?;
    let key = h.get_param_as_json_or_fail(1, IF_ARRAY_CONTAINS)?;

    // todo: compare case insensitive when both strings
    let is_value_found = value.iter().any(|s| s == key);
    let temp = if is_value_found { h.template() } else { h.inverse() };

    if let Some(t) = temp {
      t.render(handle, ctx, render_ctx, out)?
    };
    Ok(())
  }
}

/// Trim start and end of a block output
/// (all arguments are converted to string and case insensitive compared)
///```
/// # use codegenr_lib::helpers::*;
/// # use serde_json::json;
/// assert_eq!(
///   exec_template(json!({}), r#"{{#trim_block " "}} 1,2,3,4 {{/trim_block}}"#),
///   "1,2,3,4"
/// );
/// assert_eq!(
///   exec_template(json!({}), r#"{{#trim_block ","}}1,2,3,4{{/trim_block}}"#),
///   "1,2,3,4"
/// );
/// assert_eq!(
///   exec_template(json!({}), r#"{{#trim_block ","}}1,2,3,4,{{/trim_block}}"#),
///   "1,2,3,4"
/// );
/// assert_eq!(
///   exec_template(json!({}), r#"{{#trim_block ","}},1,2,3,4,{{/trim_block}}"#),
///   "1,2,3,4"
/// );
/// assert_eq!(
///   exec_template(json!({}), r#"{{#trim_block ","}},,1,2,3,4,,{{/trim_block}}"#),
///   "1,2,3,4"
/// );
/// assert_eq!(
///   exec_template(json!({"a": "42", "b": "42", "c": "42"}), r#"{{#trim_block ","}}{{#each this}}{{@key}},{{/each}}{{/trim_block}}"#),
///   "a,b,c"
/// );
///```
pub struct TrimBlockHelper;

impl HelperDef for TrimBlockHelper {
  fn call<'reg: 'rc, 'rc>(
    &self,
    h: &handlebars::Helper<'reg, 'rc>,
    handle: &'reg handlebars::Handlebars<'reg>,
    ctx: &'rc handlebars::Context,
    render_ctx: &mut handlebars::RenderContext<'reg, 'rc>,
    out: &mut dyn handlebars::Output,
  ) -> handlebars::HelperResult {
    if let Some(t) = h.template() {
      let mut buffer = StringOutput::new();
      t.render(handle, ctx, render_ctx, &mut buffer)?;
      let s = buffer.into_string()?;
      let trimmer = h.get_param_as_str(0).map(|s| s.to_string());

      out.write(&s.trim_char(trimmer))?;
    };

    Ok(())
  }
}

/// Trim start of a block output
/// (all arguments are converted to string and case insensitive compared)
///```
/// # use codegenr_lib::helpers::*;
/// # use serde_json::json;
/// assert_eq!(
///   exec_template(json!({}), r#"{{#trim_block_start}} 1,2,3,4 {{/trim_block_start}}"#),
///   "1,2,3,4 "
/// );
/// assert_eq!(
///   exec_template(json!({}), r#"{{#trim_block_start ","}}1,2,3,4{{/trim_block_start}}"#),
///   "1,2,3,4"
/// );
/// assert_eq!(
///   exec_template(json!({}), r#"{{#trim_block_start ","}}1,2,3,4,{{/trim_block_start}}"#),
///   "1,2,3,4,"
/// );
/// assert_eq!(
///   exec_template(json!({}), r#"{{#trim_block_start ","}},1,2,3,4,{{/trim_block_start}}"#),
///   "1,2,3,4,"
/// );
/// assert_eq!(
///   exec_template(json!({}), r#"{{#trim_block_start ","}},,1,2,3,4,,{{/trim_block_start}}"#),
///   "1,2,3,4,,"
/// );
/// assert_eq!(
///   exec_template(json!({"a": "42", "b": "42", "c": "42"}), r#"{{#trim_block_start ","}}{{#each this}}{{@key}},{{/each}}{{/trim_block_start}}"#),
///   "a,b,c,"
/// );
///```
pub struct TrimBlockStartHelper;

impl HelperDef for TrimBlockStartHelper {
  fn call<'reg: 'rc, 'rc>(
    &self,
    h: &handlebars::Helper<'reg, 'rc>,
    handle: &'reg handlebars::Handlebars<'reg>,
    ctx: &'rc handlebars::Context,
    render_ctx: &mut handlebars::RenderContext<'reg, 'rc>,
    out: &mut dyn handlebars::Output,
  ) -> handlebars::HelperResult {
    if let Some(t) = h.template() {
      let mut buffer = StringOutput::new();
      t.render(handle, ctx, render_ctx, &mut buffer)?;
      let s = buffer.into_string()?;
      let trimmer = h.get_param_as_str(0).map(|s| s.to_string());

      out.write(&s.trim_start_char(trimmer))?;
    };

    Ok(())
  }
}

/// Trim end of a block output
/// (all arguments are converted to string and case insensitive compared)
///```
/// # use codegenr_lib::helpers::*;
/// # use serde_json::json;
/// assert_eq!(
///   exec_template(json!({}), r#"{{#trim_block_end " "}} 1,2,3,4 {{/trim_block_end}}"#),
///   " 1,2,3,4"
/// );
/// assert_eq!(
///   exec_template(json!({}), r#"{{#trim_block_end ","}}1,2,3,4{{/trim_block_end}}"#),
///   "1,2,3,4"
/// );
/// assert_eq!(
///   exec_template(json!({}), r#"{{#trim_block_end ","}}1,2,3,4,{{/trim_block_end}}"#),
///   "1,2,3,4"
/// );
/// assert_eq!(
///   exec_template(json!({}), r#"{{#trim_block_end ","}},1,2,3,4,{{/trim_block_end}}"#),
///   ",1,2,3,4"
/// );
/// assert_eq!(
///   exec_template(json!({}), r#"{{#trim_block_end ","}},,1,2,3,4,,{{/trim_block_end}}"#),
///   ",,1,2,3,4"
/// );
/// assert_eq!(
///   exec_template(json!({"a": "42", "b": "42", "c": "42"}), r#"{{#trim_block_end ","}}{{#each this}}{{@key}},{{/each}}{{/trim_block_end}}"#),
///   "a,b,c"
/// );
///```
pub struct TrimBlockEndHelper;

impl HelperDef for TrimBlockEndHelper {
  fn call<'reg: 'rc, 'rc>(
    &self,
    h: &handlebars::Helper<'reg, 'rc>,
    handle: &'reg handlebars::Handlebars<'reg>,
    ctx: &'rc handlebars::Context,
    render_ctx: &mut handlebars::RenderContext<'reg, 'rc>,
    out: &mut dyn handlebars::Output,
  ) -> handlebars::HelperResult {
    if let Some(t) = h.template() {
      let mut buffer = StringOutput::new();
      t.render(handle, ctx, render_ctx, &mut buffer)?;
      let s = buffer.into_string()?;
      let trimmer = h.get_param_as_str(0).map(|s| s.to_string());
      out.write(&s.trim_end_char(trimmer))?;
    };

    Ok(())
  }
}

/// Trim end of a block output
/// (all arguments are converted to string and case insensitive compared)
///```
/// # use codegenr_lib::helpers::*;
/// # use serde_json::json;
/// assert_eq!(
///   exec_template(json!({}), "{{#one_line}} {{/one_line}}"),
///   "\n"
/// );
/// assert_eq!(
///   exec_template(json!({}), "{{#one_line}} |do not < remove please >| {{/one_line}}"),
///   "|do not < remove please >|\n"
/// );
/// assert_eq!(
///   exec_template(json!({}), "{{#one_line}} \n {{/one_line}}"),
///   "\n"
/// );
/// assert_eq!(
///   exec_template(json!({}), "{{#one_line}}\n {{/one_line}}"),
///   "\n"
/// );
/// assert_eq!(
///   exec_template(json!({}), "{{#one_line}}\n{{/one_line}}"),
///   "\n"
/// );
/// assert_eq!(
///   exec_template(json!({}), "{{#one_line}} \r\n {{/one_line}}"),
///   "\n"
/// );
/// assert_eq!(
///   exec_template(json!({}), "{{#one_line}}\r\n{{/one_line}}"),
///   "\n"
/// );
/// assert_eq!(
///   exec_template(json!({}), "{{#one_line}} test{{/one_line}}"),
///   "test\n"
/// );
/// assert_eq!(
///   exec_template(json!({}), "{{#one_line}} a \n z {{/one_line}}"),
///   "az\n"
/// );
/// assert_eq!(
///   exec_template(json!({}), "{{#one_line}}a\n z{{/one_line}}"),
///   "az\n"
/// );
/// assert_eq!(
///   exec_template(json!({}), "{{#one_line}}a\nz{{/one_line}}"),
///   "az\n"
/// );
/// assert_eq!(
///   exec_template(json!({}), "{{#one_line}}a \r\n z{{/one_line}}"),
///   "az\n"
/// );
/// assert_eq!(
///   exec_template(json!({}), "{{#one_line}}a \r\n \r\n \r\nz{{/one_line}}"),
///   "az\n"
/// );
/// assert_eq!(
///   exec_template(json!({}), "{{#one_line 2 true \"-\"}}a \r\n \r\n \r\nz{{/one_line}}"),
///   "  a---z\n"
/// );
/// assert_eq!(
///   exec_template(json!({}), "{{#one_line}}test\r\n\r\n\r\ntest{{/one_line}}"),
///   "testtest\n"
/// );
/// assert_eq!(
///   exec_template(json!({}), "{{#one_line 0 \"true\"}}test\r\n\r\n\r\ntest{{/one_line}}"),
///  "testtest\n"
/// );
/// assert_eq!(
///   exec_template(json!({}), "{{#one_line 0 false}}test\r\n\r\n\r\ntest{{/one_line}}"),
///   "testtest"
/// );
/// assert_eq!(
///   exec_template(json!({}), "{{#one_line}}{{/one_line}}"),
///   "\n"
/// );
/// assert_eq!(
///   exec_template(json!({}), "{{#one_line}}   test {{/one_line}}"),
/// "test\n"
/// );
/// assert_eq!(
///   exec_template(json!({}), "{{#one_line 5}}test{{/one_line}}"),
/// "     test\n"
/// );
///```
pub struct OneLineHelper;

impl HelperDef for OneLineHelper {
  fn call<'reg: 'rc, 'rc>(
    &self,
    h: &handlebars::Helper<'reg, 'rc>,
    handle: &'reg handlebars::Handlebars<'reg>,
    ctx: &'rc handlebars::Context,
    render_ctx: &mut handlebars::RenderContext<'reg, 'rc>,
    out: &mut dyn handlebars::Output,
  ) -> handlebars::HelperResult {
    if let Some(t) = h.template() {
      h.ensure_arguments_count_max(3, ONE_LINE_HELPER)?;
      let mut buffer = StringOutput::new();
      t.render(handle, ctx, render_ctx, &mut buffer)?;
      let s = buffer.into_string()?;
      let indent = h.get_param_as_integer(0);
      let line_break = h.get_param_as_bool(1);
      let replacer = h.get_param_as_str(2);
      out.write(&s.on_one_line(indent, line_break, replacer))?;
    };

    Ok(())
  }
}

/// Removes empty lines from the block
///```
/// # use codegenr_lib::helpers::*;
/// # use serde_json::json;
/// assert_eq!(
///   exec_template(json!({}), "{{#no_empty_lines}}{{/no_empty_lines}}"),
///   ""
/// );
/// assert_eq!(
///   exec_template(json!({}), "{{#no_empty_lines}} {{/no_empty_lines}}"),
///   "\n"
/// );
/// assert_eq!(
///   exec_template(json!({}), "{{#no_empty_lines}}a\n \t \n b {{/no_empty_lines}}"),
///   "a\n b \n"
/// );
/// assert_eq!(
///   exec_template(json!({}), "{{#no_empty_lines}}\r\na\n \t \nb\r\nc\r\n\r\n{{/no_empty_lines}}"),
///   "a\nb\nc\n"
/// );
///```
pub struct NoEmptyLinesHelper;

impl HelperDef for NoEmptyLinesHelper {
  fn call<'reg: 'rc, 'rc>(
    &self,
    h: &handlebars::Helper<'reg, 'rc>,
    handle: &'reg handlebars::Handlebars<'reg>,
    ctx: &'rc handlebars::Context,
    render_ctx: &mut handlebars::RenderContext<'reg, 'rc>,
    out: &mut dyn handlebars::Output,
  ) -> handlebars::HelperResult {
    if let Some(t) = h.template() {
      h.ensure_arguments_count_max(2, ONE_LINE_HELPER)?;
      let mut buffer = StringOutput::new();
      t.render(handle, ctx, render_ctx, &mut buffer)?;
      let content = buffer.into_string()?;

      let mut non_empty_lines_count: usize = 0;
      let mut empty_lines_count: usize = 0;
      for line in content.lines() {
        let is_empty = line.trim().is_empty();
        let (should_write_line, should_right_newline) = match (non_empty_lines_count, empty_lines_count, is_empty) {
          (0, 0, true) => (false, true),
          (_, _, true) => (false, false),
          (_, _, false) => (true, true),
        };
        if should_write_line {
          out.write(line)?;
        }
        if should_right_newline {
          out.write("\n")?;
        }
        if is_empty {
          non_empty_lines_count += 1;
        } else {
          empty_lines_count += 1;
        }
      }
    };
    Ok(())
  }
}

///// Trim end of a block output
///// (all arguments are converted to string and case insensitive compared)
/////```
///// # use codegenr_lib::helpers::*;
///// # use serde_json::json;
///// assert_eq!(
/////   exec_template(json!([{"t": "c"}, {"t": "a"}, {"t": "b"}]), r#"{{#each this}}{{t}}{{/each}}"#),
/////   "cab"
///// );
///// assert_eq!(
/////   exec_template(json!([{"t": "c"}, {"t": "a"}, {"t": "b"}]), r#"{{#each_with_sort this "t/a/"}}{{t}}{{/each_with_sort}}"#),
/////   "abc"
///// );
///// assert_eq!(
/////   exec_template(json!([{t: 'c'}, {t: 'a'}, {t: 'b'}]), r#"{{#each_with_sort . 't'}}{{#each .}}{{t}}{{/each}}{{/each_with_sort}}"#),
/////   "abc"
///// );
///// assert_eq!(
/////   exec_template(json!({[]}), r#"{{#each_with_sort . .}}{{/each_with_sort}}"#),
/////   ""
///// );
///// assert_eq!(
/////   exec_template(json!({ a : {}, b : {} }), r#"{{#each_with_sort .}}{{#each .}}{{@key}}{{/each}}{{/each_with_sort}}"#),
/////   "ab"
///// );
///// assert_eq!(
/////   exec_template(json!({ b : {}, a : {} }), r#"{{#each_with_sort .}}{{#each .}}{{@key}}{{/each}}{{/each_with_sort}}"#),
/////   "ab"
///// );
///// assert_eq!(
/////   exec_template(json!({\r\n{\r\n "swagger": "2.0",\r\n "info": {\r\n "title": "Marketplace Gateway API - Feeds",\r\n ...), r#"{{#each_with_sort parameters}}{{#each .}}{{@key}},{{/each}}{{/each_with_sort}}"#),
/////   "accountIdParameter,credentialParameter,feedTypeParameter,marketplaceBusinessCodeParameter,publicationIdParameter,"
///// );
/////```
// #[derive(Clone, Copy)]
// pub struct EachWithSortHelper;

// /*

//  FULL =  { data: { t: { a: "b" }, ttt: [ 42 ]  }}

//   {{#each data}}    ScopedJson:Context (FULL, vec!())
//     {{#with t}}     ScopedJson:Context (FULL, vec!("data/0"))
//       {{../ttt}}    ScopedJson:Derived ({ a: "b" }, vec!())
//     {{/with}}
//   {{/each}}

// */
// impl HelperDef for EachWithSortHelper {
//   fn call<'reg: 'rc, 'rc>(
//     &self,
//     h: &Helper<'reg, 'rc>,
//     r: &'reg handlebars::Handlebars<'reg>,
//     ctx: &'rc handlebars::Context,
//     rc: &mut handlebars::RenderContext<'reg, 'rc>,
//     out: &mut dyn handlebars::Output,
//   ) -> handlebars::HelperResult {
//     let value = h.param(0).ok_or_else(|| RenderError::new("Param not found for helper \"each\""))?;
//     let j_path = h.get_param_as_str(1).unwrap_or("");

//     let template = h.template();

//     match template {
//       Some(t) => match *value.value() {
//         Value::Array(ref list) if !list.is_empty() || (list.is_empty() && h.inverse().is_none()) => {
//           let mut to_sort = list.clone();

//           to_sort.sort_by(|a, b| {
//             todo!("Find a way !!");
//             std::cmp::Ordering::Greater
//           });

//           let block_context = create_block(value);
//           rc.push_block(block_context);

//           let len = list.len();

//           let array_path = value.context_path();

//           for (i, v) in to_sort.iter().enumerate().take(len) {
//             if let Some(ref mut block) = rc.block_mut() {
//               let is_first = i == 0usize;
//               let is_last = i == len - 1;

//               let index = to_json(i);
//               block.set_local_var("first", to_json(is_first));
//               block.set_local_var("last", to_json(is_last));
//               block.set_local_var("index", index.clone());

//               update_block_context(block, array_path, i.to_string(), is_first, v);
//               set_block_param(block, h, array_path, &index, v)?;
//             }

//             t.render(r, ctx, rc, out)?;
//           }

//           rc.pop_block();
//           Ok(())
//         }
//         Value::Object(ref obj) if !obj.is_empty() || (obj.is_empty() && h.inverse().is_none()) => {
//           let block_context = create_block(value);
//           rc.push_block(block_context);

//           let len = obj.len();

//           let obj_path = value.context_path();

//           for (i, (k, v)) in obj.iter().enumerate() {
//             if let Some(ref mut block) = rc.block_mut() {
//               let is_first = i == 0usize;
//               let is_last = i == len - 1;

//               let key = to_json(k);
//               block.set_local_var("first", to_json(is_first));
//               block.set_local_var("last", to_json(is_last));
//               block.set_local_var("key", key.clone());

//               update_block_context(block, obj_path, k.to_string(), is_first, v);
//               set_block_param(block, h, obj_path, &key, v)?;
//             }

//             t.render(r, ctx, rc, out)?;
//           }

//           rc.pop_block();
//           Ok(())
//         }
//         _ => {
//           if let Some(else_template) = h.inverse() {
//             else_template.render(r, ctx, rc, out)
//           } else if r.strict_mode() {
//             Err(RenderError::strict_error(value.relative_path()))
//           } else {
//             Ok(())
//           }
//         }
//       },
//       None => Ok(()),
//     }
//   }
// }

// fn update_block_context<'reg>(
//   block: &mut BlockContext<'reg>,
//   base_path: Option<&Vec<String>>,
//   relative_path: String,
//   is_first: bool,
//   value: &Value,
// ) {
//   if let Some(p) = base_path {
//     if is_first {
//       *block.base_path_mut() = copy_on_push_vec(p, relative_path);
//     } else if let Some(ptr) = block.base_path_mut().last_mut() {
//       *ptr = relative_path;
//     }
//   } else {
//     block.set_base_value(value.clone());
//   }
// }

// fn set_block_param<'reg: 'rc, 'rc>(
//   block: &mut BlockContext<'reg>,
//   h: &Helper<'reg, 'rc>,
//   base_path: Option<&Vec<String>>,
//   k: &Value,
//   v: &Value,
// ) -> Result<(), RenderError> {
//   if let Some(bp_val) = h.block_param() {
//     let mut params = BlockParams::new();
//     if base_path.is_some() {
//       params.add_path(bp_val, Vec::with_capacity(0))?;
//     } else {
//       params.add_value(bp_val, v.clone())?;
//     }

//     block.set_block_params(params);
//   } else if let Some((bp_val, bp_key)) = h.block_param_pair() {
//     let mut params = BlockParams::new();
//     if base_path.is_some() {
//       params.add_path(bp_val, Vec::with_capacity(0))?;
//     } else {
//       params.add_value(bp_val, v.clone())?;
//     }
//     params.add_value(bp_key, k.clone())?;

//     block.set_block_params(params);
//   }

//   Ok(())
// }

// pub fn create_block<'reg: 'rc, 'rc>(param: &'rc PathAndJson<'reg, 'rc>) -> BlockContext<'reg> {
//   let mut block = BlockContext::new();

//   if let Some(new_path) = param.context_path() {
//     *block.base_path_mut() = new_path.clone();
//   } else {
//     // use clone for now
//     block.set_base_value(param.value().clone());
//   }

//   block
// }

// fn copy_on_push_vec<T>(input: &[T], el: T) -> Vec<T>
// where
//   T: Clone,
// {
//   let mut new_vec = Vec::with_capacity(input.len() + 1);
//   new_vec.extend_from_slice(input);
//   new_vec.push(el);
//   new_vec
// }