Last active
August 29, 2015 14:12
-
-
Save codebrainz/fd235843965c2601f727 to your computer and use it in GitHub Desktop.
Getting a list of header dependencies using GCC -MM
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| import argparse | |
| import json | |
| import re | |
| import sys | |
| from collections import OrderedDict | |
| from subprocess import Popen, PIPE | |
| RE_INC = re.compile(r'^(?P<target>.+?):\s+(?P<deps>.+?)$', re.MULTILINE) | |
| SPACE_TOK = '\x1B' | |
| def parse_deps(input_text): | |
| text = input_text.replace('\\\n', ' ').replace('\\ ', SPACE_TOK) | |
| deps = OrderedDict() | |
| for match in RE_INC.finditer(text): | |
| target = match.group('target').replace(SPACE_TOK, ' ') | |
| files = [f.replace(SPACE_TOK, ' ') for f in match.group('deps').split()] | |
| deps[target] = files | |
| return deps | |
| def list_stdin_deps(encoding='utf-8'): | |
| return parse_deps(sys.stdin.read().decode(encoding)) | |
| def list_cmd_deps(cmd, encoding='utf-8'): | |
| cmd = [cmd[0], '-MM'] + cmd[1:] if len(cmd) > 1 else [] | |
| proc = Popen(cmd, stdout=PIPE) | |
| text = proc.stdout.read().decode(encoding) | |
| return parse_deps(text) | |
| if __name__ == '__main__': | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument('-e', '--encoding', metavar='ENC', dest='encoding', | |
| default='utf-8', help="input encoding (default 'utf-8')") | |
| parser.add_argument('-o', '--output', metavar='FILE', dest='output', | |
| default='-', help="output file (default '-' for stdout)") | |
| parser.add_argument('-c', '--command', metavar='CMD', dest='command', | |
| nargs=argparse.REMAINDER, default='-', | |
| help="read from CMD command (default '-' for stdin)") | |
| args = parser.parse_args() | |
| if args.command == '-': | |
| deps = list_stdin_deps(encoding=args.encoding) | |
| else: | |
| deps = list_cmd_deps(args.command, encoding=args.encoding) | |
| if args.output == '-': | |
| print(json.dumps(deps, indent=2)) | |
| else: | |
| with open(args.output, 'w') as out_file: | |
| out_file.write(json.dumps(deps, indent=2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment