#!/usr/bin/env python3 import json import subprocess import os def is_source_file(filepath): return filepath.endswith('.c') or filepath.endswith('.h') or filepath.endswith('.S') dir_stack = [] rootdir = os.getcwd() compile_db = [] make_output = subprocess.check_output(['make', '-nw']).decode('utf-8') make_output_lines = make_output.split('\n') for line in make_output_lines: line_parts = line.split(' ') new_line_parts = [] if len(line_parts) >= 2 and 'Entering directory' in line: new_dir = line[line.find('`') + 1:-1] dir_stack.append(new_dir) continue if len(line_parts) >= 2 and 'Leaving directory' in line: dir_stack.pop() continue; if 'gcc' not in line_parts[0]: continue src_file = '' for part in line_parts: part = part.strip() if is_source_file(part): src_file = part part = os.path.join(dir_stack[-1], part) new_line_parts.append(part) if len(src_file) == 0: continue db_entry = { 'directory': dir_stack[-1], 'command': ' '.join(new_line_parts).strip(), 'file': os.path.join(dir_stack[-1], src_file) } compile_db.append(db_entry) os.system('make') out_file = open('build/compile_commands.json', 'w') json.dump(compile_db, out_file, indent=4)