-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathargs.py
More file actions
270 lines (204 loc) · 7.76 KB
/
args.py
File metadata and controls
270 lines (204 loc) · 7.76 KB
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
#! /usr/bin/env python3
# -*- coding: utf-8; py-indent-offset: 4 -*-
#
# Author: Linuxfabrik GmbH, Zurich, Switzerland
# Contact: info (at) linuxfabrik (dot) ch
# https://www.linuxfabrik.ch/
# License: The Unlicense, see LICENSE file.
# https://github.com/Linuxfabrik/monitoring-plugins/blob/main/CONTRIBUTING.rst
"""Extends argparse by new input argument data types on demand.
"""
__author__ = 'Linuxfabrik GmbH, Zurich/Switzerland'
__version__ = '2025091501'
HELP_TEXTS = {
'--match': (
'Uses Python regular expressions without any external flags like `re.IGNORECASE`. '
'The regular expression is applied to each line of the output. '
'Examples: '
'`(?i)example` to match the word "example" in a case-insensitive manner. '
'`^(?!.*example).*$` to match any string except "example" (negative lookahead). '
'`(?: ... )*` is a non-capturing group that matches any sequence of characters '
'that satisfy the condition inside it, zero or more times.'
),
'--stratum': (
'Warns if the determined stratum of the time server is greater than or equal to this '
'value. '
'Stratum 1 indicates a computer with a locally attached reference clock. A computer that '
'is synchronised to a stratum 1 computer is at stratum 2. A computer that is synchronised '
'to a stratum 2 computer is at stratum 3, and so on.'
),
'--verbose': (
'Makes this plugin verbose during the operation. Useful for debugging and seeing '
'what\'s going on under the hood.'
),
}
# Predefined sets for checking units and methods
_UNITS = {'%', 'K', 'M', 'G', 'T', 'P'}
_METHODS = {'USED', 'FREE'}
def csv(arg):
"""
Converts a CSV string into a list of values.
This function takes a comma-separated string (CSV format) and returns a list where each element
corresponds to a value in the CSV string. Leading and trailing whitespace from each value is
removed.
### Parameters
- **arg** (`str`): A string containing values separated by commas (CSV format).
### Returns
- **list**: A list of strings, each representing an element from the CSV input string.
### Example
>>> csv("apple, orange, banana, grape")
['apple', 'orange', 'banana', 'grape']
>>> csv(" one, two, three , four ")
['one', 'two', 'three', 'four']
"""
return [x.strip() for x in arg.split(',')]
def float_or_none(arg):
"""
Converts an input to a float, or returns None if the input is 'none' or None.
This function attempts to convert the input argument into a float. If the input is `None` or
the string 'none' (case insensitive), the function returns `None`. Otherwise, it returns the
argument as a float.
### Parameters
- **arg** (`str`, `None`, or `float`): The input value that will be converted to a float or
returned as `None`.
### Returns
- **float** or **None**: Returns the input as a float if it is convertible, or `None` if the
input is 'none' or `None`.
### Example
>>> float_or_none('123.45')
123.45
>>> float_or_none('none')
None
>>> float_or_none(None)
None
"""
if arg is None:
return None
if isinstance(arg, str) and arg.strip().lower() == 'none':
return None
return float(arg)
def help(param):
"""
Retrieves the help text for a given parameter.
This function returns the global help text associated with a specific parameter. It contains
explanations for the valid options and usage of the parameter. If no help text is available
for the parameter, it returns an empty string.
### Parameters
- **param** (`str`): The parameter for which help text is to be retrieved.
### Returns
- **str**: The help text for the given parameter, or an empty string if the parameter is not
found.
### Example
>>> help('--match')
Lorem ipsum
>>> help('--nonexistent')
''
"""
return HELP_TEXTS.get(param, '')
def int_or_none(arg):
"""
Converts a given argument to an integer or returns None.
This function checks if the argument is `None` or the string `'none'`, in which case it returns
`None`. Otherwise, it attempts to convert the argument to an integer and returns the result.
### Parameters
- **arg** (`str` or `None`): The input value to be converted to an integer, or `None`.
### Returns
- **int** or **None**: The integer value of the argument if it can be converted, or `None` if
the argument is `None` or `'none'`.
### Example
>>> int_or_none('42')
42
>>> int_or_none('none')
None
>>> int_or_none(None)
None
"""
if arg is None:
return None
if isinstance(arg, str) and arg.strip().lower() == 'none':
return None
return int(arg)
def number_unit_method(arg, unit='%', method='USED'):
"""
Parses a string representing a number with an optional unit and method, and returns the
corresponding components.
This function expects an input string in the format `<number>[unit][method]`, typically
used for threshold arguments. The function extracts and returns the numeric value, unit
(defaults to `%`), and method (defaults to `USED`). The function supports various units
such as `K`, `M`, `G`, `T`, `P`, and `%`, and methods like `USED` and `FREE`.
### Parameters
- **arg** (`str`): The input string representing the number, unit, and method.
- **unit** (`str`, optional): The unit of measurement, one of `%%|K|M|G|T|P`. Defaults to `%`.
- **method** (`str`, optional): The method used, one of `USED|FREE`. Defaults to `USED`.
### Returns
- **tuple**: A tuple containing:
- **str**: The numeric value.
- **str**: The unit (defaults to `%` if not specified).
- **str**: The method (defaults to `USED` if not specified).
### Example
>>> number_unit_method('95')
('95.0', '%', 'USED')
>>> number_unit_method('9.5M')
('9.5', 'M', 'USED')
>>> number_unit_method('95%USED')
('95.0', '%', 'USED')
>>> number_unit_method('5FREE')
('5.0', '%', 'FREE')
>>> number_unit_method('5%FREE')
('5.0', '%', 'FREE')
>>> number_unit_method('9.5GFREE')
('9.5', 'G', 'FREE')
>>> number_unit_method('1400GUSED')
('1400.0', 'G', 'USED')
"""
arg = arg.strip()
number_part = []
unit_part = ''
method_part = ''
i = 0
while i < len(arg) and (arg[i].isdigit() or arg[i] == '.'):
number_part.append(arg[i])
i += 1
if i < len(arg) and arg[i].upper() in _UNITS:
unit_part = arg[i]
i += 1
if i < len(arg):
method_part = arg[i:].upper()
number = ''.join(number_part)
if not number:
return '0.0', unit.upper(), method.upper()
if unit_part:
unit = unit_part
if method_part in _METHODS:
method = method_part
return number, unit.upper(), method.upper()
def range_or_none(arg):
"""
See str_or_none()
"""
return str_or_none(arg)
def str_or_none(arg):
"""
Converts an input argument into a string or returns `None`.
This function checks if the input is `None` or the string `"none"` (case-insensitive) and
returns `None` in those cases. Otherwise, it returns the input as a string.
### Parameters
- **arg** (`any`): The input argument that can be any type.
### Returns
- **str** or **None**: If the input is not `None` or `"none"`, it returns the input as a
string; otherwise, it returns `None`.
### Example
>>> str_or_none(123)
'123'
>>> str_or_none('none')
None
>>> str_or_none(None)
None
"""
if arg is None:
return None
if isinstance(arg, str):
if arg.strip().lower() == 'none':
return None
return arg
return str(arg)