|
1 # -*- coding: UTF-8 -*- |
|
2 # Copyright (c) 2010, Pascal Volk |
|
3 # See COPYING for distribution information. |
|
4 |
|
5 """ |
|
6 VirtualMailManager.common |
|
7 |
|
8 Some common functions |
|
9 """ |
|
10 |
|
11 import os |
|
12 |
|
13 from VirtualMailManager import ENCODING |
|
14 from VirtualMailManager.constants.ERROR import \ |
|
15 NOT_EXECUTABLE, NO_SUCH_BINARY, NO_SUCH_DIRECTORY |
|
16 from VirtualMailManager.errors import VMMError |
|
17 |
|
18 _ = lambda msg: msg |
|
19 |
|
20 |
|
21 def expand_path(path): |
|
22 """Expands paths, starting with ``.`` or ``~``, to an absolute path.""" |
|
23 if path.startswith('.'): |
|
24 return os.path.abspath(path) |
|
25 if path.startswith('~'): |
|
26 return os.path.expanduser(path) |
|
27 return path |
|
28 |
|
29 |
|
30 def get_unicode(string): |
|
31 """Converts `string` to `unicode`, if necessary.""" |
|
32 if isinstance(string, unicode): |
|
33 return string |
|
34 return unicode(string, ENCODING, 'replace') |
|
35 |
|
36 |
|
37 def is_dir(path): |
|
38 """Checks if `path` is a directory. |
|
39 |
|
40 Throws a `VMMError` if `path` is not a directory. |
|
41 """ |
|
42 path = expand_path(path) |
|
43 if not os.path.isdir(path): |
|
44 raise VMMError(_(u"'%s' is not a directory") % get_unicode(path), |
|
45 NO_SUCH_DIRECTORY) |
|
46 return path |
|
47 |
|
48 |
|
49 def exec_ok(binary): |
|
50 """Checks if the `binary` exists and if it is executable. |
|
51 |
|
52 Throws a `VMMError` if the `binary` isn't a file or is not |
|
53 executable. |
|
54 """ |
|
55 binary = expand_path(binary) |
|
56 if not os.path.isfile(binary): |
|
57 raise VMMError(_(u"'%s' is not a file") % get_unicode(binary), |
|
58 NO_SUCH_BINARY) |
|
59 if not os.access(binary, os.X_OK): |
|
60 raise VMMError(_(u"File is not executable: '%s'") % |
|
61 get_unicode(binary), NOT_EXECUTABLE) |
|
62 return binary |
|
63 |
|
64 |
|
65 def version_hex(version_string): |
|
66 """Convert the version string '1.2.3' to an int. |
|
67 hex(version_hex('1.2.3')) -> '0x10203' |
|
68 """ |
|
69 major, minor, patch = map(int, version_string.split('.')) |
|
70 return (major << 16) + (minor << 8) + patch |
|
71 |
|
72 del _ |