Passed
Pull Request — rhel8-branch (#147)
by Jan
01:46
created

ParseHTMLContent.handle_data()   A

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nop 2
dl 0
loc 2
rs 10
c 0
b 0
f 0
1
#
2
# Copyright (C) 2013  Red Hat, Inc.
3
#
4
# This copyrighted material is made available to anyone wishing to use,
5
# modify, copy, or redistribute it subject to the terms and conditions of
6
# the GNU General Public License v.2, or (at your option) any later version.
7
# This program is distributed in the hope that it will be useful, but WITHOUT
8
# ANY WARRANTY expressed or implied, including the implied warranties of
9
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
10
# Public License for more details.  You should have received a copy of the
11
# GNU General Public License along with this program; if not, write to the
12
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
13
# 02110-1301, USA.  Any Red Hat trademarks that are incorporated in the
14
# source code or documentation are not subject to the GNU General Public
15
# License and may only be used or replicated with the express permission of
16
# Red Hat, Inc.
17
#
18
# Red Hat Author(s): Vratislav Podzimek <[email protected]>
19
#
20
21
"""
22
Module with various classes for SCAP content processing and retrieving data
23
from it.
24
25
"""
26
27
import os.path
28
29
from collections import namedtuple
30
from pyanaconda.core.util import execReadlines
31
try:
32
    from html.parser import HTMLParser
33
except ImportError:
34
    from HTMLParser import HTMLParser
35
36
37
class ParseHTMLContent(HTMLParser):
38
    """Parser class for HTML tags within content"""
39
40
    def __init__(self):
41
        HTMLParser.__init__(self)
42
        self.content = ""
43
44
    def handle_starttag(self, tag, attrs):
45
        if tag == "html:ul":
46
            self.content += "\n"
47
        elif tag == "html:li":
48
            self.content += "\n"
49
        elif tag == "html:br":
50
            self.content += "\n"
51
52
    def handle_endtag(self, tag):
53
        if tag == "html:ul":
54
            self.content += "\n"
55
        elif tag == "html:li":
56
            self.content += "\n"
57
58
    def handle_data(self, data):
59
        self.content += data.strip()
60
61
    def get_content(self):
62
        return self.content
63
64
65
def parse_HTML_from_content(content):
66
    """This is a very simple HTML to text parser.
67
68
    HTML tags will be removed while trying to maintain readability
69
    of content.
70
71
    :param content: content whose HTML tags will be parsed
72
    :return: content without HTML tags
73
    """
74
75
    parser = ParseHTMLContent()
76
    parser.feed(content)
77
    return parser.get_content()
78
79
80
# namedtuple class for info about content files found
81
# pylint: disable-msg=C0103
82
ContentFiles = namedtuple("ContentFiles", ["xccdf", "cpe", "tailoring"])
83
84
85
def explore_content_files(fpaths):
86
    """
87
    Function for finding content files in a list of file paths. SIMPLY PICKS
88
    THE FIRST USABLE CONTENT FILE OF A PARTICULAR TYPE AND JUST PREFERS DATA
89
    STREAMS OVER STANDALONE BENCHMARKS.
90
91
    :param fpaths: a list of file paths to search for content files in
92
    :type fpaths: [str]
93
    :return: ContentFiles instance containing the file names of the XCCDF file,
94
        CPE dictionary and tailoring file or "" in place of those items
95
        if not found
96
    :rtype: ContentFiles
97
98
    """
99
100
    def get_doc_type(file_path):
101
        try:
102
            for line in execReadlines("oscap", ["info", file_path]):
103
                if line.startswith("Document type:"):
104
                    _prefix, _sep, type_info = line.partition(":")
105
                    return type_info.strip()
106
        except OSError:
107
            # 'oscap info' exitted with a non-zero exit code -> unknown doc
108
            # type
109
            return None
110
111
    xccdf_file = ""
112
    cpe_file = ""
113
    tailoring_file = ""
114
    found_ds = False
115
116
    for fpath in fpaths:
117
        doc_type = get_doc_type(fpath)
118
        if not doc_type:
119
            continue
120
121
        # prefer DS over standalone XCCDF
122
        if doc_type == "Source Data Stream" and (not xccdf_file or not found_ds):
123
            xccdf_file = fpath
124
            found_ds = True
125
        elif doc_type == "XCCDF Checklist" and not xccdf_file:
126
            xccdf_file = fpath
127
        elif doc_type == "CPE Dictionary" and not cpe_file:
128
            cpe_file = fpath
129
        elif doc_type == "XCCDF Tailoring" and not tailoring_file:
130
            tailoring_file = fpath
131
132
    # TODO: raise exception if no xccdf_file is found?
133
    files = ContentFiles(xccdf_file, cpe_file, tailoring_file)
134
    return files
135