Test Failed
Pull Request — master (#187)
by Jan
02:35
created

Client._get_wanted_rules()   A

Complexity

Conditions 1

Size

Total Lines 4
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
nop 2
crap 2
1
import argparse
2
import re
3
import sys
4
from datetime import datetime
5
6
from .. import __version__
7
8
9
class Client():
10
    def __init__(self, args):
11
        self.arg = self.parse_arguments(args)
12
13
        self.source_filename = self.arg.source_filename
14
        self.rule_name = self.arg.rule_id
15
16
        self.isatty = sys.stdout.isatty()
17
18
        self.all_rules = self.arg.all
19
        self.show_failed_rules = False
20
        self.show_not_selected_rules = False
21
22
    @staticmethod
23
    def _get_message():
24
        return {
25
            'description': '',
26
            'source_filename': '',
27
        }
28
29
    @staticmethod
30
    def _get_date():
31
        return str(datetime.now().strftime("-%d_%m_%Y-%H_%M_%S"))
32
33
    # Functions for selection of rules
34
35
    def search_rules_id(self):
36
        """
37
        Function retunes array of all matched IDs of rules in selected file.
38
        """
39
        raise NotImplementedError
40
41
    def get_only_fail_rule(self, rules):
42
        """
43
        Function processes array of matched IDs of rules in selected file.
44
        Function retunes array of failed matched IDs of rules in selected file.
45
        """
46
        raise NotImplementedError
47
48
    def _get_rows_of_unselected_rules(self):
49
        """
50
        Function retunes array of rows where is not selected IDs of rules in selected file.
51
        """
52
        raise NotImplementedError
53
54
    def run_gui_and_return_answers(self):
55
        if self.isatty:
56
            if self.all_rules:
57
                return self._get_rules()
58
59
            try:
60
                import inquirer
0 ignored issues
show
introduced by
Import outside toplevel (inquirer)
Loading history...
61
                return inquirer.prompt(self.get_questions())
62
            except ImportError:
63
                print(self.get_selection_rules())
64
            return None
65
        return self._get_rules()
66
67
    def _get_rules(self):
68
        if self.show_failed_rules:
69
            return {'rules': self.get_only_fail_rule(self.search_rules_id())}
70
        return {'rules': self.search_rules_id()}
71
72
    def _get_list_of_matched_rules(self):
73
        if self.show_failed_rules:
74
            return self.get_only_fail_rule(self.search_rules_id())
75
        return self.search_rules_id()
76
77
    def _get_list_of_lines(self):
78
        lines = ['== The Rule ID regular expressions ==']
79
        for rule in self._get_list_of_matched_rules():
80
            lines.append("^" + rule + "$")
81
        if self.show_not_selected_rules:
82
            for line in self._get_rows_of_unselected_rules():
83
                lines.append(line)
84
        lines.append(
85
            "Interactive rule selection is not available,"
86
            " because inquirer is not installed."
87
            " Copy id of the rule you want to visualize and"
88
            " paste it into a command with regular"
89
            " expression characters(^$).\n"
90
            "Alternatively, use the --all or --all-in-one arguments.")
91
        return lines
92
93
    def get_selection_rules(self):
94
        return "\n".join(self._get_list_of_lines())
95
96
    def _get_choices(self):
97
        if self.show_not_selected_rules:
98
            print("\n".join(self._get_rows_of_unselected_rules()))
99
        return self._get_list_of_matched_rules()
100
101
    def get_questions(self):
102
        from inquirer.questions import Checkbox as checkbox
0 ignored issues
show
introduced by
Import outside toplevel (inquirer.questions.Checkbox)
Loading history...
103
        choices = self._get_choices()
104
        questions = [
105
            checkbox(
106
                'rules',
107
                message=(
108
                    "= The Rules IDs = (move - UP and DOWN arrows,"
109
                    " select - SPACE or LEFT and RIGHT arrows, submit - ENTER)"),
110
                choices=choices,
111
            ),
112
        ]
113
        return questions
114
115
    def _get_wanted_rules(self, rules):
116
        return [
117
            x for x in rules if re.search(
118
                self.rule_name, x)]
119
120
    def _check_rules_id(self, rules, notselected_rules):
121
        if notselected_rules and not rules:
122
            raise ValueError(
123
                ('Rule(s) "{}" was not selected, '
124
                 "so there are no results. The rule is"
125
                 ' "notselected" because it'
126
                 " wasn't a part of the executed profile"
127
                 " and therefore it wasn't evaluated "
128
                 "during the scan.")
129
                .format(notselected_rules))
130
        if not notselected_rules and not rules:
131
            raise ValueError('404 rule "{}" not found!'.format(self.rule_name))
132
        return rules
133
134
    # Function for setting arguments
135
136
    def parse_arguments(self, args):
137
        parser = argparse.ArgumentParser(
138
            prog='oval-graph',
139
            description=self._get_message().get('description'))
140
        self.prepare_parser(parser)
141
        if args is None:
142
            return parser.parse_args()
143
        return parser.parse_args(args)
144
145
    @staticmethod
146
    def prepare_args_when_user_can_list_in_rules(parser):
147
        parser.add_argument(
148
            '--show-failed-rules',
149
            action="store_true",
150
            default=False,
151
            help="Show only FAILED rules")
152
        parser.add_argument(
153
            '--show-not-selected-rules',
154
            action="store_true",
155
            default=False,
156
            help="Show notselected rules. These rules will not be visualized.")
157
158
    def prepare_parser(self, parser):
159
        parser.add_argument(
160
            '--version',
161
            action='version',
162
            version='%(prog)s ' + __version__)
163
        parser.add_argument(
164
            '-a',
165
            '--all',
166
            action="store_true",
167
            default=False,
168
            help="Process all matched rules.")
169
        parser.add_argument(
170
            '--hide-passing-tests',
171
            action="store_true",
172
            default=False,
173
            help=(
174
                "Do not display passing tests for better orientation in"
175
                " graphs that contain a large amount of nodes."))
176
        parser.add_argument(
177
            '-v',
178
            '--verbose',
179
            action="store_true",
180
            default=False,
181
            help="Displays details about the results of the running command.")
182
        parser.add_argument(
183
            '-o',
184
            '--output',
185
            action="store",
186
            default=None,
187
            help='The file where to save output.')
188
        parser.add_argument(
189
            "source_filename",
190
            help=self._get_message().get('source_filename'))
191
        parser.add_argument(
192
            "rule_id", help=(
193
                "Rule ID to be visualized. A part from the full rule ID"
194
                " a part of the ID or a regular expression can be used."
195
                " If brackets are used in the regular expression "
196
                "the regular expression must be quoted."))
197