1 /**
2  * Copyright:
3  * (C) 2016 Martin Brzenska
4  *
5  * License:
6  * Distributed under the terms of the MIT license.
7  * Consult the provided LICENSE.md file for details
8  */
9 module dominator.output;
10 
11 import std.conv : to;
12 import std.array;
13 import std.algorithm;
14 import std..string : lastIndexOf;
15 import std.stdio;
16 
17 import libdominator.Attribute;
18 import libdominator.Dominator;
19 import libdominator.Node;
20 
21 /**
22 * Builds a output string.
23 * This is usefull for formating output for the command-line.
24 * Params:
25 *   dom = The DOM Object
26 *   node = A node, that is part of dom
27 *   optOutItems = Defines the output contents
28 */
29 string[] nodeOutputItems(ref Dominator dom, Node node, string[] optOutItems)
30 {
31   import std.array : appender;
32   string[] columns;
33   auto columnsApp = appender(columns);
34 
35   foreach(string optOutItem ; optOutItems)
36   {
37     columnsApp.put(nodeOutputItem(dom , node , optOutItem));
38     }
39   return columnsApp.data;
40 }
41 
42 string nodeOutputItem(ref Dominator dom, Node node, string optOutItem)
43 {
44   switch(optOutItem)
45     {
46       case "tag":
47         return node.getTag();
48       case "element":
49         return dom.getElement(node);
50       case "element-opener":
51         return dom.getStartElement(node);
52       case "element-start-length":
53         return to!string(node.getStartTagLength());
54       case "element-end-length":
55         return to!string(node.getEndTagLength());
56       case "element-start":
57         return to!string(node.getStartPosition());
58       case "element-end":
59         return to!string(node.getEndPosition());
60       case "element-inner":
61         return dom.getInner(node);
62       case "element-strip":
63         return dom.stripTags(node);
64       case "attrib-keys":
65         return join(map!(a => a.key)(node.getAttributes()),",");
66       default:
67         /*
68         * some CLI-Arguments are parametrized, lets check them
69         */
70         if(optOutItem.length > 7 && optOutItem[0..7] == "attrib(")
71         {
72           size_t closerIndex = lastIndexOf(optOutItem, ")");
73           if(closerIndex)
74           {
75             string[] keyvalues;
76             foreach(Attribute fAttrib ; node.getAttributes().filter!(a => a.key == optOutItem[7..closerIndex]))
77             {
78               keyvalues ~= fAttrib.values;
79             }
80             return join(keyvalues, ",");
81           }
82         }
83         /*
84         * If no "OutItem" matches, output he input right away.
85         */
86         return optOutItem;
87     }
88 }
89