Debian Codegraph @

pyxs/helpers.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 pyxs.helpers
4 ~~~~~~~~~~~~
5
6 Implements various helpers.
7
8 :copyright: (c) 2011 by Selectel, see AUTHORS for more details.
9 :license: LGPL, see LICENSE for more details.
10 """
11
12 from __future__ import absolute_import
13
14 __all__ = ["check_path", "check_watch_path", "check_perms", "error"]
15
16 import errno
17 import re
18 import os
19 import posixpath
20
21 from .exceptions import InvalidPath, InvalidPermission, PyXSError
22
23
24 #: A reverse mapping for :data:`errno.errorcode`.
25 _codeerror = dict((message, code)
26 for code, message in errno.errorcode.items())
27
28
29 def error(smth):
30 """Returns a :class:`~pyxs.exceptions.PyXSError` matching a given
31 errno or error name.
32
33 >>> error(22)
34 pyxs.exceptions.PyXSError: (22, 'Invalid argument')
35 >>> error(b"EINVAL")
36 pyxs.exceptions.PyXSError: (22, 'Invalid argument')
37 """
38 if isinstance(smth, bytes):
39 smth = _codeerror.get(smth.decode(), 0)
40
41 return PyXSError(smth, os.strerror(smth))
42
43
44 _re_path = re.compile(br"^[a-zA-Z0-9-/_@]+\x00?$")
45
46
47 def check_path(path):
48 """Checks if a given path is valid, see
49 :exc:`~pyxs.exceptions.InvalidPath` for details.
50
51 :param bytes path: path to check.
52 :raises pyxs.exceptions.InvalidPath: when path fails to validate.
53 """
54 # Paths longer than 3072 bytes are forbidden; clients specifying
55 # relative paths should keep them to within 2048 bytes.
56 max_len = 3072 if posixpath.abspath(path) else 2048
57 if not _re_path.match(path) or len(path) > max_len:
58 raise InvalidPath(path)
59
60 # A path is not allowed to have a trailing /, except for the
61 # root path and shouldn't have double //'s.
62 if (len(path) > 1 and path.endswith(b"/")) or b"//" in path:
63 raise InvalidPath(path)
64
65 return path
66
67
68 _re_watch_path = re.compile(br"^@(?:introduceDomain|releaseDomain)\x00?$")
69
70
71 def check_watch_path(wpath):
72 """Checks if a given watch path is valid -- it should either be a
73 valid path or a special, starting with ``@`` character.
74
75 :param bytes wpath: watch path to check.
76 :raises pyxs.exceptions.InvalidPath: when path fails to validate.
77 """
78 if wpath.startswith(b"@") and not _re_watch_path.match(wpath):
79 raise InvalidPath(wpath)
80 else:
81 check_path(wpath)
82
83 return wpath
84
85
86 _re_perms = re.compile(br"^[wrbn]\d+$")
87
88
89 def check_perms(perms):
90 """Checks if a given list of permision follows the format described
91 in :exc:`~pyxs.exceptions.InvalidPermissions`.
92
93 :param list perms: permissions to check.
94 :raises pyxs.exceptions.InvalidPermissions:
95 when any of the permissions fails to validate.
96 """
97 for perm in perms:
98 if not _re_perms.match(perm):
99 raise InvalidPermission(perm)
100
101 return perms