Skip to content

Instantly share code, notes, and snippets.

@samdoran
Last active July 8, 2022 01:47
Show Gist options
  • Save samdoran/f4f47075caa3be379789b5172c08a8c6 to your computer and use it in GitHub Desktop.
Save samdoran/f4f47075caa3be379789b5172c08a8c6 to your computer and use it in GitHub Desktop.
def _maketrans(self, replace_chars, replacement_chars, delete_chars):
if PY3:
return str.maketrans(replace_chars, replacement_chars, delete_chars)
if not isinstance(replace_chars, text_type) or not isinstance(replacement_chars, text_type):
raise ValueError('replace_chars and replacement_chars must both be strings')
if len(replace_chars) != len(replacement_chars):
raise ValueError('replacement_chars must be the same length as replace_chars')
table = dict(zip((ord(c) for c in replace_chars), replacement_chars))
for char in delete_chars:
table[ord(char)] = None
return table
def _scrub_hostname(self, name):
"""LocalHostName only accepts valid DNS characters while HostName and ComputerName
accept a much wider range of characters. This functions aims to mimic how macOS
translates a friendly name to the LocalHostName.
"""
# Replace all these characters with a single dash
name = to_text(name)
replace_chars = '\'"~`!@#$%^&*(){}[]/=?+\\|-_ '
delete_chars = ".'"
table = self._maketrans(replace_chars, '-' * len(replace_chars), delete_chars)
name = name.translate(table)
# Replace multiple dashes with a single dash
while '-' * 2 in name:
name = name.replace('-' * 2, '')
name = name.rstrip('-')
return name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment