-
Notifications
You must be signed in to change notification settings - Fork 23
/
utils.py
51 lines (40 loc) · 1.61 KB
/
utils.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
import string
from typing import List
from collections import namedtuple
def truncate(text: str = "", max_len: int = 50) -> str:
"""
Ensure a string complies to the maximum length specified.
:param text: Text to be checked for length and truncated if necessary
:param max_len: Max length of the returned string
:return: Text in :param text: truncated to :param max_len: if necessary
"""
return text if len(text) < max_len else text[:max_len]
def format_slug(text: str) -> str:
"""
Format string to comply to NetBox slug acceptable pattern and max length.
:param text: Text to be formatted into an acceptable slug
:return: Slug of allowed characters [-a-zA-Z0-9_] with max length of 50
"""
allowed_chars = (
string.ascii_lowercase # Alphabet
+ string.digits # Numbers
+ "_-" # Symbols
)
# Convert to lowercase
text = text.lower()
# Replace separators with dash
text = text.translate({ord(sep): ord('-') for sep in " ,."})
# Strip unacceptable characters
text = ''.join(c for c in text if c in allowed_chars)
# Enforce max length
return truncate(text, max_len=50)
def remove_empty_fields(obj: dict) -> dict:
"""
Removes empty fields from NetBox objects.
This ensures NetBox objects do not return invalid None values in fields.
:param obj: A NetBox formatted object
"""
return {k: v for k, v in obj.items() if v is not None}
def remove_duplicates(lst: list) -> list:
return [i for n, i in enumerate(lst) if i not in lst[n + 1:]]
# return [key for key, group in itertools.groupby(lst, lambda x: x)]