Passed
Push — master ( 009541...003b5e )
by Jan
01:36 queued 12s
created

oval_graph.client.Client._get_footer()   A

Complexity

Conditions 2

Size

Total Lines 4
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

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