diff --git a/com.avaloq.tools.ddk.check.ui.test/src/com/avaloq/tools/ddk/check/ui/test/builder/CheckExtensionGeneratorAutoBuildTest.java b/com.avaloq.tools.ddk.check.ui.test/src/com/avaloq/tools/ddk/check/ui/test/builder/CheckExtensionGeneratorAutoBuildTest.java new file mode 100644 index 000000000..3692a1522 --- /dev/null +++ b/com.avaloq.tools.ddk.check.ui.test/src/com/avaloq/tools/ddk/check/ui/test/builder/CheckExtensionGeneratorAutoBuildTest.java @@ -0,0 +1,489 @@ +/******************************************************************************* + * Copyright (c) 2026 Avaloq Group AG and others. + * 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Avaloq Group AG - initial API and implementation + *******************************************************************************/ +package com.avaloq.tools.ddk.check.ui.test.builder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BooleanSupplier; +import java.util.function.Supplier; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.jobs.IJobChangeEvent; +import org.eclipse.core.runtime.jobs.IJobChangeListener; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.core.runtime.jobs.JobChangeAdapter; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.IDocument; +import org.eclipse.swt.widgets.Display; +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.PartInitException; +import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.ide.IDE; +import org.eclipse.ui.texteditor.ITextEditor; +import org.eclipse.xtext.testing.InjectWith; +import org.eclipse.xtext.testing.extensions.InjectionExtension; +import org.eclipse.xtext.ui.testing.util.IResourcesSetupUtil; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +import com.avaloq.tools.ddk.check.CheckUiInjectorProvider; +import com.avaloq.tools.ddk.check.ui.test.AbstractCheckTestCase; +import com.avaloq.tools.ddk.xtext.test.PluginTestProjectManager; + + +/** + * Tests that the Check builder participant edits the {@code plugin.xml} of the built project inside the auto-build, and that this does not make the + * auto-build run again and again. + */ +@SuppressWarnings({"PMD.SignatureDeclareThrowsException", "nls"}) +@InjectWith(CheckUiInjectorProvider.class) +@ExtendWith(InjectionExtension.class) +public class CheckExtensionGeneratorAutoBuildTest extends AbstractCheckTestCase { + + private static final long TIMEOUT_MILLIS = 60_000; + private static final long QUIET_MILLIS = 1_000; + private static final long POLL_MILLIS = 50; + /** Runs of the auto-build job allowed for one change, however many catalogs it has: the run that edits {@code plugin.xml}, and one to spare. */ + private static final int MAX_AUTO_BUILDS = 2; + + private static final String ADDED_CATALOG = "AddOne"; + private static final String CHANGED_CATALOG = "ChangeExisting"; + private static final String PLUGIN_XML = "plugin.xml"; + private static final String LANGUAGE_ATTRIBUTE = "language="; + private static final String PLUGIN_END_TAG = ""; + private static final String TEXT_EDITOR = "org.eclipse.ui.DefaultTextEditor"; + private static final String MANIFEST_EDITOR = "org.eclipse.pde.ui.manifestEditor"; + private static final String LF = "\n"; + private static final String BYTE_ORDER_MARK = "\uFEFF"; + private static final String CRLF = "\r\n"; + private static final String UNSAVED = ""; + private static final String HAND_WRITTEN = """ + + + + """; + private static final String CHECK = """ + + live error %s "%s" + message "%s." { + for Check elem { + issue on elem + } + } + """; + private static final String FOR_GRAMMAR = "\nfor grammar com.avaloq.tools.ddk.check.Check"; + private static final String CATALOG = """ + package autobuild + + import com.avaloq.tools.ddk.check.check.Check + + catalog %s%s { + %s} + """; + + private final AtomicInteger autoBuilds = new AtomicInteger(); + private final IJobChangeListener autoBuildCounter = new JobChangeAdapter() { + @Override + public void aboutToRun(final IJobChangeEvent event) { + if (event.getJob().belongsTo(ResourcesPlugin.FAMILY_AUTO_BUILD)) { + autoBuilds.incrementAndGet(); + } + } + }; + + @AfterEach + public void stopCounting() { + Job.getJobManager().removeJobChangeListener(autoBuildCounter); + } + + /** + * A catalog added to a project that already has a {@code plugin.xml} gets its extensions. + */ + @Test + public void testAddCatalog() throws Exception { + prepareProject("AddExisting"); + + writeCatalogs(List.of(ADDED_CATALOG), true); + + assertAutoBuildSettles(); + assertHasExtensions(ADDED_CATALOG); + } + + /** + * A catalog that no longer names a grammar gets its existing validator extension updated. + */ + @Test + public void testChangeCatalog() throws Exception { + prepareProject(CHANGED_CATALOG); + final String before = getContents(pluginXml()); + + writeCatalogs(List.of(CHANGED_CATALOG), false); + + assertAutoBuildSettles(); + String after = getContents(pluginXml()); + assertHasExtensions(CHANGED_CATALOG); + assertEquals(count(before, LANGUAGE_ATTRIBUTE) - 1, count(after, LANGUAGE_ATTRIBUTE), "the validator extension loses its language:\n" + after); + } + + /** + * Catalogs added together all get their extensions. + */ + @Test + public void testAddCatalogsTogether() throws Exception { + prepareProject("TogetherExisting"); + List catalogs = List.of("TogetherOne", "TogetherTwo", "TogetherThree"); + + writeCatalogs(catalogs, true); + + assertAutoBuildSettles(); + for (String catalog : catalogs) { + assertHasExtensions(catalog); + } + } + + /** + * Comments and extensions written by hand keep their text when a catalog is added. + */ + @Test + public void testKeepHandWrittenContent() throws Exception { + prepareProject("KeepExisting"); + String original = getContents(pluginXml()); + assertTrue(original.contains(PLUGIN_END_TAG), "precondition: plugin.xml has a plugin element:\n" + original); + setContents(pluginXml(), original.replace(PLUGIN_END_TAG, HAND_WRITTEN + PLUGIN_END_TAG)); + assertTrue(waitForAutoBuild(), "precondition: auto-build settles after the edit by hand"); + autoBuilds.set(0); + + String added = "KeepOne"; + writeCatalogs(List.of(added), true); + + assertAutoBuildSettles(); + assertHasExtensions(added); + String after = getContents(pluginXml()); + assertTrue(after.contains(HAND_WRITTEN), "plugin.xml keeps the comment and the extension written by hand as they are:\n" + after); + } + + /** + * A catalog whose extensions do not change leaves {@code plugin.xml} alone. + */ + @Test + public void testUnchangedExtensions() throws Exception { + String catalog = "UnchangedExisting"; + prepareProject(catalog); + final long stamp = pluginXml().getModificationStamp(); + IFile page = project().getFile("docs/content/" + catalog + ".html"); + long pageStamp = page.getModificationStamp(); + + setContents(project().getFile(catalogPath(catalog)), catalogSource(catalog, true).replace(".\" {", " again.\" {")); + + assertAutoBuildSettles(); + assertNotEquals(pageStamp, page.getModificationStamp(), "precondition: the builder participant processed the catalog"); + assertEquals(stamp, pluginXml().getModificationStamp(), "plugin.xml is not written"); + } + + /** + * A {@code plugin.xml} with Windows line endings keeps them. + */ + @Test + public void testWindowsLineEndings() throws Exception { + prepareProject("WindowsExisting"); + setContents(pluginXml(), getContents(pluginXml()).replace(CRLF, LF).replace(LF, CRLF)); + assertTrue(waitForAutoBuild(), "precondition: auto-build settles after the line endings changed"); + autoBuilds.set(0); + + try { + String added = "WindowsOne"; + writeCatalogs(List.of(added), true); + + assertAutoBuildSettles(); + assertHasExtensions(added); + String after = getContents(pluginXml()); + assertFalse(after.replace(CRLF, "").contains(LF), "plugin.xml has Windows line endings only:\n" + after); + } finally { + setContents(pluginXml(), getContents(pluginXml()).replace(CRLF, LF)); // the tests share the project + waitForAutoBuild(); + } + } + + /** + * A {@code plugin.xml} that starts with a byte order mark keeps it. + */ + @Test + public void testByteOrderMark() throws Exception { + prepareProject("MarkExisting"); + String before = getContents(pluginXml()); + setContents(pluginXml(), BYTE_ORDER_MARK + before); + assertTrue(waitForAutoBuild(), "precondition: auto-build settles after the byte order mark was added"); + autoBuilds.set(0); + try { + String added = "MarkOne"; + writeCatalogs(List.of(added), true); + + assertAutoBuildSettles(); + assertHasExtensions(added); + String after = getContents(pluginXml()); + assertTrue(after.startsWith(BYTE_ORDER_MARK + before.substring(0, before.indexOf(""))), "plugin.xml keeps its byte order mark and its prolog:\n" + after); + assertEquals(1, count(after, BYTE_ORDER_MARK), "plugin.xml has one byte order mark:\n" + after); + } finally { + setContents(pluginXml(), getContents(pluginXml()).replace(BYTE_ORDER_MARK, "")); // the tests share the project + waitForAutoBuild(); + } + } + + /** + * A plug-in manifest editor without unsaved changes stays that way when the build writes the extensions to the file. + */ + @Test + public void testManifestEditorWithoutChanges() throws Exception { + prepareProject("ManifestEditorExisting"); + IEditorPart editor = openEditor(MANIFEST_EDITOR); + try { + assertFalse(onUiThread(editor::isDirty), "precondition: the editor has no unsaved changes"); + String added = "ManifestEditorOne"; + writeCatalogs(List.of(added), true); + + assertAutoBuildSettles(); + assertHasExtensions(added); + assertFalse(onUiThread(editor::isDirty), "the manifest editor still has no unsaved changes"); + } finally { + close(editor); + } + } + + /** + * A text editor without unsaved changes shows the extensions that the build wrote. + */ + @Test + public void testEditorWithoutChanges() throws Exception { + prepareProject("CleanEditorExisting"); + ITextEditor editor = openTextEditor(); + try { + String added = "CleanEditorOne"; + writeCatalogs(List.of(added), true); + + assertAutoBuildSettles(); + assertHasExtensions(added); + assertTrue(waitFor(() -> getText(editor).contains(catalogReference(added))), "the editor shows the new extensions:\n" + getText(editor)); + assertFalse(onUiThread(editor::isDirty), "the editor has no unsaved changes"); + } finally { + close(editor); + } + } + + /** + * Unsaved changes in a text editor stay in the editor: the build writes its extensions to the file and does not save the editor. + */ + @Test + public void testEditorWithUnsavedChanges() throws Exception { + prepareProject("DirtyEditorExisting"); + ITextEditor editor = openTextEditor(); + try { + onUiThread(() -> { + IDocument document = getDocument(editor); + try { + document.replace(document.getLength(), 0, UNSAVED); + } catch (BadLocationException e) { + throw new IllegalStateException(e); + } + return null; + }); + assertTrue(onUiThread(editor::isDirty), "precondition: the editor has unsaved changes"); + + String added = "DirtyEditorOne"; + writeCatalogs(List.of(added), true); + + assertAutoBuildSettles(); + assertHasExtensions(added); + assertFalse(getContents(pluginXml()).contains(UNSAVED), "the build does not save the editor"); + assertTrue(onUiThread(editor::isDirty), "the editor keeps its unsaved changes"); + assertTrue(getText(editor).contains(UNSAVED), "the editor keeps its text:\n" + getText(editor)); + } finally { + close(editor); + } + } + + /** + * Builds a first catalog, so that the project is set up for Check and has built state, and starts counting the runs of the auto-build job. + * + * @param catalog + * the name of the first catalog + */ + private void prepareProject(final String catalog) throws Exception { + assertTrue(ResourcesPlugin.getWorkspace().isAutoBuilding(), "precondition: auto-build is on"); + createFile(catalogPath(catalog), catalogSource(catalog, true)); + IResourcesSetupUtil.waitForBuild(); + assertTrue(waitForAutoBuild(), "precondition: auto-build settles after the explicit build"); + assertHasExtensions(catalog); + Job.getJobManager().addJobChangeListener(autoBuildCounter); + } + + /** + * Creates or overwrites the given catalogs in one workspace operation, so that one auto-build sees them all. + * + * @param catalogs + * the names of the catalogs + * @param withGrammar + * whether the catalogs name a grammar + */ + private void writeCatalogs(final List catalogs, final boolean withGrammar) throws Exception { + ResourcesPlugin.getWorkspace().run(monitor -> { + for (String catalog : catalogs) { + IFile file = project().getFile(catalogPath(catalog)); + InputStream source = new ByteArrayInputStream(catalogSource(catalog, withGrammar).getBytes(StandardCharsets.UTF_8)); + if (file.exists()) { + file.setContents(source, true, false, monitor); + } else { + file.create(source, true, monitor); + } + } + }, new NullProgressMonitor()); + } + + private void setContents(final IFile file, final String contents) throws Exception { + file.setContents(new ByteArrayInputStream(contents.getBytes(StandardCharsets.UTF_8)), true, false, new NullProgressMonitor()); + } + + private ITextEditor openTextEditor() { + return (ITextEditor) openEditor(TEXT_EDITOR); + } + + private IEditorPart openEditor(final String editorId) { + return onUiThread(() -> { + try { + return IDE.openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), pluginXml(), editorId); + } catch (PartInitException e) { + throw new IllegalStateException(e); + } + }); + } + + private void close(final IEditorPart editor) { + onUiThread(() -> editor.getSite().getPage().closeEditor(editor, false)); + } + + private static IDocument getDocument(final ITextEditor editor) { + return editor.getDocumentProvider().getDocument(editor.getEditorInput()); + } + + private String getText(final ITextEditor editor) { + return onUiThread(() -> getDocument(editor).get()); + } + + private T onUiThread(final Supplier supplier) { + AtomicReference result = new AtomicReference<>(); + Display.getDefault().syncExec(() -> result.set(supplier.get())); + return result.get(); + } + + /** + * Waits until the condition holds. + * + * @param condition + * the condition to wait for + * @return {@code false} if that did not happen before the timeout + */ + private boolean waitFor(final BooleanSupplier condition) throws InterruptedException { + long deadline = System.currentTimeMillis() + TIMEOUT_MILLIS; + while (!condition.getAsBoolean()) { + if (System.currentTimeMillis() >= deadline) { + return false; + } + Thread.sleep(POLL_MILLIS); + } + return true; + } + + private void assertAutoBuildSettles() throws Exception { + boolean settled = waitForAutoBuild(); + int builds = autoBuilds.get(); + assertTrue(settled, "auto-build settles within " + TIMEOUT_MILLIS + " ms; runs of the auto-build job so far: " + builds); + assertTrue(builds <= MAX_AUTO_BUILDS, "at most " + MAX_AUTO_BUILDS + " runs of the auto-build job: " + builds); + } + + private void assertHasExtensions(final String catalog) throws Exception { + String pluginXml = getContents(pluginXml()); + assertTrue(pluginXml.contains(catalogReference(catalog)), "plugin.xml has the extensions of " + catalog + ":\n" + pluginXml); + } + + /** + * Waits until no auto-build has been pending for the quiet period. + * + * @return {@code false} if that did not happen before the timeout + */ + private boolean waitForAutoBuild() throws InterruptedException { + long deadline = System.currentTimeMillis() + TIMEOUT_MILLIS; + long quietSince = System.currentTimeMillis(); + int seenBuilds = autoBuilds.get(); + while (System.currentTimeMillis() < deadline) { + Job[] pending = Job.getJobManager().find(ResourcesPlugin.FAMILY_AUTO_BUILD); + if (pending.length > 0 || autoBuilds.get() != seenBuilds) { + for (Job job : pending) { + job.join(Math.max(1, deadline - System.currentTimeMillis()), null); + } + seenBuilds = autoBuilds.get(); + quietSince = System.currentTimeMillis(); + } else if (System.currentTimeMillis() - quietSince >= QUIET_MILLIS) { + return true; + } else { + Thread.sleep(POLL_MILLIS); + } + } + return false; + } + + /** + * The end of the attribute value with which an extension in {@code plugin.xml} refers to the given catalog. + * + * @param catalog + * the name of the catalog + * @return the text to look for + */ + private static String catalogReference(final String catalog) { + return "/" + catalog + ".check\""; + } + + private static String catalogPath(final String catalog) { + return "src/autobuild/" + catalog + ".check"; + } + + private static String catalogSource(final String catalog, final boolean withGrammar) { + return String.format(CATALOG, catalog, withGrammar ? FOR_GRAMMAR : "", String.format(CHECK, catalog, catalog, catalog)); + } + + private static IProject project() { + return ResourcesPlugin.getWorkspace().getRoot().getProject(PluginTestProjectManager.TEST_PROJECT_NAME); + } + + private static IFile pluginXml() { + return project().getFile(PLUGIN_XML); + } + + private static int count(final String text, final String part) { + int count = 0; + for (int i = text.indexOf(part); i >= 0; i = text.indexOf(part, i + 1)) { + count++; + } + return count; + } +} diff --git a/com.avaloq.tools.ddk.check.ui/src/com/avaloq/tools/ddk/check/ui/builder/CheckExtensionGenerator.java b/com.avaloq.tools.ddk.check.ui/src/com/avaloq/tools/ddk/check/ui/builder/CheckExtensionGenerator.java index 0805628c6..c91d67e6d 100644 --- a/com.avaloq.tools.ddk.check.ui/src/com/avaloq/tools/ddk/check/ui/builder/CheckExtensionGenerator.java +++ b/com.avaloq.tools.ddk.check.ui/src/com/avaloq/tools/ddk/check/ui/builder/CheckExtensionGenerator.java @@ -34,7 +34,6 @@ import org.eclipse.emf.common.util.URI; import org.eclipse.emf.common.util.WrappedException; import org.eclipse.emf.ecore.EValidator; -import org.eclipse.pde.core.IBaseModel; import org.eclipse.pde.core.plugin.IFragmentModel; import org.eclipse.pde.core.plugin.IPlugin; import org.eclipse.pde.core.plugin.IPluginAttribute; @@ -54,10 +53,6 @@ import org.eclipse.pde.internal.core.plugin.WorkspacePluginModelBase; import org.eclipse.pde.internal.core.project.PDEProject; import org.eclipse.pde.internal.ui.PDEPlugin; -import org.eclipse.pde.internal.ui.util.ModelModification; -import org.eclipse.pde.internal.ui.util.PDEModelUtility; -import org.eclipse.swt.SWTException; -import org.eclipse.ui.PlatformUI; import org.eclipse.xtext.builder.IXtextBuilderParticipant.IBuildContext; import org.eclipse.xtext.resource.IEObjectDescription; import org.eclipse.xtext.resource.IResourceDescription.Delta; @@ -342,17 +337,20 @@ void changePluginXmlFile(final IBuildContext context, final Delta delta, final I } IFile file = getPluginFile(uri); - if (!validPluginFile(file)) { - createNewFile(catalog, file, monitor); - } else { - if (!catalogValidates(catalog)) { - removeExtensions(file, catalog, monitor); + try { + if (!validPluginFile(file)) { + createNewFile(catalog, file, monitor); } else { - updateExtensions(file, catalog, monitor); - // TODO improve by only updating the manifest if the validator extension has changed.. + if (!catalogValidates(catalog)) { + removeExtensions(file, catalog, monitor); + } else { + updateExtensions(file, catalog, monitor); + // TODO improve by only updating the manifest if the validator extension has changed.. + } } + } finally { + mergeManifest(catalog, monitor); // also when the plug-in file could not be edited } - mergeManifest(catalog, monitor); } /** @@ -405,24 +403,12 @@ private void updateExtensions(final IFile pluginXmlFile, final CheckCatalog cata manager.sortAllExtensions(pluginModel, monitor); ModelSaver.saveIfChanged(pluginModel); } else { - final ModelModification modification = new ModelModification(pluginXmlFile) { - @Override - protected void modifyModel(final IBaseModel model, final IProgressMonitor monitor) throws CoreException {// NOPMD NPath complexity - if (!(model instanceof IPluginModelBase)) { - return; - } - IPluginModelBase pluginModel = (IPluginModelBase) model; - manager.updateExtensions(catalog, pluginModel, monitor); - manager.addExtensions(catalog, pluginModel, monitor); - manager.sortAllExtensions(pluginModel, monitor); - } - - @Override - public boolean saveOpenEditor() { - return false; // do nothing with any open editor... - } - }; - modifyModel(modification, monitor); + checkCanceled(monitor); + PluginXmlEditor.modify(pluginXmlFile, pluginModel -> { + manager.updateExtensions(catalog, pluginModel, monitor); + manager.addExtensions(catalog, pluginModel, monitor); + manager.sortAllExtensions(pluginModel, monitor); + }); } } @@ -460,26 +446,14 @@ private void removeExtensions(final IFile file, final Object object, final IProg } ModelSaver.saveIfChanged(pluginModel); } else { - final ModelModification mod = new ModelModification(file) { - @Override - protected void modifyModel(final IBaseModel model, final IProgressMonitor monitor) throws CoreException { - if (!(model instanceof IPluginModelBase)) { - return; - } - IPluginModelBase pluginModel = (IPluginModelBase) model; - if (object instanceof IEObjectDescription) { - manager.removeExtensions((IEObjectDescription) object, pluginModel, monitor); // called when catalog is deleted - } else if (object instanceof CheckCatalog) { - manager.removeExtensions((CheckCatalog) object, pluginModel, monitor); // called in order to remove extensions in an invalid model - } + checkCanceled(monitor); + PluginXmlEditor.modify(file, pluginModel -> { + if (object instanceof IEObjectDescription) { + manager.removeExtensions((IEObjectDescription) object, pluginModel, monitor); // called when catalog is deleted + } else if (object instanceof CheckCatalog) { + manager.removeExtensions((CheckCatalog) object, pluginModel, monitor); // called in order to remove extensions in an invalid model } - - @Override - public boolean saveOpenEditor() { - return false; // prevent modifications to open plugin manifest editor; the editor will become dirty once the modification is performed - } - }; - modifyModel(mod, monitor); + }); } } @@ -518,34 +492,17 @@ private void mergeManifest(final CheckCatalog catalog, final IProgressMonitor mo } /** - * Performs modifications to the Plugin Model. + * Stops the build before the {@code plugin.xml} file is edited if it was canceled. * - * @param modification - * a modification * @param monitor * progress monitor * @throws OperationCanceledException * if the operation was canceled */ - void modifyModel(final ModelModification modification, final IProgressMonitor monitor) { + private static void checkCanceled(final IProgressMonitor monitor) { if (monitor.isCanceled()) { throw new OperationCanceledException(); } - try { - PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() { - @Override - public void run() { - PDEModelUtility.modifyModel(modification, monitor); - } - }); - } catch (SWTException e) { - // If the build was cancelled while in syncExec() it will throw an SWTException - if (monitor.isCanceled()) { - throw new OperationCanceledException(); // NOPMD PreserveStackTrace - SWTException is just the cancellation signal - } else { - throw e; - } - } } /** diff --git a/com.avaloq.tools.ddk.check.ui/src/com/avaloq/tools/ddk/check/ui/builder/PluginXmlEditor.java b/com.avaloq.tools.ddk.check.ui/src/com/avaloq/tools/ddk/check/ui/builder/PluginXmlEditor.java new file mode 100644 index 000000000..eb2eac989 --- /dev/null +++ b/com.avaloq.tools.ddk.check.ui/src/com/avaloq/tools/ddk/check/ui/builder/PluginXmlEditor.java @@ -0,0 +1,165 @@ +/******************************************************************************* + * Copyright (c) 2026 Avaloq Group AG and others. + * 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 + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Avaloq Group AG - initial API and implementation + *******************************************************************************/ +package com.avaloq.tools.ddk.check.ui.builder; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.Charset; +import java.nio.charset.CodingErrorAction; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Status; +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.Document; +import org.eclipse.jface.text.IDocument; +import org.eclipse.pde.core.plugin.IPluginModelBase; +import org.eclipse.pde.internal.core.text.plugin.PluginModel; +import org.eclipse.pde.internal.core.text.plugin.XMLTextChangeListener; +import org.eclipse.text.edits.MalformedTreeException; +import org.eclipse.text.edits.MultiTextEdit; +import org.eclipse.text.edits.TextEdit; + +import com.avaloq.tools.ddk.check.ui.internal.Activator; + + +/** + * Edits a {@code plugin.xml} file on the calling thread. + *

+ * The changes are made to PDE's text model of the file and applied as text edits, as {@code PDEModelUtility} does when no editor is open, so the parts of + * the file that do not change keep their formatting and comments. The edits are applied to a private copy of the content and not to the shared file buffer, + * so this needs neither the UI thread nor a workbench and can run inside a build. An editor that has the file open sees the write as any other change on + * disk. + *

+ */ +@SuppressWarnings("restriction") +final class PluginXmlEditor { + + /** + * A change to the plug-in model of a {@code plugin.xml} file. + */ + @FunctionalInterface + interface Modification { + /** + * Changes the given model. + * + * @param model + * the model to change + * @throws CoreException + * if the model cannot be changed + */ + void apply(IPluginModelBase model) throws CoreException; + } + + private PluginXmlEditor() { + // static helpers only + } + + /** + * Applies a modification to the given {@code plugin.xml} file and writes the file if that changes its content. + * + * @param file + * the {@code plugin.xml} file, must exist + * @param modification + * the modification to apply + * @return {@code true} if the file was written + * @throws CoreException + * if the file cannot be read, parsed, edited or written + */ + static boolean modify(final IFile file, final Modification modification) throws CoreException { + final Charset charset = getCharset(file); + final String original = read(file, charset); + final IDocument document = new Document(original); + final PluginModel model = new PluginModel(document, true); + try { + model.setUnderlyingResource(file); + model.setCharset(charset); + model.load(); + if (!model.isLoaded()) { + throw new CoreException(error("Could not parse " + file.getFullPath(), null)); //$NON-NLS-1$ + } + final XMLTextChangeListener listener = new XMLTextChangeListener(document); + model.addModelChangedListener(listener); + + modification.apply(model); + + final TextEdit[] edits = listener.getTextOperations(); + if (edits.length == 0) { + return false; + } + final MultiTextEdit edit = new MultiTextEdit(); + edit.addChildren(edits); + edit.apply(document); + } catch (MalformedTreeException | BadLocationException e) { + throw new CoreException(error("Could not edit " + file.getFullPath(), e)); //$NON-NLS-1$ + } finally { + model.dispose(); + } + final String changed = document.get(); + if (changed.equals(original)) { + return false; + } + file.setContents(new ByteArrayInputStream(encode(changed, charset, file)), IResource.FORCE | IResource.KEEP_HISTORY, null); + return true; + } + + /** + * Encodes the content, and fails instead of replacing a character that the charset of the file cannot represent. + * + * @param content + * the content to encode + * @param charset + * the charset of the file + * @param file + * the file, for the error message + * @return the encoded content + * @throws CoreException + * if the charset cannot represent the content + */ + private static byte[] encode(final String content, final Charset charset, final IFile file) throws CoreException { + try { + ByteBuffer bytes = charset.newEncoder().onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT).encode(CharBuffer.wrap(content)); + byte[] result = new byte[bytes.remaining()]; + bytes.get(result); + return result; + } catch (CharacterCodingException e) { + throw new CoreException(error("Could not encode " + file.getFullPath() + " as " + charset, e)); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + + private static Charset getCharset(final IFile file) throws CoreException { + String name = file.getCharset(); + try { + return Charset.forName(name); + } catch (IllegalArgumentException e) { // an illegal or unsupported charset name + throw new CoreException(error("Unknown charset " + name + " of " + file.getFullPath(), e)); //$NON-NLS-1$ //$NON-NLS-2$ + } + } + + private static String read(final IFile file, final Charset charset) throws CoreException { + try (InputStream stream = file.getContents(true)) { + return new String(stream.readAllBytes(), charset); + } catch (IOException e) { + throw new CoreException(error("Could not read " + file.getFullPath(), e)); //$NON-NLS-1$ + } + } + + private static IStatus error(final String message, final Throwable cause) { + return new Status(IStatus.ERROR, Activator.getPluginId(), IStatus.ERROR, message, cause); + } + +}