Skip to content

Instantly share code, notes, and snippets.

@ntrrgc
Created July 31, 2017 09:44
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 ntrrgc/cf8e99d24da3b00d277fd71698725e84 to your computer and use it in GitHub Desktop.
Save ntrrgc/cf8e99d24da3b00d277fd71698725e84 to your computer and use it in GitHub Desktop.
Script to import CMake flags into a QtCreator project file
#!/usr/bin/env python
# Usage: python patch-qtcreator-project.py CMakeLists.txt.user -DPORT=GTK -DENABLE_MEDIA_SOURCE=ON ...
from argparse import ArgumentParser
from xml.etree import ElementTree
def clean_cmake_args(cmake_args):
"""
Not all arguments are relevant for QtCreator.
Returns a list with only the relevant ones.
:param list[string] cmake_args:
:return list[string]:
"""
return [
arg
for arg in cmake_args
if arg.startswith("-D") and not arg.startswith("-DCMAKE_BUILD_TYPE=")
]
def patch_setting_set(settings_set, cmake_args):
"""
Given a <valuelist/>, sets the flags from the provided CMake arguments
:type settings_set: ElementTree.Element
:type cmake_args: list[string]
"""
# Parse the XML settings
settings = dict(
node.text.split(":", 1)
for node in settings_set
)
# Update the settings dict with cmake_args
for arg in cmake_args:
name, value = arg[2:].split("=", 1)
type = "BOOL" if value in {"ON", "OFF"} else "STRING"
settings[name] = type + "=" + value
# Update the XML element with the new settings
for child in settings_set:
settings_set.remove(child)
for name, value in settings.items():
element = ElementTree.Element("value", type="QString")
element.text = name + ":" + value
settings_set.append(element)
def patch_qtcreator_project(project_file, cmake_args):
"""
:type project_file: string
:type cmake_args: list[string]
"""
project = ElementTree.parse(project_file)
settings_sets = project.findall(".//valuelist[@key='CMake.Configuration']")
for settings_set in settings_sets:
patch_setting_set(settings_set, cmake_args)
project.write(project_file)
def main():
parser = ArgumentParser(description=
"Patches a QtCreator project file (CMakeLists.txt.user) so that it includes a given set of CMake flags")
parser.add_argument("project", type=str)
args, cmake_args = parser.parse_known_args()
patch_qtcreator_project(args.project, clean_cmake_args(cmake_args))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment