From a86378608fd6ffd5c04986ce1956aa25847a4543 Mon Sep 17 00:00:00 2001 From: paul-dingemans Date: Tue, 2 Aug 2022 12:45:06 +0200 Subject: [PATCH] Prevent class cast exception when retrieving ktlint_code_style property from ".editorconfig" Closes #1559 --- .../core/api/UsesEditorConfigProperties.kt | 24 +++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/api/UsesEditorConfigProperties.kt b/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/api/UsesEditorConfigProperties.kt index 2b87ef4053..8440757d73 100644 --- a/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/api/UsesEditorConfigProperties.kt +++ b/ktlint-core/src/main/kotlin/com/pinterest/ktlint/core/api/UsesEditorConfigProperties.kt @@ -47,10 +47,24 @@ public interface UsesEditorConfigProperties { require(editorConfigProperties.contains(editorConfigProperty)) { "EditorConfigProperty '${editorConfigProperty.type.name}' may only be retrieved when it is registered in the editorConfigProperties." } - val codeStyle = getEditorConfigValue(codeStyleSetProperty, official) - return getEditorConfigValue(editorConfigProperty, codeStyle) + + return getEditorConfigValue(editorConfigProperty, getEditorConfigCodeStyle()) } + /** + * The code style property does not need to be defined in the [editorConfigProperties] of the class that defines + * this interface. Those classed should not need to be aware of the different coding styles except when setting + * different default values. As the property is not defined in the [editorConfigProperties] the value needs to + * be parsed explicitly to prevent class cast exceptions. + */ + private fun EditorConfigProperties.getEditorConfigCodeStyle() = + codeStyleSetProperty + .type + .parse( + get(codeStyleSetProperty.type.name)?.sourceValue + ).parsed + ?: official + /** * Get the value of [EditorConfigProperty] based on loaded [EditorConfigProperties] content for the current * [ASTNode]. @@ -61,8 +75,10 @@ public interface UsesEditorConfigProperties { "EditorConfigProperty '${editorConfigProperty.type.name}' may only be retrieved when it is registered in the editorConfigProperties." } val editorConfigPropertyValues = getUserData(KtLint.EDITOR_CONFIG_PROPERTIES_USER_DATA_KEY)!! - val codeStyle = editorConfigPropertyValues.getEditorConfigValue(codeStyleSetProperty, official) - return editorConfigPropertyValues.getEditorConfigValue(editorConfigProperty, codeStyle) + return editorConfigPropertyValues.getEditorConfigValue( + editorConfigProperty, + editorConfigPropertyValues.getEditorConfigCodeStyle() + ) } private fun EditorConfigProperties.getEditorConfigValue(