1 module RuleWriter;
2 
3 import std.array;
4 import std.stdio;
5 
6 class RuleWriter{
7 
8     private string pathName;
9     private string fileName;
10 
11     public ushort indentLevel;
12 
13     struct Result { ushort indent; string s;}
14     
15     private Result[] result;
16 
17     this() {
18     }
19     
20     this(string pathName) {
21         this.pathName = pathName;
22     }
23 
24     public void setOutputFilename(string fileName)
25     {
26         this.fileName = fileName;
27     }
28 
29     public void setOutputPath(string pathName)
30     {
31         this.pathName = pathName;
32     }
33 
34     public void clear() {
35         result.length = 0;
36     }
37 
38     public void put(string s) {
39         result ~= set(s);
40     }
41     
42     public void put(string[] s) {
43         foreach(el; s) {
44             result ~= set(el);
45         }
46     }
47     
48     public void putnl(string s) {
49         s ~= "\n";
50         Result r =  set(s);
51         result ~= r;
52     }
53 
54     public Result set(string s) {
55         Result r;
56         r.indent = indentLevel;
57         r.s = s;
58         return r;  
59     }
60 
61     public void print() {
62         auto r =  appender!string;
63         bool lastEndWithNL = true;
64         foreach (e; result) {
65             if (lastEndWithNL)
66                 while (e.indent-- > 0) {
67                     r.put("    "); //indent 4 spaces per level
68                 }
69             r.put(e.s);
70         if (e.s.length != 0 && e.s[$-1] == '\n')
71             lastEndWithNL = true;
72         else
73             lastEndWithNL = false;
74         }
75         if(pathName) {
76             auto f = File(pathName ~ "/" ~ fileName, "w");
77             f.write(r.data);
78             f.close;
79         }
80         else {
81             write(r.data);
82         }
83     }
84 }
85