Passed
Pull Request — master (#155)
by Jan
03:07
created

Client.open_results_in_web_browser()   A

Complexity

Conditions 3

Size

Total Lines 9
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3.7085

Importance

Changes 0
Metric Value
cc 3
eloc 9
nop 2
dl 0
loc 9
ccs 4
cts 7
cp 0.5714
crap 3.7085
rs 9.95
c 0
b 0
f 0
1 1
import re
2 1
import argparse
3 1
import tempfile
4 1
import os
5 1
import webbrowser
6 1
import subprocess
7 1
from datetime import datetime
8 1
import sys
9
10 1
from .xml_parser import XmlParser
11 1
from .exceptions import NotChecked
12 1
from ._builder_html_graph import BuilderHtmlGraph
13 1
from .__init__ import __version__
14
15
16 1
class Client():
17 1
    def __init__(self, args):
18 1
        self.parser = None
19 1
        self.MESSAGES = self._get_message()
20 1
        self.arg = self.parse_arguments(args)
21 1
        self.hide_passing_tests = self.arg.hide_passing_tests
22 1
        self.source_filename = self.arg.source_filename
23 1
        self.rule_name = self.arg.rule_id
24 1
        self.out = self.arg.output
25 1
        self.verbose = self.arg.verbose
26
27 1
        self.parts = self.get_src('parts')
28 1
        self.START_OF_FILE_NAME = 'graph-of-'
29 1
        self.date = str(datetime.now().strftime("-%d_%m_%Y-%H_%M_%S"))
30 1
        self.isatty = sys.stdout.isatty()
31
32 1
        self.all_rules = self.arg.all
33 1
        self.all_in_one = None
34 1
        self.display_html = None
35 1
        if type(self).__name__ in ('ArfToHtml', 'JsonToHtml'):
36 1
            self._set_attributes_for_ArfToHtml_or_JsonToHtml()
37
38 1
        self.show_failed_rules = False
39 1
        self.show_not_selected_rules = False
40 1
        if type(self).__name__ in ('ArfToHtml', 'ArfToJson'):
41 1
            self._set_attributes_for_ArfToHtml_or_ArfToJson()
42
43 1
        self.xml_parser = None
44 1
        if type(self).__name__ != 'JsonToHtml':
45 1
            self.xml_parser = XmlParser(self.source_filename)
46
47 1
        self.html_builder = None
48 1
        if type(self).__name__ != 'ArfToJson':
49 1
            self.html_builder = BuilderHtmlGraph(self.parts, self.verbose)
50
51 1
        self.web_browsers = []
52
53 1
    def _set_attributes_for_ArfToHtml_or_JsonToHtml(self):
54 1
        self.all_in_one = self.arg.all_in_one
55 1
        self.all_rules = True if self.all_in_one else self.arg.all
56 1
        self.display_html = True if self.out is None else self.arg.display
57
58 1
    def _set_attributes_for_ArfToHtml_or_ArfToJson(self):
59 1
        self.show_failed_rules = self.arg.show_failed_rules
60 1
        self.show_not_selected_rules = self.arg.show_not_selected_rules
61
62 1
    def _get_message(self):
63 1
        MESSAGES = {
64
            'description': '',
65
            'source_filename': '',
66
        }
67 1
        return MESSAGES
68
69 1
    def print_red_text(self, text):
70
        CRED = '\033[91m'
71
        CEND = '\033[0m'
72
        print(CRED + str(text) + CEND)
73
74 1
    def run_gui_and_return_answers(self):
75 1
        if self.isatty:
76 1
            if self.all_rules:
77
                return self._get_rules()
78
            else:
79 1
                try:
80 1
                    import inquirer
81 1
                    return inquirer.prompt(self.get_questions())
82 1
                except ImportError:
83 1
                    print(self.get_selection_rules())
84 1
                    return None
85
        else:
86 1
            return self._get_rules()
87
88 1
    def _get_rules(self):
89 1
        return {
90
            'rules': self._get_only_fail_rule(
91
                self.search_rules_id())} if self.show_failed_rules else {
92
            'rules': self.search_rules_id()}
93
94 1
    def get_list_of_matched_rules(self):
95 1
        return self._get_only_fail_rule(
96
            self.search_rules_id()) if self.show_failed_rules else self.search_rules_id()
97
98 1
    def get_list_of_lines(self):
99 1
        lines = ['== The Rule ID regular expressions ==']
100 1
        for rule in self.get_list_of_matched_rules():
101 1
            lines.append("^" + rule + "$")
102 1
        if self.show_not_selected_rules:
103 1
            for line in self.get_lines_of_wanted_not_selected_rules():
104 1
                lines.append(line)
105 1
        lines.append(
106
            "Interactive rule selection is not available,"
107
            " because inquirer is not installed."
108
            " Copy id of the rule you want to visualize and"
109
            " paste it into a command with regular"
110
            " expression characters(^$).\n"
111
            "Alternatively, use the --all or --all-in-one arguments.")
112 1
        return lines
113
114 1
    def get_selection_rules(self):
115 1
        return "\n".join(self.get_list_of_lines())
116
117 1
    def get_lines_of_wanted_not_selected_rules(self):
118 1
        out = []
119 1
        out.append('== The not selected rule IDs ==')
120 1
        for rule in self._get_wanted_rules_from_array_of_IDs(
121
                self.xml_parser.notselected_rules):
122 1
            out.append(rule + '(Not selected)')
123 1
        return out
124
125 1
    def get_choices(self):
126 1
        if self.show_not_selected_rules:
127 1
            print("\n".join(self.get_lines_of_wanted_not_selected_rules()))
128 1
        return self.get_list_of_matched_rules()
129
130 1
    def get_questions(self):
131 1
        choices = self.get_choices()
132 1
        from inquirer.questions import Checkbox as checkbox
133 1
        questions = [
134
            checkbox(
135
                'rules',
136
                message=(
137
                    "= The Rules IDs = (move - UP and DOWN arrows,"
138
                    " select - SPACE or LEFT and RIGHT arrows, submit - ENTER)"),
139
                choices=choices,
140
            ),
141
        ]
142 1
        return questions
143
144 1
    def _get_only_fail_rule(self, rules):
145 1
        return list(
146
            filter(
147
                lambda rule: self.xml_parser.used_rules[rule]['result'] == 'fail',
148
                rules))
149
150 1
    def _get_wanted_rules_from_array_of_IDs(self, rules):
151 1
        return [
152
            x for x in rules if re.search(
153
                self.rule_name, x)]
154
155 1
    def search_rules_id(self):
156 1
        return self._check_rules_id(
157
            self._get_wanted_rules_from_array_of_IDs(
158
                self.xml_parser.used_rules.keys()),
159
            self._get_wanted_rules_from_array_of_IDs(
160
                self.xml_parser.notselected_rules))
161
162 1
    def _check_rules_id(self, rules, notselected_rules):
163 1
        if len(notselected_rules) and not rules:
164 1
            raise ValueError(
165
                ('Rule(s) "{}" was not selected, '
166
                 "so there are no results. The rule is"
167
                 ' "notselected" because it'
168
                 " wasn't a part of the executed profile"
169
                 " and therefore it wasn't evaluated "
170
                 "during the scan.")
171
                .format(notselected_rules))
172 1
        elif not notselected_rules and not rules:
173 1
            raise ValueError('404 rule "{}" not found!'.format(self.rule_name))
174
        else:
175 1
            return rules
176
177 1
    def get_save_src(self, rule):
178 1
        if self.out is not None:
179 1
            os.makedirs(self.out, exist_ok=True)
180 1
            return os.path.join(
181
                self.out,
182
                self.START_OF_FILE_NAME + rule + '.html')
183 1
        return os.path.join(
184
            tempfile.gettempdir(),
185
            self.START_OF_FILE_NAME + rule + '.html')
186
187 1
    def get_src(self, src):
188 1
        _dir = os.path.dirname(os.path.realpath(__file__))
189 1
        return str(os.path.join(_dir, src))
190
191 1
    def _build_and_save_html(self, dict_oval_trees, src, rules, out_src):
192 1
        self.html_builder.save_html(dict_oval_trees, src, rules)
193 1
        out_src.append(src)
194
195 1
    def open_results_in_web_browser(self, paths_to_results):
196 1
        if self.display_html:
197 1
            try:
198 1
                self.web_browsers.append(subprocess.Popen(
199
                    ["firefox", *paths_to_results]))
200
            except BaseException:
201
                default_web_browser_name = webbrowser.get().name
202
                self.web_browsers.append(subprocess.Popen(
203
                    [default_web_browser_name, *paths_to_results]))
204
205 1
    def kill_web_browsers(self):
206 1
        for web_browser in self.web_browsers:
207 1
            web_browser.kill()
208
209 1
    def _prepare_data(self, rules, dict_oval_trees, out_src):
210 1
        for rule in rules['rules']:
211 1
            try:
212 1
                self._put_to_dict_oval_trees(dict_oval_trees, rule)
213 1
                if not self.all_in_one:
214 1
                    self._build_and_save_html(
215
                        dict_oval_trees, self._get_src_for_one_graph(
216
                            rule), dict(
217
                            rules=[rule]), out_src)
218 1
                    dict_oval_trees = {}
219 1
            except NotChecked as error:
220
                self.print_red_text(error)
221 1
        if self.all_in_one:
222
            self._build_and_save_html(
223
                dict_oval_trees, self.get_save_src(
224
                    'rules' + self.date), rules, out_src)
225
226 1
    def prepare_data(self, rules):
227 1
        out_src = []
228 1
        oval_tree_dict = dict()
229 1
        self._prepare_data(rules, oval_tree_dict, out_src)
230 1
        self.open_results_in_web_browser(out_src)
231 1
        return out_src
232
233 1
    def parse_arguments(self, args):
234 1
        self.prepare_parser()
235 1
        return self.parser.parse_args(args)
236
237 1
    def prepare_args_when_output_is_html(self):
238 1
        self.parser.add_argument(
239
            '-i',
240
            '--all-in-one',
241
            action="store_true",
242
            default=False,
243
            help="Processes all rules into one file.")
244 1
        self.parser.add_argument(
245
            '-d',
246
            '--display',
247
            action="store_true",
248
            default=False,
249
            help="Enables opening a web browser with a graph, when is used --output.")
250
251 1
    def prepare_args_when_user_can_list_in_rules(self):
252 1
        self.parser.add_argument(
253
            '--show-failed-rules',
254
            action="store_true",
255
            default=False,
256
            help="Show only FAILED rules")
257 1
        self.parser.add_argument(
258
            '--show-not-selected-rules',
259
            action="store_true",
260
            default=False,
261
            help="Show notselected rules. These rules will not be visualized.")
262
263 1
    def prepare_parser(self):
264 1
        self.parser = argparse.ArgumentParser(
265
            prog='oval-graph',
266
            description=self.MESSAGES.get('description'))
267 1
        self.parser.add_argument(
268
            '--version',
269
            action='version',
270
            version='%(prog)s ' + __version__)
271 1
        self.parser.add_argument(
272
            '-a',
273
            '--all',
274
            action="store_true",
275
            default=False,
276
            help="Process all matched rules.")
277 1
        self.parser.add_argument(
278
            '--hide-passing-tests',
279
            action="store_true",
280
            default=False,
281
            help=(
282
                "Do not display passing tests for better orientation in"
283
                " graphs that contain a large amount of nodes."))
284 1
        self.parser.add_argument(
285
            '-v',
286
            '--verbose',
287
            action="store_true",
288
            default=False,
289
            help="Displays details about the results of the running command.")
290 1
        self.parser.add_argument(
291
            '-o',
292
            '--output',
293
            action="store",
294
            default=None,
295
            help='The file where to save output.')
296 1
        self.parser.add_argument(
297
            "source_filename",
298
            help=self.MESSAGES.get('source_filename'))
299 1
        self.parser.add_argument(
300
            "rule_id", help=(
301
                "Rule ID to be visualized. A part from the full rule ID"
302
                " a part of the ID or a regular expression can be used."
303
                " If brackets are used in the regular expression "
304
                "the regular expression must be quoted."))
305