summaryrefslogtreecommitdiff
path: root/assert
blob: 4b31b5d9efcd63de32362f7a04305aeb816a096d (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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#!/usr/bin/python


import gnomevfs
import optparse
import os
import subprocess
import sys


def setup_option_parser():
    parser = optparse.OptionParser()
    
    parser.add_option("--file", metavar="FILE",
                      help="Report FILE as being failing the assertion.")
    
    return parser


def equal(options, args):
    return args[0] == args[1], "%s != %s" % (repr(args[0]), repr(args[1]))


def mime_type_is(options, args):
    wanted_type = args[0]
    args = args[1:]
    for arg in args:
        uri = gnomevfs.get_uri_from_local_path(os.path.abspath(arg))
        actual_type = gnomevfs.get_mime_type(uri)
        if actual_type != wanted_type:
            options.file = arg
            return False, "%s != %s" % (wanted_type, actual_type)
    return True, None


def file_type_is(options, args):
    wanted_type = args[0]
    filenames = args[1:]
    for filename in filenames:
        p = subprocess.Popen(["file", "-0", filename], stdout=subprocess.PIPE)
        stdout, stderr = p.communicate()
        if p.returncode == 0:
            filename, actual_type = stdout.split("\0")
            actual_type = actual_type.strip()
            if actual_type != wanted_type:
                return False, "%s != %s" % (wanted_type, actual_type)
    return True, None


def main():
    parser = setup_option_parser()
    options, args = parser.parse_args()
    
    opers = {
        "equal": (2, 2, equal),
        "file-type-is": (2, None, file_type_is),
        "mime-type-is": (2, None, mime_type_is),
    }
    
    if not args:
        raise Exception("No operation on command line.")
    elif args[0] in opers:
        name = args[0]
        args = args[1:]
        min_count, max_count, func = opers[name]
        if (len(args) < min_count or 
            (max_count is not None and len(args) > max_count)):
            raise Exception("Operation %s must have %d..%d "
                            "arguments (got %d)." %
                            (name, min_count, max_count or "infinity", 
                             len(args)))
        ok, msg = func(options, args)
        if not ok:
            parts = []
            if options.file:
                parts.append("%s: " % options.file)
            parts.append("Assertion failed: ")
            parts.append(msg or " ".join(sys.argv[1:]))
            raise Exception("".join(parts))
    else:
        raise Exception("Unknown operation '%s'." % args[0])


if __name__ == "__main__":
    try:
        main()
    except Exception, e:
        sys.stderr.write("%s\n" % str(e))
        sys.exit(1)