summaryrefslogtreecommitdiff
path: root/packages/alpm.py
blob: a7f4c3b5062fdf138a624bde22e39433e1650dd8 (plain)
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import ctypes
from ctypes.util import find_library
import operator


def load_alpm(name=None):
    # Load the alpm library and set up some of the functions we might use
    if name == None:
        name = find_library('alpm')
    try:
        alpm = ctypes.cdll.LoadLibrary(name)
    except OSError:
        return None
    alpm.alpm_version.argtypes = ()
    alpm.alpm_version.restype = ctypes.c_char_p
    alpm.alpm_pkg_vercmp.argtypes = (ctypes.c_char_p, ctypes.c_char_p)
    alpm.alpm_pkg_vercmp.restype = ctypes.c_int
    return alpm


ALPM = load_alpm()

class AlpmAPI(object):
    OPERATOR_MAP = {
        '=':  operator.eq,
        '==': operator.eq,
        '!=': operator.ne,
        '<':  operator.lt,
        '<=': operator.le,
        '>':  operator.gt,
        '>=': operator.ge,
    }

    def __init__(self):
        self.alpm = ALPM
        self.available = ALPM is not None

    def version(self):
        if not self.available:
            return None
        return ALPM.alpm_version()

    def vercmp(self, ver1, ver2):
        if not self.available:
            return None
        return ALPM.alpm_pkg_vercmp(str(ver1), str(ver2))

    def compare_versions(self, ver1, oper, ver2):
        func = self.OPERATOR_MAP.get(oper, None)
        if func is None:
            raise Exception("Invalid operator %s specified" % oper)
        if not self.available:
            return None
        res = self.vercmp(ver1, ver2)
        return func(res, 0)


def main():
    api = AlpmAPI()
    print api.version()
    print api.vercmp(1, 2)
    print api.compare_versions(1, '<', 2)


if __name__ == '__main__':
    main()

# vim: set ts=4 sw=4 et: