Skip to content

Instantly share code, notes, and snippets.

@PIlin
Forked from quarnster/cmake_options_script.py
Last active December 11, 2015 18:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PIlin/4641812 to your computer and use it in GitHub Desktop.
Save PIlin/4641812 to your computer and use it in GitHub Desktop.
# Based on @berenm's pull request https://github.com/quarnster/SublimeClang/pull/135
# Create the database with cmake with for example: cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON ..
# or you could have set(CMAKE_EXPORT_COMPILE_COMMANDS ON) in your CMakeLists.txt
# Usage within SublimeClang:
# "sublimeclang_options_script": "python ${home}/code/cmake_options_script.py ",
# 2013.01.26: Pavlo Ilin
# - Removed the usage of cache file - if cmake-scripts are changed often,
# cache file quickly becomes old and wrong.
# - Will recursively go up in directory tree and try to find compile_commands.json
# using predefined search patterns (dbfile_search_pattern)
# - Will try to guess options for files which are not listed in compile_commands.json
# Those files are, mostly, header files. See guess_option()
import re
import os
import os.path
import sys
import json
#from pprint import pprint
compilation_database_pattern = re.compile('(?<=\s)-[DIOUWfgs][^=\s]+(?:=\\"[^"]+\\"|=[^"]\S+)?')
dbfile_search_patterns = [r'/build/compile_commands.json',
r'/debug/compile_commands.json',
r'/release/compile_commands.json']
def find_dffile(path):
for dbfile_pat in dbfile_search_patterns:
dbfile = path + dbfile_pat
if os.path.isfile(dbfile):
return dbfile
# not found
newpath = os.path.dirname(path)
if path == newpath:
raise Exception(r'Unable to find ' + dbfile_pat)
return find_dffile(newpath)
def load_db(filename):
compilation_database = {}
with open(filename) as compilation_database_file:
compilation_database_entries = json.load(compilation_database_file)
entry = 0
for compilation_entry in compilation_database_entries:
entry = entry + 1
compilation_database[compilation_entry["file"]] = [ p.strip() for p in compilation_database_pattern.findall(compilation_entry["command"]) ]
return compilation_database
def guess_option(filename, db):
guessed = []
name, ext = os.path.splitext(filename)
guesses = [name + '.cpp', name + '.c']
for key in db.iterkeys():
if key.endswith('main.cpp'):
guesses.append(key)
break
for g in guesses:
if os.path.isfile(g):
# print ('guessed = ', g)
for opt in db[g]:
guessed.append(opt)
break
return guessed
srcfile = sys.argv[1]
dbfile = find_dffile(os.path.dirname(srcfile))
dbpath = os.path.dirname(dbfile)
db = load_db(dbfile)
if db:
if srcfile in db:
for option in db[srcfile]:
print option
else:
for option in guess_option(srcfile, db):
print option
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment