-
Notifications
You must be signed in to change notification settings - Fork 6
/
addonfactory_splunk_conf_parser_lib.py
245 lines (217 loc) · 9.01 KB
/
addonfactory_splunk_conf_parser_lib.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
#
# Copyright 2024 Splunk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import configparser
from os import SEEK_SET
from typing import Any, Dict
COMMENT_PREFIX = ";#*"
COMMENT_KEY = "__COMMENTS__"
class TABConfigParser(configparser.RawConfigParser):
"""
This class is used to override the Python built-in ConfigParser, because
TA builder needs to support:
1. Read/write .conf files with comments
2. Additional comment prefix such as *
3. Support multiline end with \
"""
_defaults: Dict[Any, Any]
_sections: Dict[Any, Any]
_optcre: Dict[Any, Any]
def _read(self, fp, fpname):
"""
Override the built-in _read() method to read comments
"""
from configparser import DEFAULTSECT, ParsingError
cursect = None # None, or a dictionary
optname = None
lineno = 0
e = None # None, or an exception
comment_index = 0
self.top_comments = []
self.fields_outside_stanza = []
add_space_to_next_line = False
while True:
line = fp.readline()
if not line:
break
lineno = lineno + 1
line = line.strip(" ")
# comment or blank line?
if line.strip() == "" or line[0] in COMMENT_PREFIX:
# save the lineno & comments
if cursect:
name = f"{COMMENT_KEY}{comment_index}"
comment_index += 1
cursect[name] = line
else:
self.top_comments.append(line)
continue
if line.split(None, 1)[0].lower() == "rem" and line[0] in "rR":
# no leading whitespace
continue
# continuation line?
# support multiline with \
if add_space_to_next_line:
line = " " + line
if line.strip().endswith("\\"):
line = line.rstrip("\\ ")
add_space_to_next_line = True
else:
add_space_to_next_line = False
if line[0].isspace() and cursect is not None and optname:
value = line.strip()
if value:
cursect[optname].append(value)
# a section header or option header?
else:
# is it a section header?
mo = self.SECTCRE.match(line)
if mo:
sectname = mo.group("header")
if sectname in self._sections:
cursect = self._sections[sectname]
elif sectname == DEFAULTSECT:
cursect = self._defaults
else:
cursect = self._dict()
cursect["__name__"] = sectname
self._sections[sectname] = cursect
self._proxies[sectname] = configparser.SectionProxy(
self, sectname
)
# So sections can't start with a continuation line
optname = None
# no section header in the file?
elif cursect is None:
# disable the exception since splunk allows the field outside stanzas
# raise MissingSectionHeaderError(fpname, lineno, line)
self.fields_outside_stanza.append(line)
# an option line?
else:
mo = self._optcre.match(line)
if mo:
optname, vi, optval = mo.group("option", "vi", "value")
optname = self.optionxform(optname.rstrip())
# This check is fine because the OPTCRE cannot
# match if it would set optval to None
if optval is not None:
if vi in ("=", ":") and ";" in optval:
# ';' is a comment delimiter only if it follows
# a spacing character
pos = optval.find(";")
if pos != -1 and optval[pos - 1].isspace():
optval = optval[:pos]
optval = optval.strip()
# allow empty values
if optval == '""':
optval = ""
cursect[optname] = [optval]
else:
# valueless option handling
cursect[optname] = optval
else:
# a non-fatal parsing error occurred. set up the
# exception but keep going. the exception will be
# raised at the end of the file and will contain a
# list of all bogus lines
if not e:
e = ParsingError(fpname)
e.append(lineno, repr(line))
# if any parsing errors occurred, raise an exception
if e:
raise e
# join the multi-line values collected while reading
all_sections = [self._defaults]
all_sections.extend(list(self._sections.values()))
for options in all_sections:
for name, val in list(options.items()):
if isinstance(val, list):
options[name] = "\n".join(val)
# As the type of `fp` is not defined in RawConfigParser (parent class)
# we define the type of `fp` as Any
def write(self, fp: Any, *args) -> None:
"""
Override the write() method to write comments
"""
DEFAULTSECT = "DEFAULT"
if hasattr(self, "top_comments"):
for comment in self.top_comments:
fp.write(comment)
if hasattr(self, "fields_outside_stanza"):
for field in self.fields_outside_stanza:
fp.write(field)
if self._defaults:
fp.write("[%s]\n" % DEFAULTSECT)
for (key, value) in list(self._defaults.items()):
fp.write("{} = {}\n".format(key, str(value).replace("\n", "\n\t")))
fp.write("\n")
for section in self._sections:
fp.write("[%s]\n" % section)
for (key, value) in list(self._sections[section].items()):
if key == "__name__":
continue
if key.startswith(COMMENT_KEY):
# only write the non empty line
if len(value.strip()) > 0:
fp.write(value)
# should continue as long as it is a comment line
continue
if (value is not None) or (self._optcre == self.OPTCRE):
key = " = ".join((key, str(value).replace("\n", "\n\t")))
fp.write("%s\n" % (key))
# write the separator line for stanza
fp.write("\n")
# multiple lines are added when there are stanzas/sections and its properties,
# hence we check if there are stanzas/sections before truncating the trailing newline
if self._defaults or self._sections:
# remove the trailing lines in a file, as the content should be written as-is
fp.seek(fp.tell() - 1, SEEK_SET)
fp.truncate()
def optionxform(self, optionstr):
return optionstr
def items(self, section):
"""
Override the items() method to filter out the comments
"""
items = configparser.RawConfigParser.items(self, section)
res = []
for k, v in items:
if k.startswith(COMMENT_KEY):
continue
res.append((k, v))
return res
def options(self, section):
options = configparser.RawConfigParser.options(self, section)
res = []
for opt in options:
if opt.startswith(COMMENT_KEY):
continue
res.append(opt)
return res
def item_dict(self):
res = {}
sections = dict(self._sections)
for section, key_values in list(sections.items()):
kv = {}
for k, v in list(key_values.items()):
if (
not isinstance(k, str)
or k.startswith(COMMENT_KEY)
or k == "__name__"
):
continue
kv[k] = v
res[section] = kv
return res