Passed
Pull Request — master (#156)
by Jan
05:03
created

Client.parse_arguments()   A

Complexity

Conditions 2

Size

Total Lines 5
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 0
Metric Value
cc 2
eloc 5
nop 2
dl 0
loc 5
ccs 4
cts 5
cp 0.8
crap 2.032
rs 10
c 0
b 0
f 0
1 1
import argparse
0 ignored issues
show
introduced by
Missing module docstring
Loading history...
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():
0 ignored issues
show
introduced by
Missing class docstring
Loading history...
best-practice introduced by
Too many instance attributes (12/7)
Loading history...
10 1
    def __init__(self, args):
11 1
        self.parser = None
12 1
        self.arg = self.parse_arguments(args)
13 1
        self.hide_passing_tests = self.arg.hide_passing_tests
14 1
        self.source_filename = self.arg.source_filename
15 1
        self.rule_name = self.arg.rule_id
16 1
        self.out = self.arg.output
17 1
        self.verbose = self.arg.verbose
18
19 1
        self.date = str(datetime.now().strftime("-%d_%m_%Y-%H_%M_%S"))
20 1
        self.isatty = sys.stdout.isatty()
21
22 1
        self.all_rules = self.arg.all
23 1
        self.show_failed_rules = False
24 1
        self.show_not_selected_rules = False
25
26 1
    @staticmethod
27
    def _get_message():
28 1
        return {
29
            'description': '',
30
            'source_filename': '',
31
        }
32
33
    #    Non-implemented functions can handle different types of the input file.
34
    #    Functions for input file processing and corresponding rule ID.
35
36 1
    def prepare_data(self, rules):
37
        """
38
        Function processes HTML graphs or JSON and
39
        return array of where is saved output file if exitsts.
40
        """
41 1
        raise NotImplementedError
42
43
    # Functions for selection of rules
44
45 1
    def search_rules_id(self):
46
        """
47
        Function retunes array of all matched IDs of rules in selected file.
48
        """
49 1
        raise NotImplementedError
50
51 1
    def get_only_fail_rule(self, rules):
52
        """
53
        Function processes array of matched IDs of rules in selected file.
54
        Function retunes array of failed matched IDs of rules in selected file.
55
        """
56 1
        raise NotImplementedError
57
58 1
    def _get_rows_of_unselected_rules(self):
59
        """
60
        Function retunes array of rows where is not selected IDs of rules in selected file.
61
        """
62 1
        raise NotImplementedError
63
64 1
    def run_gui_and_return_answers(self):
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
65 1
        if self.isatty:
66 1
            if self.all_rules:
67 1
                return self._get_rules()
68
69 1
            try:
70 1
                import inquirer
0 ignored issues
show
introduced by
Import outside toplevel (inquirer)
Loading history...
71 1
                return inquirer.prompt(self.get_questions())
72 1
            except ImportError:
73 1
                print(self.get_selection_rules())
74 1
            return None
75 1
        return self._get_rules()
76
77 1
    def _get_rules(self):
78 1
        if self.show_failed_rules:
79 1
            return {'rules': self.get_only_fail_rule(self.search_rules_id())}
80 1
        return {'rules': self.search_rules_id()}
81
82 1
    def _get_list_of_matched_rules(self):
83 1
        if self.show_failed_rules:
84 1
            return self.get_only_fail_rule(self.search_rules_id())
85 1
        return self.search_rules_id()
86
87 1
    def _get_list_of_lines(self):
88 1
        lines = ['== The Rule ID regular expressions ==']
89 1
        for rule in self._get_list_of_matched_rules():
90 1
            lines.append("^" + rule + "$")
91 1
        if self.show_not_selected_rules:
92 1
            for line in self._get_rows_of_unselected_rules():
93 1
                lines.append(line)
94 1
        lines.append(
95
            "Interactive rule selection is not available,"
96
            " because inquirer is not installed."
97
            " Copy id of the rule you want to visualize and"
98
            " paste it into a command with regular"
99
            " expression characters(^$).\n"
100
            "Alternatively, use the --all or --all-in-one arguments.")
101 1
        return lines
102
103 1
    def get_selection_rules(self):
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
104 1
        return "\n".join(self._get_list_of_lines())
105
106 1
    def _get_choices(self):
107 1
        if self.show_not_selected_rules:
108 1
            print("\n".join(self._get_rows_of_unselected_rules()))
109 1
        return self._get_list_of_matched_rules()
110
111 1
    def get_questions(self):
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
112 1
        from inquirer.questions import Checkbox as checkbox
0 ignored issues
show
introduced by
Import outside toplevel (inquirer.questions.Checkbox)
Loading history...
113 1
        choices = self._get_choices()
114 1
        questions = [
115
            checkbox(
116
                'rules',
117
                message=(
118
                    "= The Rules IDs = (move - UP and DOWN arrows,"
119
                    " select - SPACE or LEFT and RIGHT arrows, submit - ENTER)"),
120
                choices=choices,
121
            ),
122
        ]
123 1
        return questions
124
125 1
    def _get_wanted_rules(self, rules):
126 1
        return [
127
            x for x in rules if re.search(
128
                self.rule_name, x)]
129
130 1
    def _check_rules_id(self, rules, notselected_rules):
131 1
        if notselected_rules and not rules:
132 1
            raise ValueError(
133
                ('Rule(s) "{}" was not selected, '
134
                 "so there are no results. The rule is"
135
                 ' "notselected" because it'
136
                 " wasn't a part of the executed profile"
137
                 " and therefore it wasn't evaluated "
138
                 "during the scan.")
139
                .format(notselected_rules))
140 1
        if not notselected_rules and not rules:
141 1
            raise ValueError('404 rule "{}" not found!'.format(self.rule_name))
142 1
        return rules
143
144
    # Function for setting arguments
145
146 1
    def parse_arguments(self, args):
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
147 1
        self.prepare_parser()
148 1
        if args is None:
149
            return self.parser.parse_args()
150 1
        return self.parser.parse_args(args)
151
152 1
    def prepare_args_when_user_can_list_in_rules(self):
0 ignored issues
show
Coding Style Naming introduced by
Method name "prepare_args_when_user_can_list_in_rules" doesn't conform to '[a-z_][a-z0-9_]2,30$' pattern ('[a-z_][a-z0-9_]2,30$' pattern)

This check looks for invalid names for a range of different identifiers.

You can set regular expressions to which the identifiers must conform if the defaults do not match your requirements.

If your project includes a Pylint configuration file, the settings contained in that file take precedence.

To find out more about Pylint, please refer to their site.

Loading history...
introduced by
Missing function or method docstring
Loading history...
153 1
        self.parser.add_argument(
154
            '--show-failed-rules',
155
            action="store_true",
156
            default=False,
157
            help="Show only FAILED rules")
158 1
        self.parser.add_argument(
159
            '--show-not-selected-rules',
160
            action="store_true",
161
            default=False,
162
            help="Show notselected rules. These rules will not be visualized.")
163
164 1
    def prepare_parser(self):
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
165 1
        self.parser = argparse.ArgumentParser(
166
            prog='oval-graph',
167
            description=self._get_message().get('description'))
168 1
        self.parser.add_argument(
169
            '--version',
170
            action='version',
171
            version='%(prog)s ' + __version__)
172 1
        self.parser.add_argument(
173
            '-a',
174
            '--all',
175
            action="store_true",
176
            default=False,
177
            help="Process all matched rules.")
178 1
        self.parser.add_argument(
179
            '--hide-passing-tests',
180
            action="store_true",
181
            default=False,
182
            help=(
183
                "Do not display passing tests for better orientation in"
184
                " graphs that contain a large amount of nodes."))
185 1
        self.parser.add_argument(
186
            '-v',
187
            '--verbose',
188
            action="store_true",
189
            default=False,
190
            help="Displays details about the results of the running command.")
191 1
        self.parser.add_argument(
192
            '-o',
193
            '--output',
194
            action="store",
195
            default=None,
196
            help='The file where to save output.')
197 1
        self.parser.add_argument(
198
            "source_filename",
199
            help=self._get_message().get('source_filename'))
200 1
        self.parser.add_argument(
201
            "rule_id", help=(
202
                "Rule ID to be visualized. A part from the full rule ID"
203
                " a part of the ID or a regular expression can be used."
204
                " If brackets are used in the regular expression "
205
                "the regular expression must be quoted."))
206