-# This function makes it easy to pull in additional flags from rospack
-def rospack():
- cmd = ['rospack', 'cflags-only-I']
- try:
- out = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE).stdout
- except:
- return []
- line = out.readline()[:-1].split(" ")
- includes = []
- for include in line:
- if include.startswith(os.path.expanduser('~')):
- includes += ['-I', include]
- else:
- includes += ['-isystem', include]
- return filter(lambda a: a != ' ', includes)
+HEADER_EXTENSIONS = [
+ '.h',
+ '.hxx',
+ '.hpp',
+ '.hh'
+]
+
+
+def similarity_ratio(s, t):
+ return difflib.SequenceMatcher(a=s.lower(), b=t.lower()).ratio()
+
+
+def generate_qt_flags():
+ flags = ['-isystem', '/usr/include/qt/']
+ for p in glob('/usr/include/qt/*/'):
+ flags += ['-isystem', p]
+ return flags
+
+
+def find_similar_file_in_database(dbpath, filename):
+ import json
+ logging.info("Trying to find some file close to: " + filename)
+ db = json.load(open(dbpath))
+ best_filename = ''
+ best_ratio = 0
+ for entry in db:
+ entry_filename = os.path.normpath(os.path.join(entry["directory"],
+ entry["file"]))
+ ratio = similarity_ratio(str(filename), str(entry_filename))
+ if ratio > best_ratio:
+ best_filename = entry_filename
+ best_ratio = ratio
+ return best_filename
+
+def ok_compilation_info(info):
+ return bool(info.compiler_flags_)
+
+def get_compilation_info_for_file(dbpath, database, filename):
+ info = database.GetCompilationInfoForFile(filename)
+ if ok_compilation_info(info):
+ logging.info("Flags for file where found in database: " + filename)
+ return info
+ else:
+ logging.info("Flags for file not found in database: " + filename)
+ basename = os.path.splitext(filename)[0]
+ for extension in SOURCE_EXTENSIONS:
+ replacement_file = basename + extension
+ logging.info("Trying to replace extension with: " + extension)
+ info = database.GetCompilationInfoForFile(replacement_file)
+ if ok_compilation_info(info):
+ logging.info("Replacing header with: " + replacement_file)
+ return info
+ replacement_file = find_similar_file_in_database(dbpath, filename)
+ logging.info("Replacing header with: " + replacement_file)
+ return database.GetCompilationInfoForFile(replacement_file)
+
+
+def find_nearest_compilation_database(root='.'):
+ dirs = glob(root + '/*/compile_commands.json', recursive=True)
+
+ if len(dirs) == 1:
+ return dirs[0]
+ elif len(dirs) > 1:
+ logging.info("Multiple compilation databases found!")
+ logging.info(dirs)
+ logging.info("Selecting first: %s" % (dir))
+ return dirs[0]
+
+ parent = os.path.dirname(os.path.abspath(root))
+ if parent == root:
+ raise RuntimeError("Could not find compile_commands.json")
+ return find_nearest_compilation_database(parent)