1#!/usr/bin/env python3
2
3import argparse
4import itertools
5import json
6import posixpath
7import re
8
9
10def match_any(regex, iterable):
11    """Check whether any element in iterable matches regex."""
12    return any(regex.match(elem) for elem in iterable)
13
14
15class ModuleInfo(object):
16    def __init__(self, module_info_path):
17        with open(module_info_path, 'r') as module_info_file:
18            self._json = json.load(module_info_file)
19
20
21    def list(self, installed_filter=None, module_definition_filter=None):
22        for name, info in self._json.items():
23            installs = info['installed']
24            paths = info['path']
25
26            if installed_filter and not match_any(installed_filter, installs):
27                    continue
28            if module_definition_filter and \
29               not match_any(module_definition_filter, paths):
30                    continue
31
32            for install, path in itertools.product(installs, paths):
33                yield (install, path)
34
35
36def _parse_args():
37    """Parse command line arguments"""
38
39    parser = argparse.ArgumentParser()
40
41    parser.add_argument('module_info', help='Path to module-info.json')
42
43    parser.add_argument('--out-dir', default='out',
44                        help='Android build output directory')
45
46    parser.add_argument('--installed-filter',
47                        help='Installation filter (regular expression)')
48
49    parser.add_argument('--module-definition-filter',
50                        help='Module definition filter (regular expression)')
51
52    return parser.parse_args()
53
54
55def main():
56    """Main function"""
57
58    args = _parse_args()
59
60    installed_filter = None
61    if args.installed_filter:
62        installed_filter = re.compile(
63            re.escape(posixpath.normpath(args.out_dir)) + '/' +
64            '(?:' + args.installed_filter + ')')
65
66    module_definition_filter = None
67    if args.module_definition_filter:
68        module_definition_filter = re.compile(args.module_definition_filter)
69
70    module_info = ModuleInfo(args.module_info)
71
72    for installed_file, module_path in \
73            module_info.list(installed_filter, module_definition_filter):
74        print(installed_file, module_path)
75
76
77if __name__ == '__main__':
78    main()
79