Passed
Push — master ( b25b04...24a582 )
by Jan
04:05 queued 11s
created

oval_graph.client.Client.save_html_and_open_html()   A

Complexity

Conditions 1

Size

Total Lines 5
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 5
nop 5
dl 0
loc 5
rs 10
c 0
b 0
f 0
ccs 5
cts 5
cp 1
crap 1
1 1
import re
2 1
import argparse
3 1
import tempfile
4 1
import os
5 1
import webbrowser
6 1
import json
7 1
import shutil
8 1
from datetime import datetime
9 1
import sys
10
11 1
from .xml_parser import XmlParser
12
13
14 1
class Client():
15 1
    def __init__(self, args):
16 1
        self.parser = None
17 1
        self.MESSAGES = self._get_message()
18 1
        self.arg = self.parse_arguments(args)
19 1
        self.hide_passing_tests = self.arg.hide_passing_tests
20 1
        self.source_filename = self.arg.source_filename
21 1
        self.rule_name = self.arg.rule_id
22 1
        self.out = self.arg.output
23 1
        self.all_rules = self.arg.all
24 1
        self.isatty = sys.stdout.isatty()
25 1
        self.show_failed_rules = False
26 1
        self.show_not_selected_rules = False
27 1
        self.xml_parser = XmlParser(
28
            self.source_filename)
29 1
        self.parts = self.get_src('parts')
30
31 1
    def _get_message(self):
32 1
        MESSAGES = {
33
            'description': '',
34
            '--output': '',
35
            'source_filename': '',
36
        }
37 1
        return MESSAGES
38
39 1
    def print_red_text(self, text):
40
        CRED = '\033[91m'
41
        CEND = '\033[0m'
42
        print(CRED + str(text) + CEND)
43
44 1
    def run_gui_and_return_answers(self):
45 1
        if self.isatty:
46 1
            if self.all_rules:
47
                return {'rules': self.search_rules_id()}
48
            else:
49 1
                try:
50 1
                    import inquirer
51
                    return inquirer.prompt(self.get_questions())
52 1
                except ImportError:
53 1
                    print(self.get_selection_rules())
54 1
                    return None
55
        else:
56
            return {'rules': self.search_rules_id()}
57
58 1
    def get_list_of_matched_rules(self):
59 1
        rules = self.search_rules_id()
60 1
        if self.show_failed_rules:
61 1
            rules = self._get_only_fail_rule(rules)
62 1
        return rules
63
64 1
    def get_list_of_lines(self):
65 1
        lines = ['== The Rule IDs ==']
66 1
        for rule in self.get_list_of_matched_rules():
67 1
            lines.append("'" + rule + r'\b' + "'")
68 1
        if self.show_not_selected_rules:
69 1
            for line in self.get_lines_of_wanted_not_selected_rules():
70 1
                lines.append(line)
71 1
        lines.append(
72
            "You haven't got installed inquirer lib. "
73
            "Please copy id rule with you want use and put it in command")
74 1
        return lines
75
76 1
    def get_selection_rules(self):
77 1
        return "\n".join(self.get_list_of_lines())
78
79 1
    def get_lines_of_wanted_not_selected_rules(self):
80 1
        out = []
81 1
        out.append('== The not selected rule IDs ==')
82 1
        for rule in self._get_wanted_not_selected_rules():
83 1
            out.append(rule + '(Not selected)')
84 1
        return out
85
86 1
    def get_choices(self):
87 1
        rules = self.search_rules_id()
88 1
        if self.show_failed_rules:
89 1
            rules = self._get_only_fail_rule(rules)
90 1
        choices = rules
91 1
        if self.show_not_selected_rules:
92 1
            print("\n".join(self.get_lines_of_wanted_not_selected_rules()))
93 1
        return choices
94
95 1
    def get_questions(self):
96 1
        choices = self.get_choices()
97 1
        from inquirer.questions import Checkbox as checkbox
98 1
        questions = [
99
            checkbox(
100
                'rules',
101
                message=(
102
                    "= The Rules IDs = (move - UP and DOWN arrows,"
103
                    " select - SPACE or LEFT and RIGHT arrows, submit - ENTER)"),
104
                choices=choices,
105
            ),
106
        ]
107 1
        return questions
108
109 1
    def _get_only_fail_rule(self, rules):
110 1
        return list(
111
            filter(
112
                lambda rule: self.xml_parser.used_rules[rule]['result'] == 'fail',
113
                rules))
114
115 1
    def _get_wanted_rules(self):
116 1
        return [
117
            x for x in self.xml_parser.used_rules.keys() if re.search(
118
                self.rule_name, x)]
119
120 1
    def _get_wanted_not_selected_rules(self):
121 1
        return [
122
            x for x in self.xml_parser.notselected_rules if re.search(
123
                self.rule_name, x)]
124
125 1
    def search_rules_id(self):
126 1
        rules = self._get_wanted_rules()
127 1
        notselected_rules = self._get_wanted_not_selected_rules()
128 1
        if len(notselected_rules) and not rules:
129 1
            raise ValueError(
130
                ('Rule(s) "{}" was not selected, '
131
                 "so there are no results. The rule is"
132
                 ' "notselected" because it'
133
                 " wasn't a part of the executed profile"
134
                 " and therefore it wasn't evaluated "
135
                 "during the scan.")
136
                .format(notselected_rules))
137 1
        elif not notselected_rules and not rules:
138 1
            raise ValueError('404 rule "{}" not found!'.format(self.rule_name))
139
        else:
140 1
            return rules
141
142 1
    def save_html_and_open_html(self, oval_tree_dict, src, rule, out):
143 1
        self.save_html_report(oval_tree_dict, src)
144 1
        print('Rule "{}" done!'.format(rule))
145 1
        out.append(src)
146 1
        self.open_web_browser(src)
147
148 1
    def open_web_browser(self, src):
149 1
        if not self.off_webbrowser:
150
            try:
151
                webbrowser.get('firefox').open_new_tab(src)
152
            except BaseException:
153
                webbrowser.open_new_tab(src)
154
155 1
    def get_src(self, src):
156 1
        _dir = os.path.dirname(os.path.realpath(__file__))
157 1
        FIXTURE_DIR = os.path.join(_dir, src)
158 1
        return str(FIXTURE_DIR)
159
160 1
    def get_save_src(self, rule):
161 1
        date = str(datetime.now().strftime("-%d_%m_%Y-%H_%M_%S"))
162 1
        if self.out is not None:
163 1
            os.makedirs(self.out, exist_ok=True)
164 1
            return os.path.join(
165
                self.out,
166
                'graph-of-' + rule + date + '.html')
167 1
        return os.path.join(
168
            os.getcwd(),
169
            'graph-of-' + rule + date + '.html')
170
171 1
    def _get_head(self):
172 1
        with open(os.path.join(self.parts, 'head.html'), "r") as data_file:
173 1
            head = data_file.readlines()
174 1
        return head
175
176 1
    def _get_footer(self):
177 1
        with open(os.path.join(self.parts, 'footer.html'), "r") as data_file:
178 1
            footer = data_file.readlines()
179 1
        return footer
180
181 1
    def _merge_report_parts(self, data):
182 1
        head = self._get_head()
183 1
        footer = self._get_footer()
184 1
        return [*head, data, *footer]
185
186 1
    def save_html_report(self, dict_, src):
187 1
        data = "var data_of_tree =" + str(
188
            json.dumps(dict_, sort_keys=False, indent=4) + ";")
189 1
        with open(src, "w+") as data_file:
190 1
            data_file.writelines(self._merge_report_parts(data))
191
192 1
    def parse_arguments(self, args):
193 1
        self.prepare_parser()
194 1
        args = self.parser.parse_args(args)
195 1
        return args
196
197 1
    def prepare_parser(self):
198 1
        self.parser = argparse.ArgumentParser(
199
            description=self.MESSAGES.get('description'))
200 1
        self.parser.add_argument(
201
            '--all',
202
            action="store_true",
203
            default=False,
204
            help="Process all matched rules.")
205 1
        self.parser.add_argument(
206
            '--hide-passing-tests',
207
            action="store_true",
208
            default=False,
209
            help=(
210
                "Do not display passing tests for better orientation in"
211
                " graphs that contain a large amount of nodes.(Not implemented)"))
212 1
        self.parser.add_argument(
213
            '-o',
214
            '--output',
215
            action="store",
216
            default=None,
217
            help=self.MESSAGES.get('--output'))
218 1
        self.parser.add_argument(
219
            "source_filename",
220
            help=self.MESSAGES.get('source_filename'))
221 1
        self.parser.add_argument(
222
            "rule_id", help=(
223
                "Rule ID to be visualized. A part from the full rule ID"
224
                " a part of the ID or a regular expression can be used."
225
                " If brackets are used in the regular expression "
226
                "the regular expression must be quoted."))
227