From 3a3bf41eef26b58cfda1ff8031dfd9d21ad19636 Mon Sep 17 00:00:00 2001 From: Cristian Adam Date: Thu, 3 Aug 2023 19:29:37 +0200 Subject: [PATCH] CMakePM: Add support for cmake-format config files Fixes: QTCREATORBUG-28969 Change-Id: I0bb31993e4d2ffd8affcc67dee5fd70654e2c1d3 Reviewed-by: Eike Ziller --- .../cmakeprojectmanager/cmakeformatter.cpp | 50 ++++++++++++++++++- 1 file changed, 48 insertions(+), 2 deletions(-) diff --git a/src/plugins/cmakeprojectmanager/cmakeformatter.cpp b/src/plugins/cmakeprojectmanager/cmakeformatter.cpp index 9128adccad1..38e9f0cb32c 100644 --- a/src/plugins/cmakeprojectmanager/cmakeformatter.cpp +++ b/src/plugins/cmakeprojectmanager/cmakeformatter.cpp @@ -97,7 +97,11 @@ public: Core::Command *cmd = ActionManager::registerAction(&formatFile, Constants::CMAKEFORMATTER_ACTION_ID); connect(&formatFile, &QAction::triggered, this, [this] { - TextEditor::formatCurrentFile(formatCommand()); + auto command = formatCommand(); + if (auto editor = EditorManager::currentEditor()) + extendCommandWithConfigs(command, editor->document()->filePath()); + + TextEditor::formatCurrentFile(command); }); ActionManager::actionContainer(Constants::CMAKEFORMATTER_MENU_ID)->addAction(cmd); @@ -142,6 +146,46 @@ public: return cmd; } + static FilePaths formatConfigFiles(const FilePath &dir) + { + if (dir.isEmpty()) + return FilePaths(); + + return filtered(transform({".cmake-format", + ".cmake-format.py", + ".cmake-format.json", + ".cmake-format.yaml", + "cmake-format.py", + "cmake-format.json", + "cmake-format.yaml"}, + [dir](const QString &fileName) { + return dir.pathAppended(fileName); + }), + &FilePath::exists); + } + + static FilePaths findConfigs(const FilePath &fileName) + { + FilePath parentDirectory = fileName.parentDir(); + while (parentDirectory.exists()) { + FilePaths configFiles = formatConfigFiles(parentDirectory); + if (!configFiles.isEmpty()) + return configFiles; + + parentDirectory = parentDirectory.parentDir(); + } + return FilePaths(); + } + + static void extendCommandWithConfigs(TextEditor::Command &command, const FilePath &source) + { + const FilePaths configFiles = findConfigs(source); + if (!configFiles.isEmpty()) { + command.addOption("--config-files"); + command.addOptions(Utils::transform(configFiles, &FilePath::nativePath)); + } + } + FilePathAspect command{this}; bool haveValidFormatCommand{false}; BoolAspect autoFormatOnSave{this}; @@ -199,8 +243,10 @@ void CMakeFormatterSettings::applyIfNecessary(IDocument *document) const IEditor *currentEditor = EditorManager::currentEditor(); IEditor *editor = editors.contains(currentEditor) ? currentEditor : editors.first(); - if (auto widget = TextEditorWidget::fromEditor(editor)) + if (auto widget = TextEditorWidget::fromEditor(editor)) { + extendCommandWithConfigs(command, editor->document()->filePath()); TextEditor::formatEditor(widget, command); + } } CMakeFormatterSettings &formatterSettings()