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 libdominator.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   string[] columns;
32   foreach(string optOutItem ; optOutItems)
33   {
34     switch(optOutItem)
35     {
36       case "tag":
37         columns ~= node.getTag();
38       break;
39       case "element":
40         columns ~= dom.getElelment(node);
41       break;
42       case "element-opener":
43         columns ~= dom.getStartElement(node);
44         break;
45       case "element-length":
46         columns ~= to!string(node.getStartTagLength());
47       break;
48       case "element-start":
49         columns ~= to!string(node.getStartPosition());
50       break;
51       case "element-end":
52         columns ~= to!string(node.getEndPosition());
53       break;
54       case "element-inner":
55         columns ~= dom.getInner(node);
56       break;
57       case "attrib-keys":
58         columns ~= join(map!(a => a.key)(node.getAttributes()),",");
59       break;
60       default:
61         /*
62         * some CLI-Arguments are parametrized, lets check them
63         */
64         if(optOutItem.length > 7 && optOutItem[0..7] == "attrib(")
65         {
66           size_t closerIndex = lastIndexOf(optOutItem, ")");
67           if(closerIndex)
68           {
69             string[] keyvalues;
70             foreach(Attribute fAttrib ; node.getAttributes().filter!(a => a.key == optOutItem[7..closerIndex]))
71             {
72               keyvalues ~= fAttrib.values;
73             }
74             columns ~= join(keyvalues, ",");
75           }
76         }
77         else {
78           /*
79           * If no "OutItem" matches, output he input right away.
80           */
81           columns ~= optOutItem;
82         }
83       break;
84     }
85   }
86   return columns;
87 }