1#!/usr/bin/env python3
2from argparse import ArgumentParser
3import os
4import json
5import re
6
7def actorFile(actor: str, build: str, src: str):
8    res = actor.replace(build, src, 1)
9    res = res.replace('actor.g.cpp', 'actor.cpp')
10    return res.replace('actor.g.h', 'actor.h')
11
12def rreplace(s, old, new, occurrence = 1):
13    li = s.rsplit(old, occurrence)
14    return new.join(li)
15
16
17def actorCommand(cmd: str, build:str, src: str):
18    r1 = re.compile('-c (.+)(actor\.g\.cpp)')
19    m1 = r1.search(cmd)
20    if m1 is None:
21        return cmd
22    cmd1 = r1.sub('\\1actor.cpp', cmd)
23    return rreplace(cmd1, build, src)
24
25
26parser = ArgumentParser(description="Generates a new compile_commands.json for rtags+flow")
27parser.add_argument("-b", help="Build directory", dest="builddir", default=os.getcwd())
28parser.add_argument("-s", help="Build directory", dest="srcdir", default=os.getcwd())
29parser.add_argument("-o", help="Output file", dest="out", default="processed_compile_commands.json")
30parser.add_argument("input", help="compile_commands.json", default="compile_commands.json", nargs="?")
31args = parser.parse_args()
32
33print("transform {} with build directory {}".format(args.input, args.builddir))
34
35with open(args.input) as f:
36    cmds = json.load(f)
37
38result = []
39
40for cmd in cmds:
41    cmd['command'] = cmd['command'].replace(' -DNO_INTELLISENSE ', ' ')
42    if cmd['file'].endswith('actor.g.cpp'):
43        # here we need to rewrite the rule
44        cmd['command'] = actorCommand(cmd['command'], args.builddir, args.srcdir)
45        cmd['file'] = actorFile(cmd['file'], args.builddir, args.srcdir)
46        result.append(cmd)
47    else:
48        result.append(cmd)
49
50with open(args.out, 'w') as f:
51    json.dump(result, f, indent=4)
52