Passed
Push — master ( f92a60...087b33 )
by Matěj
02:24 queued 11s
created

oval_graph.client.Client.prepare_data()   A

Complexity

Conditions 3

Size

Total Lines 17
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 17
nop 2
dl 0
loc 17
ccs 15
cts 15
cp 1
crap 3
rs 9.55
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 json
6 1
import shutil
7 1
from datetime import datetime
8
9 1
from .xml_parser import XmlParser
10 1
from .converter import Converter
11
12
13 1
class Client():
14 1
    def __init__(self, args):
15 1
        self.parser = None
16 1
        self.arg = self.parse_arguments(args)
17 1
        self.remove_pass_tests = self.arg.remove_pass_tests
18 1
        self.show_fail_rules = self.arg.show_fail_rules
19 1
        self.show_not_selected_rules = self.arg.show_not_selected_rules
20 1
        self.source_filename = self.arg.source_filename
21 1
        self.rule_name = self.arg.rule_id
22 1
        self.out = self.arg.out
23 1
        self.xml_parser = XmlParser(
24
            self.source_filename)
25 1
        if self.remove_pass_tests:
26
            raise NotImplementedError('Not implemented!')
27
28 1
    def run_gui_and_return_answers(self):
29 1
        try:
30 1
            import inquirer
31
            return inquirer.prompt(self.get_questions())
32 1
        except ImportError:
33 1
            print('== The Rule IDs ==')
34 1
            rules = self.search_rules_id()
35 1
            if self.show_fail_rules:
36 1
                rules = self._get_only_fail_rule(rules)
37 1
            for rule in rules:
38 1
                print(rule['id_rule'] + r'\b')
39 1
            if self.show_not_selected_rules:
40 1
                print('== The not selected rule IDs ==')
41 1
                for rule in self._get_wanted_not_selected_rules():
42 1
                    print(rule['id_rule'] + '(Not selected)')
43 1
            print("You haven't got installed inquirer lib. "
44
                  "Please copy id rule with you want use and put it in command")
45 1
            return None
46
47 1
    def get_questions(self):
48 1
        rules = self.search_rules_id()
49 1
        if self.show_fail_rules:
50 1
            rules = self._get_only_fail_rule(rules)
51 1
        choices_ = []
52 1
        for rule in rules:
53 1
            choices_.append(rule['id_rule'])
54 1
        if self.show_not_selected_rules:
55 1
            print('== The not selected rule IDs ==')
56 1
            for rule in self._get_wanted_not_selected_rules():
57 1
                print(rule['id_rule'] + '(Not selected)')
58 1
        from inquirer.questions import Checkbox as checkbox
59 1
        questions = [
60
            checkbox(
61
                'rules',
62
                message=(
63
                    "= The Rules IDs = (move - UP and DOWN arrows,"
64
                    " select - SPACE or LEFT and RIGHT arrows, submit - ENTER)"),
65
                choices=choices_,
66
            ),
67
        ]
68 1
        return questions
69
70 1
    def _get_only_fail_rule(self, rules):
71 1
        return list(filter(lambda rule: rule['result'] == 'fail', rules))
72
73 1
    def _get_wanted_rules(self):
74 1
        return [
75
            x for x in self.xml_parser.get_used_rules() if re.search(
76
                self.rule_name, x['id_rule'])]
77
78 1
    def _get_wanted_not_selected_rules(self):
79 1
        return [
80
            x for x in self.xml_parser.get_notselected_rules() if re.search(
81
                self.rule_name, x['id_rule'])]
82
83 1
    def search_rules_id(self):
84 1
        rules = self._get_wanted_rules()
85 1
        notselected_rules = self._get_wanted_not_selected_rules()
86 1
        if len(notselected_rules) and not rules:
87 1
            raise ValueError(
88
                ('err- rule(s) "{}" was not selected, '
89
                 "so there are no results. The rule is"
90
                 ' "notselected" because it'
91
                 " wasn't a part of the executed profile"
92
                 " and therefore it wasn't evaluated "
93
                 "during the scan.")
94
                .format(notselected_rules[0]['id_rule']))
95 1
        elif not notselected_rules and not rules:
96 1
            raise ValueError('err- 404 rule not found!')
97
        else:
98 1
            return rules
99
100 1
    def create_dict_of_rule(self, rule_id):
101
        parser = XmlParser(self.source_filename)
102
        converter = Converter(parser.get_oval_tree(rule_id))
103
        return converter.to_JsTree_dict()
104
105 1
    def save_dict(self, dict_, src):
106
        with open(os.path.join(src, 'data.js'), "w+") as data_file:
107
            data_file.write("var data_json =" + str(json.dumps(
108
                dict_, sort_keys=False, indent=4) + ";"))
109
110 1
    def copy_interpreter(self, dst):
111
        src = self.XmlParser.get_src(self.html_interpreter)
112
        os.mkdir(dst)
113
        for item in os.listdir(src):
114
            s = os.path.join(src, item)
115
            d = os.path.join(dst, item)
116
            if os.path.isdir(s):
117
                shutil.copytree(s, d)
118
            else:
119
                shutil.copy2(s, d)
120
121 1
    def get_save_src(self, rule):
122 1
        date = str(datetime.now().strftime("_%d-%m-%Y_%H:%M:%S"))
123 1
        if self.out is not None:
124 1
            if not os.path.isdir(self.out):
125 1
                os.mkdir(self.out)
126 1
                return os.path.join(self.out, 'graph-of-' + rule + date)
127
            return os.path.join(
128
                self.out,
129
                'graph-of-' + rule + date)
130 1
        return os.path.join(
131
            tempfile.gettempdir(),
132
            'graph-of-' + rule + date)
133
134 1
    def parse_arguments(self, args):
135 1
        self.prepare_parser()
136 1
        args = self.parser.parse_args(args)
137 1
        return args
138
139 1
    def prepare_parser(self):
140 1
        self.parser = argparse.ArgumentParser(
141
            description="Client for visualization of SCAP rule evaluation results")
142 1
        self.parser.add_argument(
143
            '--show-fail-rules',
144
            action="store_true",
145
            default=False,
146
            help="Show only FAIL rules")
147 1
        self.parser.add_argument(
148
            '--show-not-selected-rules',
149
            action="store_true",
150
            default=False,
151
            help="Show notselected rules. These rules will not be visualized.")
152 1
        self.parser.add_argument(
153
            '--out',
154
            action="store",
155
            default=None,
156
            help="The directory where to save output files.")
157 1
        self.parser.add_argument(
158
            '--remove-pass-tests',
159
            action="store_true",
160
            default=False,
161
            help=(
162
                "Do not display passing tests for better orientation in"
163
                " graphs that contain a large amount of nodes.(Not implemented)"))
164 1
        self.parser.add_argument("source_filename", help="ARF scan file")
165 1
        self.parser.add_argument(
166
            "rule_id", help=(
167
                "Rule ID to be visualized. A part from the full rule ID"
168
                " a part of the ID or a regular expression can be used."
169
                " If brackets are used in the regular expression "
170
                "the regular expression must be quoted."))
171