Craig Tiller | 0b2a372 | 2015-01-18 11:30:07 -0800 | [diff] [blame] | 1 | #!/usr/bin/python |
| 2 | # produces cleaner build.json files |
| 3 | |
| 4 | import collections |
| 5 | import json |
| 6 | import os |
| 7 | import sys |
| 8 | |
Craig Tiller | d4eeff8 | 2015-01-19 20:51:28 -0800 | [diff] [blame] | 9 | TEST = (os.environ.get('TEST', 'false') == 'true') |
| 10 | |
Craig Tiller | 0b2a372 | 2015-01-18 11:30:07 -0800 | [diff] [blame] | 11 | _TOP_LEVEL_KEYS = ['settings', 'filegroups', 'libs', 'targets'] |
| 12 | _VERSION_KEYS = ['major', 'minor', 'micro', 'build'] |
| 13 | _ELEM_KEYS = [ |
| 14 | 'name', |
| 15 | 'build', |
| 16 | 'language', |
| 17 | 'public_headers', |
| 18 | 'headers', |
| 19 | 'src', |
| 20 | 'deps'] |
| 21 | |
| 22 | def rebuild_as_ordered_dict(indict, special_keys): |
| 23 | outdict = collections.OrderedDict() |
| 24 | for key in special_keys: |
| 25 | if key in indict: |
| 26 | outdict[key] = indict[key] |
| 27 | for key in sorted(indict.keys()): |
| 28 | if key in special_keys: continue |
| 29 | outdict[key] = indict[key] |
| 30 | return outdict |
| 31 | |
| 32 | def clean_elem(indict): |
| 33 | for name in ['public_headers', 'headers', 'src']: |
| 34 | if name not in indict: continue |
| 35 | inlist = indict[name] |
| 36 | protos = set(x for x in inlist if os.path.splitext(x)[1] == '.proto') |
| 37 | others = set(x for x in inlist if x not in protos) |
| 38 | indict[name] = sorted(protos) + sorted(others) |
| 39 | return rebuild_as_ordered_dict(indict, _ELEM_KEYS) |
| 40 | |
| 41 | for filename in sys.argv[1:]: |
| 42 | with open(filename) as f: |
| 43 | js = json.load(f) |
| 44 | js = rebuild_as_ordered_dict(js, _TOP_LEVEL_KEYS) |
| 45 | js['settings']['version'] = rebuild_as_ordered_dict( |
| 46 | js['settings']['version'], _VERSION_KEYS) |
| 47 | for grp in ['filegroups', 'libs', 'targets']: |
| 48 | if grp not in js: continue |
| 49 | js[grp] = sorted([clean_elem(x) for x in js[grp]], |
Craig Tiller | 7d7b6c7 | 2015-01-18 12:03:17 -0800 | [diff] [blame] | 50 | key=lambda x: (x.get('language', '_'), x['name'])) |
Craig Tiller | 0b2a372 | 2015-01-18 11:30:07 -0800 | [diff] [blame] | 51 | output = json.dumps(js, indent = 2) |
| 52 | # massage out trailing whitespace |
| 53 | lines = [] |
| 54 | for line in output.splitlines(): |
| 55 | lines.append(line.rstrip() + '\n') |
Craig Tiller | d4eeff8 | 2015-01-19 20:51:28 -0800 | [diff] [blame] | 56 | output = ''.join(lines) |
| 57 | if TEST: |
| 58 | with open(filename) as f: |
| 59 | assert f.read() == output |
| 60 | else: |
| 61 | with open(filename, 'w') as f: |
| 62 | f.write(output) |
Craig Tiller | 0b2a372 | 2015-01-18 11:30:07 -0800 | [diff] [blame] | 63 | |