Passed
Pull Request — master (#46)
by Jan
05:51
created

oscap_report.cli   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 176
Duplicated Lines 0 %

Test Coverage

Coverage 77.5%

Importance

Changes 0
Metric Value
eloc 135
dl 0
loc 176
ccs 62
cts 80
cp 0.775
rs 10
c 0
b 0
f 0
wmc 12

8 Methods

Rating   Name   Duplication   Size   Complexity  
A CommandLineAPI._parse_arguments() 0 9 1
A CommandLineAPI.__init__() 0 10 1
B CommandLineAPI._prepare_arguments() 0 56 1
A CommandLineAPI._setup_logging() 0 6 1
A CommandLineAPI.close_files() 0 4 1
A CommandLineAPI.generate_report() 0 10 2
A CommandLineAPI.load_file() 0 3 1
A CommandLineAPI.store_file() 0 6 2

1 Function

Rating   Name   Duplication   Size   Complexity  
A main() 0 17 2
1 1
import argparse
2 1
import logging
3 1
from sys import exit as sys_exit
4 1
from sys import stdin, stdout
5
6 1
from lxml.etree import XMLSyntaxError
7
8 1
from . import __version__
9 1
from .html_report.report_generator import ReportGenerator
10 1
from .old_html_report_style.report_generator import \
11
    ReportGenerator as OldOSCAPReportGenerator
12 1
from .scap_results_parser.scap_results_parser import SCAPResultsParser
13
14 1
DESCRIPTION = ("Generate a HTML (JSON, PDF?, Printable HTML, etc) document (HTML report)"
15
               " from an ARF (or XCCDF file) containing results of oscap scan. Unless"
16
               " the --output option is specified it will be written to standard output.")
17 1
LOG_LEVES_DESCRIPTION = (
18
    "LOG LEVELS:\n"
19
    "\tDEBUG - Detailed information, typically of interest only when diagnosing problems.\n"
20
    "\tINFO - Confirmation that things are working as expected.\n"
21
    "\tWARING -  An indication that something unexpected happened, or indicative of"
22
    " some problem in the near future. The software is still working as expected.\n"
23
    "\tERROR - Due to a more serious problem, the software has not been able to perform "
24
    "some function.\n"
25
    "\tCRITICAL - A serious error, indicating that the program itself may be unable "
26
    "to continue running.\n"
27
)
28 1
DEBUG_FLAGS_DESCRIPTION = (
29
    "DEBUG FLAGS:\n"
30
    "\tNO-MINIFY - The HTML report is not minified."
31
)
32
33 1
MASSAGE_FORMAT = '%(levelname)s: %(message)s'
34 1
EXPECTED_ERRORS = (XMLSyntaxError, )
35 1
EXIT_FAILURE_CODE = 1
36 1
EXIT_SUCCESS_CODE = 0
37
38
39 1
class CommandLineAPI():
40 1
    def __init__(self):
41 1
        self.arguments = self._parse_arguments()
42 1
        self.log_file = self.arguments.log_file
43 1
        self.log_level = self.arguments.log_level
44 1
        self.debug_flags = self.arguments.debug
45 1
        self._setup_logging()
46 1
        logging.debug("Args: %s", self.arguments)
47 1
        self.report_file = self.arguments.FILE
48 1
        self.output_file = self.arguments.output
49 1
        self.output_format = self.arguments.format.upper()
50
51 1
    def _parse_arguments(self):
52 1
        parser = argparse.ArgumentParser(
53
            prog="oscap-report",
54
            formatter_class=argparse.RawTextHelpFormatter,
55
            description=DESCRIPTION,
56
            add_help=False,
57
        )
58 1
        self._prepare_arguments(parser)
59 1
        return parser.parse_args()
60
61 1
    @staticmethod
62 1
    def _prepare_arguments(parser):
63 1
        parser.add_argument(
64
            "--version",
65
            action="version",
66
            version="%(prog)s " + __version__,
67
            help="Show program's version number and exit.")
68 1
        parser.add_argument(
69
            '-h',
70
            '--help',
71
            action='help',
72
            default=argparse.SUPPRESS,
73
            help='Show this help message and exit.')
74 1
        parser.add_argument(
75
            'FILE',
76
            type=argparse.FileType("r"),
77
            nargs='?',
78
            default=stdin,
79
            help="ARF file, stdin if not provided.")
80 1
        parser.add_argument(
81
            "-o",
82
            "--output",
83
            action="store",
84
            type=argparse.FileType("wb+", 0),
85
            default=stdout,
86
            help="write the report to this file instead of standard output.")
87 1
        parser.add_argument(
88
            "--log-file",
89
            action="store",
90
            default=None,
91
            help="if not provided - stderr.")
92 1
        parser.add_argument(
93
            "--log-level",
94
            action="store",
95
            default="WARNING",
96
            choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
97
            help=(
98
                "creates LOG_FILE file with log information depending on LOG_LEVEL."
99
                f"\n{LOG_LEVES_DESCRIPTION}")
100
        )
101 1
        parser.add_argument(
102
            "-f",
103
            "--format",
104
            action="store",
105
            default="HTML",
106
            choices=["HTML", "OLD-STYLE-HTML"],
107
            help="FORMAT: %(choices)s (default: %(default)s)."
108
        )
109 1
        parser.add_argument(
110
            "-d",
111
            "--debug",
112
            action="store",
113
            nargs='+',
114
            default=[""],
115
            choices=["NO-MINIFY"],
116
            help=f"{DEBUG_FLAGS_DESCRIPTION}"
117
        )
118
119 1
    def _setup_logging(self):
120 1
        logging.basicConfig(
121
            format=MASSAGE_FORMAT,
122
            filename=self.log_file,
123
            filemode='w',
124
            level=self.log_level.upper()
125
        )
126
127 1
    def generate_report(self, report_parser):
128 1
        logging.info("Generate report")
129 1
        if self.output_format == "OLD-STYLE-HTML":
130
            report_generator = OldOSCAPReportGenerator(report_parser)
131
            return report_generator.generate_html_report()
132 1
        report_generator = ReportGenerator(report_parser)
133
134 1
        minify = "NO-MINIFY" not in self.debug_flags
135
136 1
        return report_generator.generate_html_report(minify)
137
138 1
    def load_file(self):
139 1
        logging.info("Loading file: %s", self.report_file)
140 1
        return self.report_file.read().encode()
141
142 1
    def store_file(self, data):
143 1
        logging.info("Store report")
144 1
        if self.output_file.name == "<stdout>":
145
            logging.info("Output is stdout, converting bytes output to str")
146
            data = data.read().decode("utf-8")
147 1
        self.output_file.writelines(data)
148
149 1
    def close_files(self):
150 1
        logging.info("Close files")
151 1
        self.report_file.close()
152 1
        self.output_file.close()
153
154
155 1
def main():
156
    exit_code = EXIT_SUCCESS_CODE
157
    api = CommandLineAPI()
158
    arf_report = api.load_file()
159
160
    logging.info("Parse file")
161
    try:
162
        parser = SCAPResultsParser(arf_report)
163
164
        report = api.generate_report(parser)
165
166
        api.store_file(report)
167
    except EXPECTED_ERRORS as error:
168
        logging.fatal("%s", error)
169
        exit_code = EXIT_FAILURE_CODE
170
    api.close_files()
171
    sys_exit(exit_code)
172
173
174 1
if __name__ == '__main__':
175
    main()
176