From c7bfb5d2db2a060b81ba93ec076e5a9cf0995bd7 Mon Sep 17 00:00:00 2001 From: Micke Nordin Date: Mon, 28 Mar 2022 20:10:08 +0200 Subject: [PATCH] Make formated output valid nagios config --- src/nag_object.py | 44 ++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 40 insertions(+), 4 deletions(-) diff --git a/src/nag_object.py b/src/nag_object.py index 1e70396..e4907e9 100644 --- a/src/nag_object.py +++ b/src/nag_object.py @@ -1,6 +1,34 @@ +import shlex from enum import Enum +def wrap(input: str, ws_base, max_length=70) -> str: + output: str = str() + if len(input) < max_length: + return input + + temp = shlex.split(input, posix=False) + length = len(temp[0]) + whitespace = str() + for _ in range(0, ws_base): + whitespace += " " + separator = " \\\n " + whitespace + for i in range(0, len(temp)): + if i < len(temp) - 1: + if length + len(temp[i]) < max_length: + output += " " + temp[i] + length += len(temp[i + 1]) + else: + output += separator + temp[i] + length = len(temp[i]) + len(" \\\n\t\t") + else: + if length < max_length - len(temp[i]): + output += " " + temp[i] + else: + output += separator + temp[i] + return output + + class NagObjectType(Enum): Command = "command" ContactGroup = "contactgroup" @@ -18,6 +46,7 @@ class NagObjectType(Enum): class NagObject: + def __init__(self, config_file: str = str(), directives: list[list[str]] = list(), @@ -29,11 +58,18 @@ class NagObject: self.m_type: NagObjectType = type def __str__(self): - string = "{}:\n\t{}: {}\n".format(self.m_config_file, self.m_line_no, - self.m_type) + string = 'define {}'.format(self.m_type.value) + ' {\n' + ws_base = len(max([x[0] for x in self.m_directives], key=len)) + 4 for dir in self.m_directives: - string += "\t\t{}: {}\n".format(dir[0], dir[1]) - return string + num_whitespace = ws_base - len(dir[0]) + + whitespace = str() + for _ in range(0, num_whitespace): + whitespace += " " + string += ' {}{}{}\n'.format( + dir[0], whitespace, + wrap(dir[1], ws_base).strip().strip('\\\n').strip()) + return string + '}\n' def get_type(self) -> NagObjectType: return self.m_type