Yaml -> Props conversion

This commit is contained in:
aboyko
2024-03-20 16:31:44 -04:00
parent 8bf29f4b91
commit 3a0ee635f2
8 changed files with 690 additions and 18 deletions

View File

@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-17"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry kind="src" path="src"/>
<classpathentry kind="output" path="target/classes"/>

View File

@@ -1,13 +1,15 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.codegen.targetPlatform=17
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.compliance=17
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.release=disabled
org.eclipse.jdt.core.compiler.source=1.8
org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning
org.eclipse.jdt.core.compiler.release=enabled
org.eclipse.jdt.core.compiler.source=17

View File

@@ -10,6 +10,12 @@
id="org.springframework.ide.eclipse.boot.properties.editor.convertPropertiesToYaml"
name="Convert .properties to .yaml">
</command>
<command
categoryId="org.springframework.ide.eclipse.boot.commands.category"
defaultHandler="org.springframework.ide.eclipse.boot.refactoring.ConvertYamlToPropertiesHandler"
id="org.springframework.ide.eclipse.boot.properties.editor.convertYamlToProperties"
name="Convert .yaml to .properties">
</command>
</extension>
<extension
point="org.eclipse.ui.menus">
@@ -24,22 +30,63 @@
<count
value="1">
</count>
<or>
<with variable="activeEditorId">
<equals value="SpringBootPropertyEditor"/>
</with>
<with variable="activeMenuSelection">
<with
variable="activeMenuSelection">
<iterate
ifEmpty="false">
<adapt type="org.eclipse.core.resources.IResource">
<test property="org.eclipse.core.resources.extension" value="properties" />
ifEmpty="false">
<adapt
type="org.eclipse.core.resources.IResource">
<and>
<test
property="org.springsource.ide.eclipse.boot.isBootResource">
</test>
<test
property="org.eclipse.core.resources.extension"
value="properties">
</test>
</and>
</adapt>
</iterate>
</with>
</or>
</with>
</and>
</visibleWhen>
</command>
<command
commandId="org.springframework.ide.eclipse.boot.properties.editor.convertYamlToProperties"
icon="icons/boot-icon.png">
<visibleWhen
checkEnabled="false">
<and>
<count
value="1">
</count>
<with
variable="activeMenuSelection">
<iterate
ifEmpty="false">
<adapt
type="org.eclipse.core.resources.IResource">
<and>
<test
property="org.springsource.ide.eclipse.boot.isBootResource">
</test>
<or>
<test
property="org.eclipse.core.resources.extension"
value="yml">
</test>
<test
property="org.eclipse.core.resources.extension"
value="yaml">
</test>
</or>
</and>
</adapt>
</iterate>
</with>
</and>
</visibleWhen>
</command>
</menuContribution>
</extension>

View File

@@ -0,0 +1,93 @@
/*******************************************************************************
* Copyright (c) 2024 Broadcom, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Broadcom, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.eclipse.boot.refactoring;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.filebuffers.FileBuffers;
import org.eclipse.core.filebuffers.ITextFileBuffer;
import org.eclipse.core.filebuffers.LocationKind;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation;
import org.eclipse.ui.handlers.HandlerUtil;
import org.springsource.ide.eclipse.commons.livexp.util.Log;
public class ConvertYamlToPropertiesHandler extends AbstractHandler {
private static ITextFileBuffer getDirtyFileBuffer(IFile file) {
ITextFileBuffer buffer = FileBuffers.getTextFileBufferManager().getTextFileBuffer(file.getFullPath(), LocationKind.IFILE);
if (buffer!=null && buffer.isDirty()) {
return buffer;
}
return null;
}
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
IFile file = getTarget(event);
try {
if (file!=null) {
ITextFileBuffer dirtyBuffer = getDirtyFileBuffer(file);
if (dirtyBuffer!=null) {
dirtyBuffer.commit(null, true);
}
ConvertYamlToPropertiesRefactoring refactoring = new ConvertYamlToPropertiesRefactoring(file);
RefactoringWizard wizard = new RefactoringWizard(refactoring,
RefactoringWizard.DIALOG_BASED_USER_INTERFACE |
RefactoringWizard.CHECK_INITIAL_CONDITIONS_ON_OPEN |
RefactoringWizard.NO_BACK_BUTTON_ON_STATUS_DIALOG
) {
@Override
protected void addUserInputPages() {
//no inputs required
}
};
new RefactoringWizardOpenOperation(wizard).run(HandlerUtil.getActiveShell(event), "Convert '"+file.getName()+"' to .properties");
}
} catch (Exception e) {
Log.log(e);
}
return null;
}
private IFile getTarget(ExecutionEvent event) {
ISelection selection = HandlerUtil.getActiveMenuSelection(event);
IStructuredSelection ss = null;
if (selection instanceof IStructuredSelection) {
ss = (IStructuredSelection) selection;
} else {
selection = HandlerUtil.getActiveMenuEditorInput(event);
if (selection instanceof IStructuredSelection) {
ss = (IStructuredSelection) selection;
}
}
if (ss!=null && !ss.isEmpty()) {
return asFile(ss.getFirstElement());
}
return null;
}
private IFile asFile(Object selectedElement) {
if (selectedElement instanceof IFile) {
return (IFile) selectedElement;
}
if (selectedElement instanceof IAdaptable) {
return ((IAdaptable) selectedElement).getAdapter(IFile.class);
}
return null;
}
}

View File

@@ -0,0 +1,162 @@
/*******************************************************************************
* Copyright (c) 2024 Broadcom, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Broadcom, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.eclipse.boot.refactoring;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.Map;
import java.util.Properties;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.ltk.core.refactoring.Change;
import org.eclipse.ltk.core.refactoring.CompositeChange;
import org.eclipse.ltk.core.refactoring.Refactoring;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.ltk.core.refactoring.TextFileChange;
import org.eclipse.ltk.core.refactoring.resource.RenameResourceChange;
import org.eclipse.text.edits.ReplaceEdit;
import org.springsource.ide.eclipse.commons.livexp.util.ExceptionUtil;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.events.CommentEvent;
import org.yaml.snakeyaml.events.Event;
import org.yaml.snakeyaml.events.StreamEndEvent;
public class ConvertYamlToPropertiesRefactoring extends Refactoring {
private static final String YAML_EXT = ".yml";
private static final String PROPERTIES_EXT = ".properties";
private IFile propsFile;
private final IFile yamlFile;
private String propsContent;
private int inputTextLen;
public ConvertYamlToPropertiesRefactoring(IFile yamlFile) {
this.yamlFile = yamlFile;
}
@Override
public String getName() {
return "Convert .yaml to .properties";
}
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm)
throws CoreException, OperationCanceledException {
if (!yamlFile.isAccessible()) {
return RefactoringStatus.createFatalErrorStatus("The resource '"+yamlFile.getFullPath()+"' is not accessible");
}
this.propsFile = propsFileFor(yamlFile);
if (propsFile.exists()) {
return RefactoringStatus.createFatalErrorStatus("File '"+propsFile.getFullPath()+"' already exists!");
}
return new RefactoringStatus();
}
private static IFile propsFileFor(IFile yamlFile) {
IContainer container = yamlFile.getParent();
String name = yamlFile.getName();
if (name.endsWith(YAML_EXT)) {
name = name.substring(0, name.length()-YAML_EXT.length())+PROPERTIES_EXT;
} else {
name = name + PROPERTIES_EXT;
}
return container.getFile(Path.EMPTY.append(name));
}
@Override
public RefactoringStatus checkFinalConditions(IProgressMonitor pm)
throws CoreException, OperationCanceledException {
RefactoringStatus status = new RefactoringStatus();
try {
if (hasComments(yamlFile)) {
status.merge(RefactoringStatus.createWarningStatus("The yaml file has comments, which will be lost in the refactoring!"));
}
} catch (Exception e) {
status.merge(RefactoringStatus.create(ExceptionUtil.status(e, "Problems reading file: "+yamlFile.getFullPath())));
return status;
}
Map<String, ?> o = null;
try (InputStream content = yamlFile.getContents()) {
o = new Yaml().load(content);
} catch (Exception e) {
status.merge(RefactoringStatus.create(ExceptionUtil.status(e, "Problems parsing as a .yaml file: "+yamlFile.getFullPath())));
}
if (o != null) {
try {
YamlToPropertiesConverter converter = new YamlToPropertiesConverter(o);
Properties props = converter.getProperties();
StringWriter write = new StringWriter();
props.store(write, null);
write.flush();
write.close();
// Skip over the date header. Comments are not present but date header is.
if (write.getBuffer().charAt(0) == '#') {
int idx = write.getBuffer().indexOf("\n");
this.propsContent = idx >= 0 && idx < write.getBuffer().length() ? write.getBuffer().substring(idx + 1) : write.getBuffer().toString();
} else {
this.propsContent = write.getBuffer().toString();
}
status.merge(converter.getStatus());
} catch (IOException e) {
status.merge(RefactoringStatus.create(ExceptionUtil.status(e, "Problems writing to .properties file: "+propsFile.getFullPath())));
}
} else {
propsContent = "";
}
return status;
}
private boolean hasComments(IFile yamlFile) throws Exception {
InputStream is = null;
try {
is = yamlFile.getContents();
LoaderOptions loaderOptions = new LoaderOptions();
loaderOptions.setProcessComments(true);
boolean hasComments = false;
for (Event e : new Yaml(loaderOptions).parse(new InputStreamReader(is))) {
if (e instanceof StreamEndEvent) {
inputTextLen = e.getEndMark().getIndex();
}
if (!hasComments && e instanceof CommentEvent) {
hasComments = true;
}
}
return hasComments;
} catch (Throwable t) {
if (is != null) {
is.close();
}
return true;
}
}
@Override
public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException {
CompositeChange changes = new CompositeChange(getName());
TextFileChange textChange = new TextFileChange(getName(), yamlFile);
textChange.setEdit(new ReplaceEdit(0, inputTextLen, propsContent));
changes.add(textChange);
changes.add(new RenameResourceChange(yamlFile.getFullPath(), propsFile.getName()));
changes.initializeValidationData(pm);
return changes;
}
}

View File

@@ -0,0 +1,85 @@
/*******************************************************************************
* Copyright (c) 2024 Broadcom, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Broadcom, Inc. - initial API and implementation
*******************************************************************************/
package org.springframework.ide.eclipse.boot.refactoring;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
public class YamlToPropertiesConverter {
private final RefactoringStatus status;
private final Properties properties;
public YamlToPropertiesConverter(Map<String, ?> yaml) {
this.status = new RefactoringStatus();
this.properties = new Properties() {
private static final long serialVersionUID = 1L;
private LinkedHashMap<Object, Object> delegate = new LinkedHashMap<>();
@Override
public synchronized Object put(Object key, Object value) {
delegate.put(key, value);
return super.put(key, value);
}
@Override
public Set<Map.Entry<Object, Object>> entrySet() {
return delegate.entrySet();
}
};
for (Map.Entry<String, ?> e : yaml.entrySet()) {
readProperties(e.getValue(), e.getKey());
}
}
private void readPropertiesFromYamlMap(Map<String, ?> map, String prefix) {
for (Map.Entry<String, ?> e : map.entrySet()) {
readProperties(e.getValue(), "%s.%s".formatted(prefix, e.getKey()));
}
}
private void readPropertiesFromYamlList(List<?> l, String prefix) {
for (int i = 0; i < l.size(); i++) {
readProperties(l.get(i), "%s[%d]".formatted(prefix, i));
}
}
@SuppressWarnings("unchecked")
private void readProperties(Object o, String prefix) {
if (o instanceof Map) {
readPropertiesFromYamlMap((Map<String, ?>) o, prefix);
} else if ( o instanceof List) {
readPropertiesFromYamlList((List<?>) o, prefix);
} else {
properties.put(prefix, o.toString());
}
}
public RefactoringStatus getStatus() {
return status;
}
public Properties getProperties() {
return properties;
}
}