Merge pull request #399 from JPilson/feature/key_naming_convention

Feature/Automated Key Naming Convention Suggestion for Localize-It Action
This commit is contained in:
Marcel 2024-05-31 20:28:31 +02:00 committed by GitHub
commit 5428ae3d46
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
16 changed files with 307 additions and 39 deletions

View File

@ -10,6 +10,7 @@ import com.intellij.openapi.project.Project;
import de.marhali.easyi18n.dialog.AddDialog;
import de.marhali.easyi18n.model.KeyPath;
import de.marhali.easyi18n.settings.presets.NamingConvention;
import de.marhali.easyi18n.settings.ProjectSettingsService;
import de.marhali.easyi18n.util.DocumentUtil;
@ -47,7 +48,7 @@ class LocalizeItAction extends AnAction {
throw new RuntimeException("Project is null!");
}
AddDialog dialog = new AddDialog(project, new KeyPath(text), text, (key) -> replaceSelectedText(project, editor, key));
AddDialog dialog = new AddDialog(project, new KeyPath(convertKeyToNamingCase(text, project)), text, (key) -> replaceSelectedText(project, editor, key));
dialog.showAndHandle();
}
@ -77,7 +78,18 @@ class LocalizeItAction extends AnAction {
*/
private String buildReplacement(String flavorTemplate, String key, DocumentUtil documentUtil) {
if (documentUtil.isVue() || documentUtil.isJsOrTs()) return flavorTemplate + "('" + key + "')";
return flavorTemplate + "(\"" + key + "\")";
}
/**
* Converts a given key to the specified naming convention.
*
* @param key the key to convert
* @param project the project where the key is being converted
* @return the converted key
*/
private String convertKeyToNamingCase(String key, Project project) {
return NamingConvention.convertKeyToConvention(key, ProjectSettingsService.get(project).getState().getCaseFormat());
}
}

View File

@ -3,35 +3,61 @@ package de.marhali.easyi18n.settings;
import de.marhali.easyi18n.io.parser.ParserStrategyType;
import de.marhali.easyi18n.io.folder.FolderStrategyType;
import de.marhali.easyi18n.settings.presets.NamingConvention;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* API to access the project-specific configuration for this plugin.
*
* @author marhaliu
*/
public interface ProjectSettings {
// Resource Configuration
@Nullable String getLocalesDirectory();
@NotNull FolderStrategyType getFolderStrategy();
@NotNull ParserStrategyType getParserStrategy();
@NotNull String getFilePattern();
@Nullable
String getLocalesDirectory();
@NotNull
FolderStrategyType getFolderStrategy();
@NotNull
ParserStrategyType getParserStrategy();
@NotNull
String getFilePattern();
boolean isIncludeSubDirs();
boolean isSorting();
// Editor Configuration
@Nullable String getNamespaceDelimiter();
@NotNull String getSectionDelimiter();
@Nullable String getContextDelimiter();
@Nullable String getPluralDelimiter();
@Nullable String getDefaultNamespace();
@NotNull String getPreviewLocale();
@Nullable
String getNamespaceDelimiter();
@NotNull
String getSectionDelimiter();
@Nullable
String getContextDelimiter();
@Nullable
String getPluralDelimiter();
@Nullable
String getDefaultNamespace();
@NotNull
String getPreviewLocale();
boolean isNestedKeys();
boolean isAssistance();
// Experimental Configuration
boolean isAlwaysFold();
String getFlavorTemplate();
@NotNull
NamingConvention getCaseFormat();
}

View File

@ -13,6 +13,7 @@ import com.intellij.util.ui.FormBuilder;
import de.marhali.easyi18n.io.parser.ArrayMapper;
import de.marhali.easyi18n.io.parser.ParserStrategyType;
import de.marhali.easyi18n.settings.presets.NamingConvention;
import de.marhali.easyi18n.settings.presets.Preset;
import javax.swing.*;
@ -26,6 +27,7 @@ import java.util.ResourceBundle;
/**
* Configuration panel with all possible options for this plugin.
*
* @author marhali
*/
public class ProjectSettingsComponent extends ProjectSettingsComponentState {
@ -64,7 +66,9 @@ public class ProjectSettingsComponent extends ProjectSettingsComponentState {
.addVerticalGap(24)
.addComponent(new TitledSeparator(bundle.getString("settings.experimental.title")))
.addComponent(constructAlwaysFoldField())
.addVerticalGap(12)
.addLabeledComponent(bundle.getString("settings.experimental.flavor-template"), constructFlavorTemplate(), 1, false)
.addLabeledComponent(bundle.getString("settings.experimental.key-naming-format.title"), constructKeyCaseFormater(), 1, false)
.addComponentFillVertically(new JPanel(), 0)
.getPanel();
}
@ -226,6 +230,14 @@ public class ProjectSettingsComponent extends ProjectSettingsComponentState {
return flavorTemplate;
}
private JComponent constructKeyCaseFormater() {
KeyCaseFormater = new ComboBox<>(NamingConvention.getEnumNames());
KeyCaseFormater.setToolTipText(bundle.getString("settings.experimental.key-naming-format.tooltip"));
KeyCaseFormater.setMinimumAndPreferredWidth(200);
return KeyCaseFormater;
}
private ItemListener handleParserChange() {
return e -> {
if (e.getStateChange() == ItemEvent.SELECTED) {

View File

@ -5,12 +5,14 @@ import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import de.marhali.easyi18n.io.parser.ParserStrategyType;
import de.marhali.easyi18n.io.folder.FolderStrategyType;
import de.marhali.easyi18n.settings.presets.NamingConvention;
import de.marhali.easyi18n.settings.presets.Preset;
import javax.swing.*;
/**
* Mandatory for state management for the project settings component.
*
* @author marhali
*/
public class ProjectSettingsComponentState {
@ -41,6 +43,7 @@ public class ProjectSettingsComponentState {
protected JCheckBox alwaysFold;
protected JTextField flavorTemplate;
protected ComboBox<String> KeyCaseFormater;
protected ProjectSettingsState getState() {
// Every field needs to provide its state
@ -65,8 +68,11 @@ public class ProjectSettingsComponentState {
state.setAssistance(assistance.isSelected());
state.setAlwaysFold(alwaysFold.isSelected());
state.setFlavorTemplate(flavorTemplate.getText());
state.setCaseFormat(NamingConvention.fromString(KeyCaseFormater.getSelectedItem().toString()));
return state;
}
@ -92,5 +98,7 @@ public class ProjectSettingsComponentState {
alwaysFold.setSelected(state.isAlwaysFold());
flavorTemplate.setText(state.getFlavorTemplate());
KeyCaseFormater.setSelectedItem(state.getCaseFormat().getName());
}
}

View File

@ -6,6 +6,7 @@ import de.marhali.easyi18n.io.parser.ParserStrategyType;
import de.marhali.easyi18n.io.folder.FolderStrategyType;
import de.marhali.easyi18n.settings.presets.DefaultPreset;
import de.marhali.easyi18n.settings.presets.NamingConvention;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@ -13,32 +14,48 @@ import java.util.Objects;
/**
* Represents the project-specific configuration of this plugin.
*
* @author marhali
*/
public class ProjectSettingsState implements ProjectSettings {
// Resource Configuration
@Property private String localesDirectory;
@Property private FolderStrategyType folderStrategy;
@Property private ParserStrategyType parserStrategy;
@Property private String filePattern;
@Property
private String localesDirectory;
@Property
private FolderStrategyType folderStrategy;
@Property
private ParserStrategyType parserStrategy;
@Property
private String filePattern;
@Property private Boolean includeSubDirs;
@Property private boolean sorting;
@Property
private Boolean includeSubDirs;
@Property
private boolean sorting;
// Editor configuration
@Property private String namespaceDelimiter;
@Property private String sectionDelimiter;
@Property private String contextDelimiter;
@Property private String pluralDelimiter;
@Property private String defaultNamespace;
@Property private String previewLocale;
@Property
private String namespaceDelimiter;
@Property
private String sectionDelimiter;
@Property
private String contextDelimiter;
@Property
private String pluralDelimiter;
@Property
private String defaultNamespace;
@Property
private String previewLocale;
@Property private Boolean nestedKeys;
@Property private Boolean assistance;
@Property
private Boolean nestedKeys;
@Property
private Boolean assistance;
// Experimental configuration
@Property private Boolean alwaysFold;
@Property
private Boolean alwaysFold;
/**
* The `flavorTemplate` specifies the format used for replacing strings with their i18n (internationalization) counterparts.
@ -47,7 +64,11 @@ public class ProjectSettingsState implements ProjectSettings {
* the specific framework or developers' preferences for handling i18n. The ability to dynamically change this template adds flexibility and customization
* to cater to different i18n handling methods.
*/
@Property private String flavorTemplate;
@Property
private String flavorTemplate;
@Property
private NamingConvention caseFormat;
public ProjectSettingsState() {
this(new DefaultPreset());
@ -75,6 +96,7 @@ public class ProjectSettingsState implements ProjectSettings {
this.alwaysFold = defaults.isAlwaysFold();
this.flavorTemplate = defaults.getFlavorTemplate();
this.caseFormat = defaults.getCaseFormat();
}
@Override
@ -158,6 +180,11 @@ public class ProjectSettingsState implements ProjectSettings {
return this.flavorTemplate;
}
@Override
public @NotNull NamingConvention getCaseFormat() {
return this.caseFormat;
}
public void setLocalesDirectory(String localesDirectory) {
this.localesDirectory = localesDirectory;
}
@ -218,10 +245,15 @@ public class ProjectSettingsState implements ProjectSettings {
this.alwaysFold = alwaysFold;
}
public void setFlavorTemplate(String flavorTemplate){
public void setFlavorTemplate(String flavorTemplate) {
this.flavorTemplate = flavorTemplate;
}
public void setCaseFormat(NamingConvention caseFormat) {
this.caseFormat = caseFormat;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
@ -242,7 +274,8 @@ public class ProjectSettingsState implements ProjectSettings {
&& Objects.equals(nestedKeys, that.nestedKeys)
&& Objects.equals(assistance, that.assistance)
&& Objects.equals(alwaysFold, that.alwaysFold)
&& Objects.equals(flavorTemplate,that.flavorTemplate);
&& Objects.equals(flavorTemplate, that.flavorTemplate)
&& Objects.equals(caseFormat, that.caseFormat);
}
@Override
@ -250,7 +283,7 @@ public class ProjectSettingsState implements ProjectSettings {
return Objects.hash(
localesDirectory, folderStrategy, parserStrategy, filePattern, includeSubDirs,
sorting, namespaceDelimiter, sectionDelimiter, contextDelimiter, pluralDelimiter,
defaultNamespace, previewLocale, nestedKeys, assistance, alwaysFold,flavorTemplate
defaultNamespace, previewLocale, nestedKeys, assistance, alwaysFold, flavorTemplate, caseFormat
);
}
@ -273,6 +306,7 @@ public class ProjectSettingsState implements ProjectSettings {
", assistance=" + assistance +
", alwaysFold=" + alwaysFold +
", flavorTemplate=" + flavorTemplate +
", caseFormat=" + caseFormat.toString() +
'}';
}
}

View File

@ -91,4 +91,9 @@ public class DefaultPreset implements ProjectSettings {
public String getFlavorTemplate() {
return "$i18n.t";
}
@Override
public @NotNull NamingConvention getCaseFormat() {
return NamingConvention.CAMEL_CASE;
}
}

View File

@ -0,0 +1,92 @@
package de.marhali.easyi18n.settings.presets;
import com.google.common.base.CaseFormat;
import java.util.Arrays;
/**
* Enum representing different naming conventions.
* Provides utility methods to convert keys to the specified convention.
*/
public enum NamingConvention {
CAMEL_CASE("Camel Case"),
PASCAL_CASE("Pascal Case"),
SNAKE_CASE("Snake Case"),
SNAKE_CASE_UPPERCASE("Snake Case (Uppercase)");
private final String name;
private NamingConvention(String name) {
this.name = name;
}
/**
* Retrieves the name of the current instance of the class.
*
* @return the name of the current instance
*/
public String getName() {
return this.name;
}
@Override
public String toString() {
return super.name().toLowerCase();
}
/**
* Converts a string representation of a naming convention to the corresponding NamingConvention enum value.
*
* @param name the string representation of the naming convention
* @return the corresponding NamingConvention enum value
*/
static public NamingConvention fromString(String name) {
for (NamingConvention value : NamingConvention.values()) {
if (value.getName().equals(name))
return value;
}
return NamingConvention.CAMEL_CASE;
}
/**
* Returns an array of strings representing the names of the enum values in the {@link NamingConvention} enum.
*
* @return an array of strings representing the enum names
*/
static public String[] getEnumNames() {
return Arrays.stream(NamingConvention.values())
.map(NamingConvention::getName)
.toArray(String[]::new);
}
/**
* Converts a given key to the specified naming convention.
*
* @param key the key to convert
* @param convention the naming convention to convert the key to
* @return the converted key
*/
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 PASCAL_CASE:
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);
}
}

View File

@ -91,4 +91,8 @@ public class ReactI18NextPreset implements ProjectSettings {
public String getFlavorTemplate() {
return "$i18n.t";
}
@Override
public @NotNull NamingConvention getCaseFormat() {
return NamingConvention.CAMEL_CASE;
}
}

View File

@ -90,4 +90,9 @@ public class VueI18nPreset implements ProjectSettings {
public String getFlavorTemplate() {
return "$i18n.t";
}
@Override
public @NotNull NamingConvention getCaseFormat() {
return NamingConvention.CAMEL_CASE;
}
}

View File

@ -62,6 +62,9 @@ settings.experimental.always-fold.title=Always fold translation keys
settings.experimental.always-fold.tooltip=Forces the editor to always display the value behind a translation key. The value cannot be unfolded when this function is active.
settings.experimental.flavor-template =I18n flavor template
settings.experimental.flavor-template-tooltip = Specify how to replace strings with i18n representation.
settings.experimental.key-naming-format.title=Key format of extracted translation
settings.experimental.key-naming-format.tooltip=Choose Naming Convention for the keys of extracted translation
error.io=An error occurred while processing translation files. \n\
Config: {0} => {1} ({2}) \n\
Path: {3} \n\

View File

@ -3,6 +3,7 @@ package de.marhali.easyi18n;
import de.marhali.easyi18n.io.parser.ParserStrategyType;
import de.marhali.easyi18n.io.folder.FolderStrategyType;
import de.marhali.easyi18n.model.KeyPath;
import de.marhali.easyi18n.settings.presets.NamingConvention;
import de.marhali.easyi18n.settings.ProjectSettings;
import de.marhali.easyi18n.util.KeyPathConverter;
@ -172,6 +173,11 @@ public class KeyPathConverterTest {
public boolean isIncludeSubDirs() {
return false;
}
@Override
public @NotNull NamingConvention getCaseFormat() {
return NamingConvention.CAMEL_CASE;
}
});
}
}

View File

@ -22,6 +22,7 @@ import java.util.Objects;
/**
* End-to-end test case.
*
* @author marhali
*/
public abstract class EndToEndTestCase extends BasePlatformTestCase {
@ -57,7 +58,8 @@ public abstract class EndToEndTestCase extends BasePlatformTestCase {
out.setLocalesDirectory(tempPath.toString());
ProjectSettingsService.get(getProject()).setState(out);
InstanceManager.get(getProject()).store().saveToPersistenceLayer(success -> {});
InstanceManager.get(getProject()).store().saveToPersistenceLayer(success -> {
});
// Compare file structure and contents
IOFileFilter fileFilter = TrueFileFilter.INSTANCE;
@ -73,7 +75,7 @@ public abstract class EndToEndTestCase extends BasePlatformTestCase {
assertEquals(originalFiles.length, outputFiles.length);
for(int i = 0; i < originalFiles.length; i++) {
for (int i = 0; i < originalFiles.length; i++) {
File originalFile = originalFiles[i];
File outputFile = outputFiles[i];

View File

@ -7,6 +7,7 @@ import de.marhali.easyi18n.io.parser.properties.PropertiesMapper;
import de.marhali.easyi18n.io.parser.properties.SortableProperties;
import de.marhali.easyi18n.model.TranslationData;
import de.marhali.easyi18n.model.KeyPath;
import de.marhali.easyi18n.settings.presets.NamingConvention;
import de.marhali.easyi18n.settings.ProjectSettings;
import de.marhali.easyi18n.util.KeyPathConverter;
@ -19,6 +20,7 @@ import java.util.*;
/**
* Unit tests for {@link PropertiesMapper}.
*
* @author marhali
*/
public class PropertiesMapperTest extends AbstractMapperTest {
@ -245,6 +247,11 @@ public class PropertiesMapperTest extends AbstractMapperTest {
public boolean isIncludeSubDirs() {
return false;
}
@Override
public @NotNull NamingConvention getCaseFormat() {
return NamingConvention.CAMEL_CASE;
}
});
}
}

View File

@ -0,0 +1,35 @@
package de.marhali.easyi18n.settings;
import com.intellij.testFramework.fixtures.BasePlatformTestCase;
import de.marhali.easyi18n.settings.presets.NamingConvention;
import java.io.IOException;
public class NamingConventionTest extends BasePlatformTestCase {
@Override
protected void setUp() throws Exception {
super.setUp();
}
public void testConvertToNamingConvention() throws IOException {
assertEquals("helloWorld", NamingConvention.convertKeyToConvention("Hello World", NamingConvention.CAMEL_CASE));
assertEquals("hello_world", NamingConvention.convertKeyToConvention("Hello World", NamingConvention.SNAKE_CASE));
assertEquals("HelloWorld", NamingConvention.convertKeyToConvention("Hello World", NamingConvention.PASCAL_CASE));
assertEquals("HELLO_WORLD", NamingConvention.convertKeyToConvention("Hello World", NamingConvention.SNAKE_CASE_UPPERCASE));
}
public void testGetEnumNames() throws Exception {
String[] expected = {"Camel Case", "Pascal Case", "Snake Case", "Snake Case (Uppercase)"};
String[] actual = NamingConvention.getEnumNames();
assertEquals(expected.length, actual.length);
}
public void testFromString() {
assertEquals(NamingConvention.CAMEL_CASE, NamingConvention.fromString("Camel Case"));
assertEquals(NamingConvention.PASCAL_CASE, NamingConvention.fromString("Pascal Case"));
assertEquals(NamingConvention.SNAKE_CASE, NamingConvention.fromString("Snake Case"));
assertEquals(NamingConvention.SNAKE_CASE_UPPERCASE, NamingConvention.fromString("Snake Case (Uppercase)"));
assertEquals(NamingConvention.CAMEL_CASE, NamingConvention.fromString("Invalid Input"));
}
}

View File

@ -4,9 +4,11 @@ import com.intellij.testFramework.fixtures.BasePlatformTestCase;
import com.intellij.util.xmlb.XmlSerializerUtil;
import de.marhali.easyi18n.settings.presets.DefaultPreset;
import de.marhali.easyi18n.settings.presets.NamingConvention;
/**
* Tests for the project settings service itself.
*
* @author marhali
*/
public class ProjectSettingsServiceTest extends BasePlatformTestCase {
@ -35,4 +37,12 @@ public class ProjectSettingsServiceTest extends BasePlatformTestCase {
ProjectSettingsState after = XmlSerializerUtil.createCopy(previous);
assertEquals("mySinglePropTest", after.getLocalesDirectory());
}
public void testPersistenceFormatCase() {
ProjectSettingsState previous = new ProjectSettingsState();
assertEquals(previous.getCaseFormat(), NamingConvention.CAMEL_CASE);
previous.setCaseFormat(NamingConvention.SNAKE_CASE);
ProjectSettingsState after = XmlSerializerUtil.createCopy(previous);
assertEquals(after.getCaseFormat(), NamingConvention.SNAKE_CASE);
}
}

View File

@ -3,11 +3,13 @@ package de.marhali.easyi18n.settings;
import de.marhali.easyi18n.io.folder.FolderStrategyType;
import de.marhali.easyi18n.io.parser.ParserStrategyType;
import de.marhali.easyi18n.settings.presets.NamingConvention;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Settings preset to test the functionality of the settings service.
*
* @author marhali
*/
public class SettingsTestPreset implements ProjectSettings {
@ -88,6 +90,11 @@ public class SettingsTestPreset implements ProjectSettings {
@Override
public String getFlavorTemplate() {
return "";
return "t";
}
@Override
public @NotNull NamingConvention getCaseFormat() {
return NamingConvention.CAMEL_CASE;
}
}