Skip to content

Instantly share code, notes, and snippets.

@kergoth
Created July 18, 2012 14:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kergoth/3136618 to your computer and use it in GitHub Desktop.
Save kergoth/3136618 to your computer and use it in GitHub Desktop.
import os
valid_path = "/usr/local/bin:/usr/bin"
invalid_path = "/usr/local/bin::/usr/bin"
invalid_path2 = "/usr/local/bin:.:/usr/bin"
class InvalidPath(Exception):
def __init__(self, path, entry, position, char_position):
self.path = path
self.entry = entry
self.position = position
self.char_position = char_position
def as_string(self, indent_offset=0):
prefix = 'Invalid path entry `%s` at char %d: ' % (self.entry, self.char_position)
indent = ' ' * (1 + len(prefix) + self.char_position + indent_offset)
return prefix + '%s\n%s^' % (self.path, indent)
def __str__(self):
return self.as_string()
def validate_path(path):
location = 0
for position, entry in enumerate(path.split(':')):
if not entry or not os.path.isabs(entry):
raise InvalidPath(path, entry, position, location)
location += len(entry)
validate_path(valid_path)
try:
validate_path(invalid_path)
except InvalidPath as exc:
print("ERROR: " + exc.as_string(indent_offset=7))
try:
validate_path(invalid_path2)
except InvalidPath as exc:
print("ERROR: " + exc.as_string(indent_offset=7))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment