Passed
Pull Request — master (#199)
by Jan
06:32 queued 01:25
created

Client._get_wanted_rules()   A

Complexity

Conditions 1

Size

Total Lines 4
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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