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