rustache 0.1.0

Mustache templating engine for rust
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
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
use std::path::Path;
use std::fs;
use std::fs::File;
use std::io::{Read, Write};

use compiler;
use parser;
use parser::Node;
use parser::Node::{Value, Static, Unescaped, Section, Part};
use Data;
use Data::{Strng, Bool, Integer, Float, Vector, Hash, Lambda};
use build::HashBuilder;
use std::collections::HashMap;

use RustacheResult;
use RustacheError::TemplateErrorType;
use self::TemplateError::*;

pub struct Template {
    partials_path: String,
}

#[derive(Debug)]
pub enum TemplateError {
    StreamWriteError(String),
    FileReadError(String),
    UnexpectedDataType(String),
    UnexpectedNodeType(String),
}

impl Template {
    pub fn new() -> Template {
        Template { partials_path: String::new() }
    }

    // utility method to write out rendered template with error handling
    fn write_to_stream<W: Write>(&self,
                                 writer: &mut W,
                                 data: &str,
                                 errstr: &str)
                                 -> RustacheResult<()> {
        writer.write_fmt(format_args!("{}", &data[..])).map_err(|e| {
            let msg = format!("{}: {}", e, errstr);
            TemplateErrorType(StreamWriteError(msg))
        })
    }

    // method to escape HTML for default value tags
    fn escape_html(&self, input: &str) -> String {
        input.chars().map(|c| {
            match c {
                '<' => {
                    "&lt;".into()
                }
                '>' => {
                    "&gt;".into()
                }
                '&' => {
                    "&amp;".into()
                }
                '"' => {
                    "&quot;".into()
                }
                _ => {
                    c.to_string()
                }
            }
        }).collect()
    }

    // key:       the key we're looking for
    // sections:  an array of the nested sections to look through, e.g. [e, d, c, b, a]
    // datastore: the hash of the data to search for key in
    //
    // TODO: handle vector data for real, change to not build vector, but
    // iterate the same way until data is found
    //
    fn look_up_section_data<'a, 'b>(&self,
                                    key: &str,
                                    sections: &[String],
                                    datastore: &'b HashMap<String, Data<'a>>)
                                    -> Option<&'b Data<'a>> {
        let mut rv = None;
        let mut hashes = Vec::new();
        let mut hash = datastore;


        // any kind of tag may be in a nested section, in which case it's data
        // may be in a context further up, so we have to have a way to search
        // up those contexts for a value for some key.
        //
        // so a template of {{#a}}{{#b}}{{#c}}{{value}}{{/c}}{{/b}}{{/a}}
        // and data of { a: { b: { "value": "foo", c: {}}}
        // we should be able to find "foo" even though it is not under "c"'s data
        //
        // to do this, we look, first through a nested path.  we take the hash
        // found for each section, starting with the most nested to the outside,
        // and push references their sub-hashes onto a vector.
        //
        // so with data of { a: { b: { "value": "foo", c: {"cdata": foo}}}
        // we end up with a vector: [{"cdata":"foo"},
        //                           {"value": "foo", "c": { "cdata": foo }},
        //                           { b: { "value": "foo", c: {"cdata": foo}}]
        for section in sections.iter() {
            if let Some(data) = hash.get(section) {
                if let Hash(ref h) = *data {
                    hashes.insert(0, h);
                    hash = h;
                }
            }
        }

        // data for nested sections may also be in the top level of data,
        // so not only do we have to check up the nested structure, we have
        // to check the top level for each section data
        //
        // so a template of {{#a}}{{#b}}{{#c}}{{value}}{{/c}}{{/b}}{{/a}}
        // and data of { a: {}, b: { "value", "foo"}, c{} }
        // we should be able to find the value "foo"
        //
        // after this, we do the same for the top level datastore.  we need to do it
        // in this order so we look through nested first.
        // so with data { a: {}, b: { "value", "foo"}, c{} }
        // we end up with the previous vector plus: [{}, { "value", "foo"}, {}]
        //
        for section in sections.iter() {
            if let Some(data) = datastore.get(section) {
                match *data {
                    Hash(ref h) => {
                        hashes.insert(0, h);
                    }
                    Vector(_) => {
                        return Some(data);
                    }
                    _ => {}
                }
            }
        }

        // once we've assembled the vector of hashes to look through
        // we iterate through it looking for the data
        for hash in hashes.iter() {

            rv = hash.get(key);
            if rv.is_some() {
                break;
            }
        }

        // last but not least, check the top level if we didn't find anything
        if rv.is_none() {
            rv = datastore.get(key);
        }

        rv
    }

    fn handle_unescaped_lambda_interpolation<W: Write>(&mut self,
                                                       f: &mut FnMut(String) -> String,
                                                       data: &HashMap<String, Data>,
                                                       raw: String,
                                                       writer: &mut W)
                                                       -> RustacheResult<()> {
        let val = (*f)(raw);
        let tokens = compiler::create_tokens(&val[..]);
        let nodes = parser::parse_nodes(&tokens);

        self.render(writer, data, &nodes)
    }

    fn handle_escaped_lambda_interpolation<W: Write>(&mut self,
                                                     f: &mut FnMut(String) -> String,
                                                     data: &HashMap<String, Data>,
                                                     raw: String,
                                                     writer: &mut W)
                                                     -> RustacheResult<()> {
        let val = (*f)(raw);
        let value = self.escape_html(&val[..]);
        let tokens = compiler::create_tokens(&value[..]);
        let nodes = parser::parse_nodes(&tokens);

        self.render(writer, data, &nodes)
    }

    // data:      the data value for the tag/node we're handling
    // key:       the name of the tag we're handling, i.e. the key into the data hash
    // datastore: all the data for the template
    // writer:    the output stream to write rendered template to
    //
    // the Data enum, which is how we hold different types of data in one hash,
    // can be, well, several different types.  this method matches them all and
    // handles the data appropriately.
    //
    // TODO: really don't need to be handling Bool, Vector or Hash
    fn handle_unescaped_or_value_node<W: Write>(&mut self,
                                                node: &Node,
                                                data: &Data,
                                                key: String,
                                                datastore: &HashMap<String, Data>,
                                                writer: &mut W)
                                                -> RustacheResult<()> {
        let mut rv = Ok(());
        let mut tmp: String = String::new();
        match *data {
            // simple value-for-tag exchange, write out the string
            Strng(ref val) => {
                match *node {
                    Unescaped(_, _) => tmp = tmp + val,
                    Value(_, _) => tmp = self.escape_html(&val[..]),
                    _ => return Err(TemplateErrorType(UnexpectedNodeType(format!("{:?}", node)))),
                }
                rv = self.write_to_stream(writer, &tmp, "render: unescaped node string fail");
            }
            // TODO: this one doesn't quite make sense.  i don't think we need it.
            Bool(ref val) => {
                if *val {
                    tmp.push_str("true")
                } else {
                    tmp.push_str("false")
                }
                rv = self.write_to_stream(writer, &tmp, "render: unescaped node bool");
            }
            // if the data is an integer, convert it to a string and write that
            Integer(ref val) => {
                tmp = tmp + &val.to_string();
                rv = self.write_to_stream(writer, &tmp, "render: unescaped node int");
            }
            // if the data is a float, convert it to a string and write that
            Float(ref val) => {
                tmp = tmp + &val.to_string();
                rv = self.write_to_stream(writer, &tmp, "render: unescaped node float");
            }
            // TODO: this one doesn't quite make sense.  i don't think we need it.
            Vector(ref list) => {
                for item in list.iter() {
                    try!(self.handle_unescaped_or_value_node(node,
                                                             item,
                                                             key.to_string(),
                                                             datastore,
                                                             writer));
                }
            }
            // TODO: this one doesn't quite make sense.  i don't think we need it.
            Hash(ref hash) => {
                if hash.contains_key(&key) {
                    let tmp = &hash[&key];
                    try!(self.handle_unescaped_or_value_node(node,
                                                             tmp,
                                                             key.to_string(),
                                                             datastore,
                                                             writer));
                }
            }
            // if we have a lambda for the data, the return value of the
            // lambda is what we substitute for the tag
            Lambda(ref f) => {
                let raw = "".to_string();
                match *node {
                    Unescaped(_, _) => {
                        rv = self.handle_unescaped_lambda_interpolation(&mut *f.borrow_mut(),
                                                                        datastore,
                                                                        raw,
                                                                        writer)
                    }
                    Value(_, _) => {
                        rv = self.handle_escaped_lambda_interpolation(&mut *f.borrow_mut(),
                                                                      datastore,
                                                                      raw,
                                                                      writer)
                    }
                    _ => return Err(TemplateErrorType(UnexpectedNodeType(format!("{:?}", node)))),
                }
            }
        }

        rv
    }

    // nodes:     children of the inverted section tag
    // datastore: all the data for the template
    // writer:    the io stream to write the rendered template to
    //
    // inverted nodes only contain static text to render and are only rendered
    // if the data in the template data for the tag name is "falsy"
    //
    fn handle_inverted_node<W: Write>(&mut self,
                                      nodes: &[Node],
                                      datastore: &HashMap<String, Data>,
                                      writer: &mut W)
                                      -> RustacheResult<()> {
        let mut rv = Ok(());
        for node in nodes.iter() {
            match *node {
                Static(key) => {
                    rv =
                        self.write_to_stream(writer,
                                             &key.to_string(),
                                             "render: inverted node static");
                }
                // TODO: this one doesn't quite make sense.  i don't think we need it.
                Part(filename, _) => {
                    rv = self.handle_partial_file_node(filename, datastore, writer);
                }
                Section(key, ref children, ref inverted, _, _) => {
                    let tmp = key.to_string();
                    let truthy = if datastore.contains_key(&tmp) {
                        self.is_section_data_true(&datastore[&tmp])
                    } else {
                        false
                    };
                    match (truthy, *inverted) {
                        (true, true) | (false, false) => {}
                        (true, false) => {
                            let val = &datastore[&tmp];
                            let mut sections = vec![tmp.clone()];
                            rv = self.handle_section_node(children,
                                                          &tmp,
                                                          val,
                                                          datastore,
                                                          &mut sections,
                                                          writer);
                        }
                        (false, true) => {
                            rv = self.handle_inverted_node(children, datastore, writer);
                        }
                    }
                }
                _ => {}
            }
        }

        rv
    }

    // nodes:     the section's children
    // data:      data from section key from HashBuilder store
    // datastore: HashBuilder data
    // writer:    io stream
    fn handle_section_node<W: Write>(&mut self,
                                     nodes: &[Node],
                                     _: &str,
                                     data: &Data,
                                     datastore: &HashMap<String, Data>,
                                     sections: &mut Vec<String>,
                                     writer: &mut W)
                                     -> RustacheResult<()> {
        let mut rv = Ok(());
        // there's a special case if the section tag data was a lambda
        // if so, the lambda is used to generate the values for the tag inside the section
        match *data {
            Lambda(ref f) => {
                let raw = self.get_section_text(nodes);
                return self.handle_unescaped_lambda_interpolation(&mut *f.borrow_mut(),
                                                                  datastore,
                                                                  raw,
                                                                  writer);
            }
            Vector(ref v) => {
                for d in v.iter() {
                    for node in nodes.iter() {
                        match *d {
                            Hash(ref h) => {
                                rv = self.handle_node(node, h, writer);
                            }
                            Strng(ref val) => {
                                return Err(TemplateErrorType(UnexpectedDataType(format!("{}",
                                                                                        val))))
                            }
                            Bool(ref val) => {
                                return Err(TemplateErrorType(UnexpectedDataType(format!("{}",
                                                                                        val))))
                            }
                            Integer(ref val) => {
                                return Err(TemplateErrorType(UnexpectedDataType(format!("{}",
                                                                                        val))))
                            }
                            Float(ref val) => {
                                return Err(TemplateErrorType(UnexpectedDataType(format!("{}",
                                                                                        val))))
                            }
                            Vector(ref val) => {
                                return Err(TemplateErrorType(UnexpectedDataType(format!("{:?}",
                                                                                        val))))
                            }
                            Lambda(_) => {
                                return Err(TemplateErrorType(UnexpectedDataType("lambda"
                                    .to_string())))
                            }
                        }
                    }
                }
                return rv;
            }
            _ => {}
        }

        // in a section tag, there are child tags to fill out,
        // we need to iterate through each one
        for node in nodes.iter() {
            match *node {
                // unescaped is simple, just look up the data in the
                // special way sections need to and handle the node
                Unescaped(key, _) | Value(key, _) => {
                    let tmpkey = key.to_string();
                    let tmpdata = self.look_up_section_data(&tmpkey, sections, datastore);
                    if tmpdata.is_some() {
                        rv = self.handle_unescaped_or_value_node(node,
                                                                 tmpdata.unwrap(),
                                                                 key.to_string(),
                                                                 datastore,
                                                                 writer);
                    }
                }
                // most simple, just write the static data out, nothing to replace
                Static(key) => {
                    rv =
                        self.write_to_stream(writer,
                                             &key.to_string(),
                                             "render: section node static");
                }
                // sections are special and may be inverted
                Section(key, ref children, ref inverted, _, _) => {
                    if !*inverted {
                        // A normal, not inverted tag is more complicated and may recurse
                        // we need to save what sections we have been in, so the data
                        // lookup can happen correctly.  Data lookup is special for sections.
                        let tmpkey = key.to_string();
                        sections.push(tmpkey.clone());
                        let tmpdata = self.look_up_section_data(&tmpkey, sections, datastore);
                        if tmpdata.is_some() {
                            rv = self.handle_section_node(children,
                                                          &tmpkey,
                                                          tmpdata.unwrap(),
                                                          datastore,
                                                          sections,
                                                          writer);
                        }
                    } else {
                        // inverted only has internal static text, so is easy to handle
                        rv = self.handle_inverted_node(children, datastore, writer);
                    }
                }
                // if it's a partial, we have a file to read in and render
                Part(path, _) => {
                    rv = self.handle_partial_file_node(path, datastore, writer);
                }
            }
        }

        rv
    }

    // section data is considered false in a few cases:
    // there is no data for the key in the data hashmap
    // the data is a bool with a value of false
    // the data is an empty vector
    fn is_section_data_true(&self, data: &Data) -> bool {
        match *data {
            // if the data is a bool, rv is just the bool value
            Bool(value) => value,
            Vector(ref vec) => !vec.is_empty(),
            _ => true,
        }
    }

    // children: a vector of nodes representing the template text
    //           found between the section tags
    //
    // in the case of values for a section being lambdas, we need to pass
    // the raw text of the inside of the section tags to the lambda.
    // we store the raw text of each tag in the tag enum itself,
    // so we iterate through the children of the section, pulling out
    // the raw text and creating a string of it to pass to the lambda.
    //
    fn get_section_text(&self, children: &[Node]) -> String {
        children.iter().map(|child| {
            match *child {
                Static(text) | Part(_, text) => text.into(),
                Value(_, ref text) |
                Unescaped(_, ref text) => String::from(&text[..]),
                Section(_, ref children, _, ref open, ref close) => {
                    let rv = self.get_section_text(children);
                    format!("{}{}{}", &open[..], &rv[..], &close[..])
                }
            }
        }).collect()
    }

    // filename:  the filename of the partial template to include,
    //            a.k.a the value inside the tag
    // datastore: all the template data
    // writer:    the io stream to write the rendered template out to
    //
    // in the mustache spec, it says parials are rendered at runtime,
    // so we call render in this method.  datastore and writer are taken
    // in as parameters because we have to do this
    //
    // TODO: throw error if partials file doesn't exist, if file read fails
    //
    fn handle_partial_file_node<W: Write>(&mut self,
                                          filename: &str,
                                          datastore: &HashMap<String, Data>,
                                          writer: &mut W)
                                          -> RustacheResult<()> {
        let path = Path::new(&self.partials_path.clone()).join(filename);
        if fs::metadata(&path).is_ok() {

            let mut contents = String::new();
            let file = File::open(&path).and_then(|ref mut f| f.read_to_string(&mut contents));
            match file {
                Ok(_) => {
                    let tokens = compiler::create_tokens(&contents[..]);
                    let nodes = parser::parse_nodes(&tokens);

                    self.render(writer, datastore, &nodes)
                }
                Err(err) => {
                    let msg = format!("{}: {}", err, filename);
                    Err(TemplateErrorType(FileReadError(msg)))
                }
            }
        } else {
            // if the file is not found, it's supposed to fail silently
            Ok(())
        }
    }

    fn handle_node<W: Write>(&mut self,
                             node: &Node,
                             datastore: &HashMap<String, Data>,
                             writer: &mut W)
                             -> RustacheResult<()> {
        let mut rv = Ok(());

        match *node {
            // value nodes contain tags who's data gets HTML escaped
            // when it gets written out
            Unescaped(key, _) |
            Value(key, _) => {
                let tmp = key.to_string();
                if datastore.contains_key(&tmp) {
                    let val = &datastore[&tmp];
                    rv = self.handle_unescaped_or_value_node(node,
                                                             val,
                                                             "".to_string(),
                                                             datastore,
                                                             writer);
                }
            }
            // static nodes are the test in the template that doesn't get modified,
            // just gets written out character for character
            Static(key) => {
                rv = self.write_to_stream(writer, &key.to_string(), "render: static");
            }
            // sections come in two kinds, normal and inverted
            //
            // inverted are if the tag data is not there, the Static between it
            // and it's closing tag gets written out, otherwise the text is thrown out
            //
            // normal section tags enclose a bit of html that will get repeated
            // for each element found in it's data
            Section(key, ref children, ref inverted, _, _) => {
                let tmp = key.to_string();
                let truthy = if datastore.contains_key(&tmp) {
                    self.is_section_data_true(&datastore[&tmp])
                } else {
                    false
                };
                match (truthy, *inverted) {
                    (true, true) | (false, false) => {}
                    (true, false) => {
                        let val = &datastore[&tmp];
                        let mut sections = vec![tmp.clone()];
                        rv = self.handle_section_node(children,
                                                      &tmp,
                                                      val,
                                                      datastore,
                                                      &mut sections,
                                                      writer);
                    }
                    (false, true) => {
                        rv = self.handle_inverted_node(children, datastore, writer);
                    }
                }
            }
            // partials include external template files and compile and process them
            // at runtime, inserting them into the document at the point the tag is found
            Part(name, _) => {
                rv = self.handle_partial_file_node(name, datastore, writer);
            }
        }

        rv
    }
    // writer: an io::stream to write the rendered template out to
    // data:   the internal HashBuilder data store
    // parser: the parser object that has the parsed nodes, see src/parse.js
    pub fn render<W: Write>(&mut self,
                            writer: &mut W,
                            data: &HashMap<String, Data>,
                            nodes: &[Node])
                            -> RustacheResult<()> {
        // nodes are what the template file is parsed into
        // we have to iterate through each one and handle it as
        // the kind of node it is
        for node in nodes.iter() {
            try!(self.handle_node(node, data, writer));
        }
        Ok(())
    }

    // main entry point to Template
    pub fn render_data<W: Write>(&mut self,
                                 writer: &mut W,
                                 datastore: &HashBuilder,
                                 nodes: &[Node])
                                 -> RustacheResult<()> {
        // we need to hang on to the partials path internally,
        // if there is one, for class methods to use.
        self.partials_path.truncate(0);
        self.partials_path.push_str(datastore.partials_path);

        self.render(writer, &datastore.data, nodes)
    }
}


#[cfg(test)]
mod template_tests {
    use std::fs::File;
    use std::path::Path;
    use std::io::{self, Cursor, Read, Seek, SeekFrom};
    use std::str;

    use parser;
    use parser::Node;
    use parser::Node::{Value, Static, Unescaped, Section, Part};
    use compiler;
    use template::Template;
    use build::{HashBuilder, VecBuilder};
    use Data::Strng;

    #[test]
    fn test_look_up_section_data() {
        let hb = HashBuilder::new()
            .insert("a",
                    HashBuilder::new()
                        .insert("b",
                                HashBuilder::new()
                                    .insert("name", "Phil")
                                    .insert("c",
                                            HashBuilder::new()
                                                .insert("d",
                                                        HashBuilder::new()
                                                            .insert("e", HashBuilder::new())))));

        let key = "name".to_string();
        let sections = vec!["a".to_string(),
                            "b".to_string(),
                            "c".to_string(),
                            "d".to_string(),
                            "e".to_string()];
        let data = hb.data;

        let answer = Template::new().look_up_section_data(&key, &sections, &data);

        assert!(answer.is_some());
        match answer {
            Some(d) => {
                match *d {
                    Strng(ref s) => assert_eq!("Phil".to_string(), *s),
                    _ => {
                        assert!(false);
                    }
                }
            }
            _ => {
                assert!(false);
            }
        }
    }

    #[test]
    fn test_look_up_section_data_also() {
        let hb = HashBuilder::new()
            .insert("a", HashBuilder::new())
            .insert("b", HashBuilder::new().insert("name", "Phil"))
            .insert("c", HashBuilder::new())
            .insert("d", HashBuilder::new())
            .insert("e", HashBuilder::new());

        let key = "name".to_string();
        let sections = vec!["a".to_string(),
                            "b".to_string(),
                            "c".to_string(),
                            "d".to_string(),
                            "e".to_string()];
        let data = hb.data;

        let answer = Template::new().look_up_section_data(&key, &sections, &data);

        assert!(answer.is_some());
        match answer {
            Some(d) => {
                match *d {
                    Strng(ref s) => assert_eq!("Phil".to_string(), *s),
                    _ => {
                        assert!(false);
                    }
                }
            }
            _ => {
                assert!(false);
            }
        }
    }

    #[test]
    fn test_escape_html() {
        let s1 = "a < b > c & d \"spam\"\'";
        let a1 = "a &lt; b &gt; c &amp; d &quot;spam&quot;'";
        let s2 = "1<2 <b>hello</b>";
        let a2 = "1&lt;2 &lt;b&gt;hello&lt;/b&gt;";

        let mut w = Cursor::new(Vec::new());
        let nodes: Vec<Node> = vec![Value("value", "{{ value }}".to_string())];
        let data = HashBuilder::new().insert("value", s1);

        let rv = Template::new().render_data(&mut w, &data, &nodes);
        match rv {
            _ => {}
        }

        assert_eq!(a1, str::from_utf8(w.get_ref()).unwrap());

        w = Cursor::new(Vec::new());
        let newdata = HashBuilder::new().insert("value", s2);
        let rv = Template::new().render_data(&mut w, &newdata, &nodes);
        match rv {
            _ => {}
        }

        assert_eq!(a2, str::from_utf8(w.get_ref()).unwrap());
    }

    #[test]
    fn test_section_tag_iteration() {
        let mut w = Cursor::new(Vec::new());
        let template = "{{#repo}}<b>{{name}}</b>{{/repo}}";
        let tokens = compiler::create_tokens(template);
        let nodes = parser::parse_nodes(&tokens);
        let data = HashBuilder::new().insert("repo",
                                             VecBuilder::new()
                                                 .push(HashBuilder::new()
                                                     .insert("name", "resque"))
                                                 .push(HashBuilder::new().insert("name", "hub"))
                                                 .push(HashBuilder::new().insert("name", "rip")));

        let rv = Template::new().render_data(&mut w, &data, &nodes);
        match rv {
            _ => {}
        }

        assert_eq!("<b>resque</b><b>hub</b><b>rip</b>".to_string(),
                   String::from_utf8(w.into_inner()).unwrap());
    }

    #[test]
    fn test_not_escape_html() {
        let s = "1<2 <b>hello</b>";
        let mut w = Cursor::new(Vec::new());
        let nodes: Vec<Node> = vec![Unescaped("value", "{{ value }}".to_string())];
        let data = HashBuilder::new().insert("value", s);

        let rv = Template::new().render_data(&mut w, &data, &nodes);
        match rv {
            _ => {}
        }

        assert_eq!(s, String::from_utf8(w.into_inner()).unwrap());
    }

    #[test]
    fn test_render_to_io_stream() {
        let mut w = Cursor::new(Vec::new());
        let data = HashBuilder::new().insert("value1", "The heading");
        let nodes: Vec<Node> =
            vec![Static("<h1>"), Value("value1", "{{ value1 }}".to_string()), Static("</h1>")];

        let rv = Template::new().render_data(&mut w, &data, &nodes);
        match rv {
            _ => {}
        }

        assert_eq!("<h1>The heading</h1>".to_string(),
                   String::from_utf8(w.into_inner()).unwrap());
    }

    #[test]
    fn test_unescaped_node_correct_bool_false_data() {
        let mut w = Cursor::new(Vec::new());
        let nodes: Vec<Node> =
            vec![Static("<h1>"), Unescaped("value1", "{{& value1 }}".to_string()), Static("</h1>")];
        let data = HashBuilder::new().insert("value1", false);

        let rv = Template::new().render_data(&mut w, &data, &nodes);
        match rv {
            _ => {}
        }

        assert_eq!("<h1>false</h1>".to_string(),
                   String::from_utf8(w.into_inner()).unwrap());
    }

    #[test]
    fn test_unescaped_node_correct_bool_true_data() {
        let mut w = Cursor::new(Vec::new());
        let nodes: Vec<Node> =
            vec![Static("<h1>"), Unescaped("value1", "{{& value1 }}".to_string()), Static("</h1>")];
        let data = HashBuilder::new().insert("value1", true);

        let rv = Template::new().render_data(&mut w, &data, &nodes);
        match rv {
            _ => {}
        }

        assert_eq!("<h1>true</h1>".to_string(),
                   String::from_utf8(w.into_inner()).unwrap());
    }

    #[test]
    fn test_section_value_string_data() {
        let mut w = Cursor::new(Vec::new());
        let nodes: Vec<Node> = vec![Section("value1",
                                            vec![Value("value", "{{ value }}".to_string())],
                                            false,
                                            "{{# value1 }}".to_string(),
                                            "{{/ value1 }}".to_string())];
        let data = HashBuilder::new().insert("value1",
                                             HashBuilder::new().insert("value", "<Section Value>"));

        let rv = Template::new().render_data(&mut w, &data, &nodes);
        match rv {
            _ => {}
        }

        assert_eq!("&lt;Section Value&gt;".to_string(),
                   String::from_utf8(w.into_inner()).unwrap());
    }

    #[test]
    fn test_section_multiple_value_string_data() {
        let mut w = Cursor::new(Vec::new());
        let nodes: Vec<Node> = vec![Section("names",
                                            vec![Value("name", "{{ name }}".to_string())],
                                            false,
                                            "{{# names }}".to_string(),
                                            "{{/ names }}".to_string())];
        let data = HashBuilder::new().insert("names",
                                             HashBuilder::new().insert("name",
                                                                       VecBuilder::new()
                                                                           .push("tom")
                                                                           .push("robert")
                                                                           .push("joe")));

        let rv = Template::new().render_data(&mut w, &data, &nodes);
        match rv {
            _ => {}
        }

        assert_eq!("tomrobertjoe".to_string(),
                   String::from_utf8(w.into_inner()).unwrap());
    }

    // #[test]
    // fn test_excessively_nested_data() {
    //     let mut w = Cursor::new(Vec::new());
    //     let nodes: Vec<Node> = vec![Section("hr", vec![Section("people", vec![Value("name", "{{ name }}".to_string())], false, "{{# people }}".to_string(), "{{/ people }}".to_string())], false, "{{# hr }}".to_string(), "{{/ hr }}".to_string())];
    //     let data = HashBuilder::new()
    //         .insert_hash("hr", |builder| {
    //             builder.insert_hash("people", |builder| {
    //                 builder
    //                     .insert_vector("name", |builder| {
    //                         builder
    //                             .push("tom")
    //                             .push("robert")
    //                             .push("joe")
    //                 })
    //             })
    //         });

    //     let rv = Template::new().render_data(&mut w, &data, &nodes);
    //     assert_eq!("tomrobertjoe".to_string(), String::from_utf8(w.into_inner()).unwrap());
    // }

    #[test]
    fn test_unescaped_node_lambda_data() {
        let mut w = Cursor::new(Vec::new());
        let nodes: Vec<Node> =
            vec![Static("<h1>"), Unescaped("func1", "{{& func1 }}".to_string()), Static("</h1>")];
        let mut f = |_| "heading".to_string();
        let data = HashBuilder::new().insert_lambda("func1", &mut f);

        let rv = Template::new().render_data(&mut w, &data, &nodes);
        match rv {
            _ => {}
        }

        assert_eq!("<h1>heading</h1>".to_string(),
                   String::from_utf8(w.into_inner()).unwrap());
    }

    #[test]
    fn test_value_node_lambda_data() {
        let mut w = Cursor::new(Vec::new());
        let nodes: Vec<Node> =
            vec![Static("<h1>"), Value("func1", "{{ func1 }}".to_string()), Static("</h1>")];
        let mut f = |_| "heading".to_string();
        let data = HashBuilder::new().insert_lambda("func1", &mut f);

        let rv = Template::new().render_data(&mut w, &data, &nodes);
        match rv {
            _ => {}
        }

        assert_eq!("<h1>heading</h1>".to_string(),
                   String::from_utf8(w.into_inner()).unwrap());
    }

    // #[test]
    // fn test_spec_lambdas_interpolation_using_render_text() {
    //     let mut s = Cursor::new(Vec::new());
    //     let data = HashBuilder::new()
    //                 .insert_lambda("lambda", |_| {
    //                      "world".to_string()
    //                  });
    //     let s = rustache::render_text("Hello, {{lambda}}!", data);
    //     assert_eq!("Hello, world!".to_string(), String::from_utf8(w.into_inner()).unwrap());
    // }

    // #[test]
    // fn test_spec_lambdas_inverted_section_using_render_text() {
    //     let data = HashBuilder::new()
    //                 .insert("static", "static")
    //                 .insert_lambda("lambda", |_| {
    //                     "false".to_string()
    //                 });

    //     let s = rustache::render_text("<{{^lambda}}{{static}}{{/lambda}}>", data);

    //     assert_eq!("<>".to_string(), String::from_utf8(w.into_inner()).unwrap());
    // }

    #[test]
    fn test_value_node_correct_false_bool_data() {
        let mut w = Cursor::new(Vec::new());
        let nodes: Vec<Node> = vec![Value("value1", "{{ value1 }}".to_string())];
        let data = HashBuilder::new().insert("value1", false);

        let rv = Template::new().render_data(&mut w, &data, &nodes);
        match rv {
            _ => {}
        }

        assert_eq!("false".to_string(),
                   String::from_utf8(w.into_inner()).unwrap());
    }

    #[test]
    fn test_value_node_correct_true_bool_data() {
        let mut w = Cursor::new(Vec::new());
        let nodes: Vec<Node> = vec![Value("value1", "{{ value1 }}".to_string())];
        let data = HashBuilder::new().insert("value1", true);

        let rv = Template::new().render_data(&mut w, &data, &nodes);
        match rv {
            _ => {}
        }

        assert_eq!("true".to_string(),
                   String::from_utf8(w.into_inner()).unwrap());
    }

    #[test]
    fn test_partial_node_correct_data() {
        let mut w = Cursor::new(Vec::new());
        let nodes: Vec<Node> = vec![Static("A wise woman once said: "),
                                    Part("hopper_quote.partial", "{{> hopper_quote.partial }}")];
        let data = HashBuilder::new()
            .insert("author", "Grace Hopper")
            .set_partials_path("test_data");

        let mut s: String = String::new();
        s.push_str("A wise woman once said: It's easier to get forgiveness than \
                    permission.-Grace Hopper");

        let rv = Template::new().render_data(&mut w, &data, &nodes);
        match rv {
            _ => {}
        }

        assert_eq!(s, String::from_utf8(w.into_inner()).unwrap());
    }

    #[test]
    fn test_partial_node_correct_data_with_extra() {
        let mut w = Cursor::new(Vec::new());
        let nodes: Vec<Node> = vec![Static("A wise woman once said: "),
                                    Part("hopper_quote.partial", "{{> hopper_quote.partial }}"),
                                    Static(" something else "),
                                    Value("extra", "{{ extra }}".to_string())];
        let data = HashBuilder::new()
            .insert("author", "Grace Hopper")
            .insert("extra", "extra data")
            .set_partials_path("test_data");

        let mut s: String = String::new();
        s.push_str("A wise woman once said: It's easier to get forgiveness than \
                    permission.-Grace Hopper something else extra data");

        let rv = Template::new().render_data(&mut w, &data, &nodes);
        match rv {
            _ => {}
        }

        assert_eq!(s, String::from_utf8(w.into_inner()).unwrap());
    }

    #[test]
    fn test_section_node_partial_node_correct_data() {
        let mut w = Cursor::new(Vec::new());
        let data = HashBuilder::new()
            .set_partials_path("test_data")
            .insert("people",
                    HashBuilder::new().insert("information",
                                              VecBuilder::new()
                                                  .push("<tr><td>Jarrod</td><td>Ruhland</td></tr>")
                                                  .push("<tr><td>Sean</td><td>Chen</td></tr>")
                                                  .push("<tr><td>Fleur</td><td>Dragan</td></tr>")
                                                  .push("<tr><td>Jim</td><td>O'Brien</td></tr>")));
        let path = Path::new("test_data/section_with_partial_template.html");
        let contents = File::open(path)
            .and_then(|mut fp| {
                let mut contents = String::new();
                fp.read_to_string(&mut contents)
                    .map(move |_| contents)
            })
            .unwrap();

        let mut tokens = compiler::create_tokens(&contents[..]);
        let nodes = parser::parse_nodes(&mut tokens);

        let rv = Template::new().render_data(&mut w, &data, &nodes);
        match rv {
            _ => {}
        }

        let mut f = File::create(&Path::new("test_data/section_with_partial.html")).unwrap();
        w.seek(SeekFrom::Start(0)).unwrap();
        let completed = io::copy(&mut w, &mut f);
        assert_eq!(completed.is_ok(), true);
    }

    // - name: Interpolation - Multiple Calls
    //   desc: Interpolated lambdas should not be cached.
    //   data:
    //     lambda: !code
    //       ruby:    'proc { $calls ||= 0; $calls += 1 }'
    //       perl:    'sub { no strict; $calls += 1 }'
    //       js:      'function() {return (g=(function(){return this})()).calls=(g.calls||0)+1 }'
    //       php:     'global $calls; return ++$calls;'
    //       python:  'lambda: globals().update(calls=globals().get("calls",0)+1) or calls'
    //       clojure: '(def g (atom 0)) (fn [] (swap! g inc))'
    //   template: '{{lambda}} == {{{lambda}}} == {{lambda}}'
    //   expected: '1 == 2 == 3'
    #[test]
    fn test_spec_lambda_not_cached_on_interpolation() {
        let mut planets = vec!["Jupiter", "Earth", "Saturn"];
        let mut w = Cursor::new(Vec::new());
        let mut tokens = compiler::create_tokens("{{lambda}} == {{&lambda}} == {{lambda}}");
        let nodes = parser::parse_nodes(&mut tokens);
        let mut f = |_| planets.pop().unwrap().to_string();
        let data = HashBuilder::new()
            .insert_lambda("lambda", &mut f)
            .insert("planet", "world");

        let rv = Template::new().render_data(&mut w, &data, &nodes);
        match rv {
            _ => {}
        }
        assert_eq!("Saturn == Earth == Jupiter".to_string(),
                   String::from_utf8(w.into_inner()).unwrap());
    }

}