Created
May 16, 2024 23:08
-
-
Save bc-lee/8707d1e62d14f8bb6bd30ef6e67f1625 to your computer and use it in GitHub Desktop.
parse-compile-commands
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 | |
# SPDX-FileCopyrightText: 2024 Byoungchan Lee | |
# SPDX-FileContributor: Byoungchan Lee | |
# SPDX-License-Identifier: MIT | |
__doc__ == """ | |
This script cleans up the compile_commands.json file generated by gn or other | |
build systems. It removes flags that are not essential for understanding | |
the build commands, making the file easier to use with tools like | |
clangd and CLion. | |
""" | |
import errno | |
import json | |
import os | |
import re | |
import sys | |
COMPILE_COMMANDS = "compile_commands.json" | |
RE_ccache = re.compile(r"[^\" ]*ccache\s+") | |
RE_deps = re.compile(r"-MMD\s+-MF\s+\S+\s+") | |
RE_invalid = re.compile(r"libsrtp2 2.1.0-pre") | |
def usage(): | |
print( | |
"Usage: {} path/to/compile_commands.json (output file) ".format(sys.argv[0]) + \ | |
"If output file is not provided, the default output file is '{}'".format(COMPILE_COMMANDS), | |
file=sys.stderr) | |
sys.exit(1) | |
def main(argv): | |
if len(argv) not in (1, 2): | |
usage() | |
input_file = argv[0] | |
try: | |
output_file = argv[1] | |
except IndexError: | |
output_file = COMPILE_COMMANDS | |
if os.path.isdir(input_file): | |
input_file = os.path.join(input_file, COMPILE_COMMANDS) | |
with open(input_file) as f: | |
data = json.load(f) | |
for item in data: | |
command = item.get("command") | |
if command is not None: | |
# Do whatever you want cleaning up the command here | |
command = RE_ccache.sub("", command) | |
command = RE_deps.sub("", command) | |
command = RE_invalid.sub("libsrtp2\\ 2.1.0-pre", command) | |
item["command"] = command | |
output_file_dir = os.path.dirname(os.path.abspath(output_file)) | |
try: | |
os.makedirs(output_file_dir, exist_ok=True) | |
except OSError as e: | |
if e.errno != errno.EEXIST or not os.path.isdir(output_file_dir): | |
raise e | |
with open(output_file, "w") as f: | |
json.dump(data, f, indent=2) | |
if __name__ == "__main__": | |
sys.exit(main(sys.argv[1:])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment