refactor: streamline key naming convention conversion

Moved key naming convention conversion logic into NamingConvention enum. This simplifies the code in LocalizeItAction and makes the conversion function easily reusable. Also added support for uppercase snake and camel cases.
This commit is contained in:
JPilson 2024-04-20 19:28:16 +02:00
parent 027016921f
commit 4c737e25fa
2 changed files with 28 additions and 19 deletions

View File

@ -83,21 +83,8 @@ class LocalizeItAction extends AnAction {
return flavorTemplate + "(\"" + key + "\")";
}
private String convertKeyToNamingCase(String key,Project project) {
String newKey = key.toLowerCase();
newKey = newKey.replaceAll("\\s+", "_");
NamingConvention namingConvention = ProjectSettingsService.get(project).getState().getCaseFormat();
return (namingConvention == NamingConvention.CAMEL_CASE) ? convertKeyToCamelCase(newKey) : convertKeyToSnakeCase(newKey);
private String convertKeyToNamingCase(String key, Project project) {
return NamingConvention.convertKeyToConvention(key, ProjectSettingsService.get(project).getState().getCaseFormat());
}
private String convertKeyToCamelCase(String key) {
return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, key);
}
private String convertKeyToSnakeCase(String key) {
return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_UNDERSCORE, key);
}
}

View File

@ -5,12 +5,10 @@ import com.google.common.base.CaseFormat;
import java.util.Arrays;
public enum NamingConvention {
SNAKE_CASE("Snake Case"),
CAMEL_CASE("Camel Case"),
CAMEL_CASE_UPPERCASE("Camel Case Uppercase"),
;
SNAKE_CASE("Snake Case"),
SNAKE_CASE_UPPERCASE("Snake Case Uppercase");
private final String name;
@ -37,4 +35,28 @@ public enum NamingConvention {
.map(NamingConvention::getName)
.toArray(String[]::new);
}
static public String convertKeyToConvention(String key, NamingConvention convention) {
String newKey = key.toLowerCase();
newKey = newKey.replaceAll("\\s+", "_");
return switch (convention) {
case SNAKE_CASE:
yield formatToSnakeCase(newKey, false);
case SNAKE_CASE_UPPERCASE:
yield formatToSnakeCase(newKey, true);
case CAMEL_CASE:
yield formatToCamelCase(newKey, false);
case CAMEL_CASE_UPPERCASE:
yield formatToCamelCase(newKey, true);
};
}
static private String formatToCamelCase(String key, boolean capitalized) {
return CaseFormat.LOWER_UNDERSCORE.to(capitalized ? CaseFormat.UPPER_CAMEL : CaseFormat.LOWER_CAMEL, key);
}
static private String formatToSnakeCase(String key, boolean capitalized) {
return CaseFormat.LOWER_UNDERSCORE.to(capitalized ? CaseFormat.UPPER_UNDERSCORE : CaseFormat.LOWER_UNDERSCORE, key);
}
}