diff --git a/_ext/eclipse-base/CHANGES.md b/_ext/eclipse-base/CHANGES.md deleted file mode 100644 index 796ed584fd..0000000000 --- a/_ext/eclipse-base/CHANGES.md +++ /dev/null @@ -1,53 +0,0 @@ -# spotless-eclipse-base - -We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format (starting after version `3.2.1`). - -## [Unreleased] - -## [3.5.2] - 2021-10-23 -### Fixed -* Racing condition when cleaning up temporary workspace on JVM runtime shutdown (see [#967](https://github.com/diffplug/spotless/issues/967)). Can lead to error logs and remaining files in workspace. - -## [3.5.1] - 2021-10-16 -### Fixed -* ~~Racing condition when cleaning up temporary workspace on JVM runtime shutdown (see [#967](https://github.com/diffplug/spotless/issues/967)). Can lead to error logs and remaining files in workspace.~~ - -## [3.5.0] - 2021-06-20 -### Added -* Support of `org.eclipse.core.resources` version `3.15.0` required by Eclipse `4.20`. -* Minimum required Java version changed from 8 to 11. - -## [3.4.2] - 2020-12-26 -### Fixed -* `org.eclipse.osgi` version `3.16.100` does not allow `null` as Debug service for `CloseableBundleFile`. - -## [3.4.1] - 2020-09-24 -### Fixed -* Restored scope of transitive dependencies to 'compile'. - -## [3.4.0] - 2020-09-23 -### Added -* Upgraded to `org.eclipse.osgi` version `3.16`. - -## [3.3.0] - 2020-03-04 -### Added -* Added support of plugin extensions without activator ([#533](https://github.com/diffplug/spotless/issues/533)). Required since `org.eclipse.core.filesystem` version `1.7.600` (see -[Bug 550548](https://bugs.eclipse.org/bugs/show_bug.cgi?id=550548)) -* Updated configuration via single interface implementation. Functional based configuration still supported. - -## [3.2.1] - 2019-09-03 -* Fixed deletion of temporary workspace. ([#447](https://github.com/diffplug/spotless/issues/447)) - -## [3.2.0] - 2019-06-30 -* Added support of Eclipse 4.12 framework wiring. ([#413](https://github.com/diffplug/spotless/issues/413)) - -## [3.1.1] - 2019-06-04 -* Fixed problem handling URL escaped characters in JAR file location. ([#401](https://github.com/diffplug/spotless/issues/401)) - -## [3.1.0] - 2019-02-10 -* Added logging service based on SLF4J. ([#236](https://github.com/diffplug/spotless/issues/236)) -* Updated internal interfaces to support `org.eclipse.osgi` version 3.13. -* Corrected documentation of version number usage in `gradle.properties`. - -## [3.0.0] - 2018-06-18 -* Initial release! diff --git a/_ext/eclipse-base/LICENSE.txt b/_ext/eclipse-base/LICENSE.txt deleted file mode 100644 index 3d967aee74..0000000000 --- a/_ext/eclipse-base/LICENSE.txt +++ /dev/null @@ -1,70 +0,0 @@ -Eclipse Public License - v 1.0 - -THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. - -1. DEFINITIONS - -"Contribution" means: - -a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and -b) in the case of each subsequent Contributor: -i) changes to the Program, and -ii) additions to the Program; -where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program. -"Contributor" means any person or entity that distributes the Program. - -"Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program. - -"Program" means the Contributions distributed in accordance with this Agreement. - -"Recipient" means anyone who receives the Program under this Agreement, including all Contributors. - -2. GRANT OF RIGHTS - -a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form. -b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder. -c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program. -d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement. -3. REQUIREMENTS - -A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that: - -a) it complies with the terms and conditions of this Agreement; and -b) its license agreement: -i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose; -ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits; -iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and -iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange. -When the Program is made available in source code form: - -a) it must be made available under this Agreement; and -b) a copy of this Agreement must be included with each copy of the Program. -Contributors may not remove or alter any copyright notices contained within the Program. - -Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution. - -4. COMMERCIAL DISTRIBUTION - -Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense. - -For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages. - -5. NO WARRANTY - -EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations. - -6. DISCLAIMER OF LIABILITY - -EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -7. GENERAL - -If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. - -If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed. - -All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive. - -Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved. - -This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation. \ No newline at end of file diff --git a/_ext/eclipse-base/README.md b/_ext/eclipse-base/README.md deleted file mode 100644 index 39a03591ab..0000000000 --- a/_ext/eclipse-base/README.md +++ /dev/null @@ -1,62 +0,0 @@ -# spotless-eclipse-base - -Eclipse formatters are embedded in plugins serving multiple purposes and not necessarily supporting headless builds. Hence the plugin interfaces are depending on various Eclipse plugins and services not required for the formatting purpose. - -Spotless provides its own plugin framework with `com.diffplug.spotless.JarState`. This allows Spotless to use different Eclipse versions in parallel. - - -The `com.diffplug.gradle.spotless:spotless-eclipse-base` artifact mocks the redundant Eclipse OSGI/plugin framework for Spotless. Furthermore it provides Eclipse services adapted for Spotless's own use, which avoids for example the creation of a permanent Eclipse workspace and reduces dependencies on Eclipse modules unused by the Eclipse code formatters. - -## Usage - -Include the artifact in your Spotless Eclipse formatter project, where the major version must match the Eclipse core version your formatter supports. The exact default version should be selected by the **lib-extra**. -Minor versions indicate a change in the minimum Eclipse (core/resource) dependencies. -Patch versions are always backward compatible. - - -```Gradle -dependencies { - compile "com.diffplug.spotless:spotless-eclipse-base:3.+" -} -``` - -In the constructor of your formatter, the Spotless Eclipse Framework can be configured depending on your formatter's requirements. For example the JDT formatter can be configured like: - -```Java -public EclipseFormatterStepImpl(Properties settings) throws Exception { - SpotlessEclipseFramework.setup(plugins -> { - plugins.applyDefault(); - plugins.add(new org.eclipse.jdt.core.JavaCore()); - }); - ... -``` - -The framework also supports fat JARs, providing multiple plugins. -In this cases the resources required by plugins, especially the `META-INF` and plugin information, must be located in locations unique to the plugin. -For this purpose the framework expects that these resources are stored in a sub-directory -which has the name of the package containing the plugin. For example in case the JDT plugin -is included in your formatter fat JAR, the directory structure should be: - -``` -+ resources -| -+--+ org.eclipse.jdt.core -| | -| +--+ META-INF -| | | -| | +-- MANIFEST.MF -| | -| +--- plugin.properties -| | -| +--- plugin.xml - -``` - -## Build - -To publish a new version, update the `_ext/eclipse-base/gradle.properties` appropriately and see [CONTRIBUTING.md](../../CONTRIBUTING.md) how to enable -`_ext` projects. - -## License - -Spotless at large is under the Apache 2.0 license, but this jar is under the EPL v1. diff --git a/_ext/eclipse-base/build.gradle b/_ext/eclipse-base/build.gradle deleted file mode 100644 index 88255b57b3..0000000000 --- a/_ext/eclipse-base/build.gradle +++ /dev/null @@ -1,32 +0,0 @@ -apply from: rootProject.file('_ext/gradle/java-setup.gradle') -apply from: rootProject.file('gradle/java-publish.gradle') - -ext { - developers = [ - fvgh: [ name: 'Frank Vennemeyer', email: 'frankgh@zoho.com' ] - ] -} - -dependencies { - api("org.eclipse.platform:org.eclipse.core.resources:${VER_ECLIPSE_CORE_RESOURCES}") { - exclude group: 'org.eclipse.platform', module: 'org.eclipse.ant.core' - exclude group: 'org.eclipse.platform', module: 'org.eclipse.core.expressions' - } - api("org.slf4j:slf4j-api:${VER_SLF4J}") - - testImplementation("org.slf4j:slf4j-simple:${VER_SLF4J}") -} - -jar { - manifest { - from 'src/main/resources/META-INF/MANIFEST.MF' - } -} - -////////// -// Test // -////////// -sourceSets { - // Use JAR file with all resources for Eclipse-Base integration-tests - test.runtimeClasspath = jar.outputs.files + sourceSets.test.output + sourceSets.test.compileClasspath -} diff --git a/_ext/eclipse-base/gradle.properties b/_ext/eclipse-base/gradle.properties deleted file mode 100644 index 9f8774a417..0000000000 --- a/_ext/eclipse-base/gradle.properties +++ /dev/null @@ -1,8 +0,0 @@ -artifactId=spotless-eclipse-base -description=Eclipse bundle controller and services for Spotless - -# Build requirements -VER_JAVA=11 - -# Compile dependencies -VER_ECLIPSE_CORE_RESOURCES=[3.15.0,4.0.0[ diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipseConfig.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipseConfig.java deleted file mode 100644 index c8d1fb4db3..0000000000 --- a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipseConfig.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.base; - -/** - * Obtain configuration for Eclipse framework setup - *

- * The setup consitst of 4 phases: - *

    - *
  1. Registration of framework bundles
  2. - *
  3. Registration of servicves
  4. - *
  5. Resitration of extension points, activation of bundles/plugins
  6. - *
  7. Customize bundle/plugin configuration
  8. - *
- */ -public interface SpotlessEclipseConfig { - default public void registerBundles(SpotlessEclipseCoreConfig config) { - config.applyDefault(); - } - - default public void registerServices(SpotlessEclipseServiceConfig config) { - config.applyDefault(); - } - - default public void activatePlugins(SpotlessEclipsePluginConfig config) { - config.applyDefault(); - } - - default public void customize() {} -} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipseCoreConfig.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipseCoreConfig.java deleted file mode 100644 index 4f3aa9c2a2..0000000000 --- a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipseCoreConfig.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.base; - -import org.osgi.framework.BundleActivator; - -import com.diffplug.spotless.extra.eclipse.base.SpotlessEclipseFramework.DefaultBundles; -import com.diffplug.spotless.extra.eclipse.base.osgi.BundleConfig; - -/** - * Configuration of core bundles which shall be provided by the - * {@link SpotlessEclipseFramework}. - *

- * Core bundles are not accessed via the plugin registry, but by static methods. - * Hence they do not require a registration, which allows a lightweight - * setup. - *

- * See {@code org.eclipse.core.internal.runtime.PlatformActivator} implementation for details. - */ -public class SpotlessEclipseCoreConfig extends BundleConfig { - - /** - * Don't instantiate and call {@link SpotlessEclipseConfig} directly. - * Registered bundles should only be instantiated once, since - * older bundles still abusing singletons for access. - */ - SpotlessEclipseCoreConfig() {} - - @Override - public void applyDefault() { - add(SpotlessEclipseFramework.DefaultBundles.createAll()); - } - - @Override - protected BundleActivator create(DefaultBundles bundle) { - return bundle.create(); - } - - @Override - protected int getDefaultState(DefaultBundles bundle) { - return bundle.getDesiredState(); - } - -} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipseFramework.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipseFramework.java deleted file mode 100644 index 2eaf9e568e..0000000000 --- a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipseFramework.java +++ /dev/null @@ -1,306 +0,0 @@ -/* - * Copyright 2016-2021 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.base; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.util.Arrays; -import java.util.List; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.stream.Collectors; - -import javax.xml.parsers.SAXParserFactory; - -import org.eclipse.core.internal.runtime.InternalPlatform; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.osgi.framework.BundleException; - -import com.diffplug.spotless.extra.eclipse.base.osgi.BundleConfig; -import com.diffplug.spotless.extra.eclipse.base.osgi.BundleController; -import com.diffplug.spotless.extra.eclipse.base.runtime.PluginRegistrar; - -/** Setup a framework for Spotless Eclipse based formatters */ -public final class SpotlessEclipseFramework { - /** Spotless demands for internal formatter chains Unix (LF) line endings. */ - public static final String LINE_DELIMITER = "\n"; - - /** - * Default core bundles required by most plugins. - */ - public enum DefaultBundles { - /** - * Plugins ask the platform whether core runtime bundle is in debug mode. - *

- * Note that the bundle requires the - * {@link org.eclipse.osgi.service.environment.EnvironmentInfo} - * service. - *

- *

- * Per default, the platform is not activated. Some plugins use this information - * to determine whether they are running in a headless modes (without IDE). - *

- */ - PLATFORM(org.eclipse.core.internal.runtime.PlatformActivator.class, Bundle.RESOLVED), - /** The Spotless {@link BundleController} wraps the OSGi layer. But the plugin/extension look-up still uses the Eclipse OSGi registry.*/ - REGISTRY(org.eclipse.core.internal.registry.osgi.Activator.class), - /** Eclipse preferences always check whether this bundle has been activated before preference are set.*/ - PREFERENCES(org.eclipse.core.internal.preferences.Activator.class), - /** The common runtime provides common services, like log and service adapters registry. */ - COMMON(org.eclipse.core.internal.runtime.Activator.class); - - private final Class activatorClass; - private final int state; - - private DefaultBundles(Class clazz) { - this(clazz, Bundle.ACTIVE); - } - - private DefaultBundles(Class clazz, int state) { - activatorClass = clazz; - this.state = state; - } - - /** Create new bundle activator instance. */ - public BundleActivator create() { - return createInstance(activatorClass); - } - - public int getDesiredState() { - return state; - } - - /** Create bundle activator instances for all enumerated values. */ - public static List createAll() { - return Arrays.stream(values()) - .map(value -> new BundleConfig.Entry(value.create(), value.getDesiredState())).collect(Collectors.toList()); - } - } - - /** - * Default plugins required by most Spotless formatters. - *

- * Eclipse plugins are OSGI bundles themselves and do not necessarily derive from the Eclipse Plugin class. - * {@link BundleActivator} implementation may as well serve as plugins. - * All plugins must provide a MANIFEST.MF, plugin.properties and plugin.xml description file, - * required for the plugin registration. - *

- */ - public enum DefaultPlugins { - /** - * The resources plugin initialized the Eclipse workspace and allows URL look-up. - * Most formatters using the workspace to resolve URLs or create - * file interfaces. - * See {@code org.eclipse.core.resources.IFile} implementation for details. - */ - RESOURCES(org.eclipse.core.resources.ResourcesPlugin.class); - - private final Class pluginClass; - - DefaultPlugins(Class clazz) { - pluginClass = clazz; - } - - /** Create new plugin instance. */ - public BundleActivator create() { - return createInstance(pluginClass); - } - - /** Create plugin instances for all enumerated values. */ - public static List createAll() { - return Arrays.stream(values()).map(value -> value.create()).collect(Collectors.toList()); - } - } - - private static T createInstance(Class clazz) { - try { - Constructor ctor = clazz.getConstructor(); - return ctor.newInstance(new Object[]{}); - } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { - throw new RuntimeException("Failed to create instance for: " + clazz.getCanonicalName(), e); - } - } - - private static SpotlessEclipseFramework INSTANCE = null; - - /** - * Creates and configures a new {@link SpotlessEclipseFramework} using - * {@link DefaultBundles}, {@link DefaultPlugins} and default {@link SpotlessEclipseServiceConfig}. - * If there is already a an instance, the call is ignored. - * @return False if the {@link SpotlessEclipseFramework} instance already exists, true otherwise. - * @throws BundleException Throws exception in case the setup failed. - * @deprecated Use {@link #setup(SpotlessEclipseConfig)} instead. - */ - @Deprecated - public synchronized static boolean setup() throws BundleException { - return setup(plugins -> plugins.applyDefault()); - } - - /** - * Creates and configures a new {@link SpotlessEclipseFramework} using - * {@link DefaultBundles} and {@link DefaultPlugins}. - * If there is already a an instance, the call is ignored. - * @param plugins Eclipse plugins (which are also OSGi bundles) to start - * @return False if the {@link SpotlessEclipseFramework} instance already exists, true otherwise. - * @throws BundleException Throws exception in case the setup failed. - * @deprecated Use {@link #setup(SpotlessEclipseConfig)} instead. - */ - @Deprecated - public synchronized static boolean setup(Consumer plugins) throws BundleException { - return setup(config -> config.applyDefault(), plugins); - } - - /** - * Creates and configures a new {@link SpotlessEclipseFramework} using {@link DefaultBundles}. - * If there is already a an instance, the call is ignored. - * @param config Framework service configuration - * @param plugins Eclipse plugins (which are also OSGi bundles) to start - * @return False if the {@link SpotlessEclipseFramework} instance already exists, true otherwise. - * @throws BundleException Throws exception in case the setup failed. - * @deprecated Use {@link #setup(SpotlessEclipseConfig)} instead. - */ - @Deprecated - public synchronized static boolean setup(Consumer config, Consumer plugins) throws BundleException { - return setup(core -> core.applyDefault(), config, plugins); - } - - /** - * Creates and configures a new {@link SpotlessEclipseFramework} if there is none. - * If there is already a an instance, the call is ignored. - * @param core Activators of core bundles - * @param services Framework service configuration - * @param plugins Eclipse plugins to start - * @return False if the {@link SpotlessEclipseFramework} instance already exists, true otherwise. - * @throws BundleException Throws exception in case the setup failed. - * @deprecated Use {@link #setup(SpotlessEclipseConfig)} instead. - */ - @Deprecated - public synchronized static boolean setup(Consumer core, Consumer services, Consumer plugins) throws BundleException { - if (null != INSTANCE) { - return false; - } - setup(new SpotlessEclipseConfig() { - @Override - public void registerBundles(SpotlessEclipseCoreConfig config) { - core.accept(config); - } - - @Override - public void registerServices(SpotlessEclipseServiceConfig config) { - services.accept(config); - } - - @Override - public void activatePlugins(SpotlessEclipsePluginConfig config) { - plugins.accept(config); - } - }); - return true; - } - - /** - * Creates and configures a new {@link SpotlessEclipseFramework} if there is none. - * If there is already a an instance, the call is ignored. - * @param config Configuration - * @throws BundleException Throws exception in case the setup failed. - */ - public synchronized static void setup(SpotlessEclipseConfig config) throws BundleException { - if (null == INSTANCE) { - INSTANCE = new SpotlessEclipseFramework(); - Runtime.getRuntime().addShutdownHook(new Thread(() -> { - try { - INSTANCE.shutdown(); - } catch (Exception e) { - //At shutdown everything is just done on best-efforts basis - } - })); - - config.registerServices(INSTANCE.getServiceConfig()); - - SpotlessEclipseCoreConfig coreConfig = new SpotlessEclipseCoreConfig(); - config.registerBundles(coreConfig); - INSTANCE.startCoreBundles(coreConfig); - - SpotlessEclipsePluginConfig pluginConfig = new SpotlessEclipsePluginConfig(); - config.activatePlugins(pluginConfig); - for (Class extension : pluginConfig.getExtensions()) { - INSTANCE.addExtension(extension); - } - for (BundleConfig.Entry plugin : pluginConfig.get()) { - INSTANCE.addPlugin(plugin.state, plugin.activator); - } - - config.customize(); - } - } - - private final Function registry; - private final BundleController controller; - - private SpotlessEclipseFramework() throws BundleException { - - controller = new BundleController(); - registry = (pluginBundle) -> { - return PluginRegistrar.register(pluginBundle); - }; - } - - void shutdown() { - controller.shutdown(); - } - - private SpotlessEclipseServiceConfig getServiceConfig() { - return controller.getServices(); - } - - private void addExtension(Class clazzInBundleJar) throws BundleException { - controller.addBundle(clazzInBundleJar, registry); - } - - private void addPlugin(int state, BundleActivator plugin) throws BundleException { - controller.addBundle(state, plugin, registry); - } - - private void startCoreBundles(SpotlessEclipseCoreConfig coreConfig) throws BundleException { - //The SAXParserFactory.class is required for parsing the plugin XML files - addMandatoryServiceIfMissing(SAXParserFactory.class, SAXParserFactory.newInstance()); - - /* - * Since org.eclipse.core.runtime version 3.15.300, the Eclipse bundle look-up is accomplished - * via the wiring framework, which requires starting the InternalPlatform. - * The internal platform initialization is customized by the services - * registered to the controller. - */ - InternalPlatform.getDefault().start(controller); - - for (BundleConfig.Entry coreBundle : coreConfig.get()) { - try { - BundleContext context = controller.createContext(coreBundle.state); - coreBundle.activator.start(context); - } catch (Exception e) { - throw new BundleException(String.format("Failed to start %s", coreBundle.activator.getClass().getName()), BundleException.ACTIVATOR_ERROR, e); - } - } - } - - private void addMandatoryServiceIfMissing(Class interfaceClass, S service) { - if (null == controller.getServiceReference(interfaceClass)) { - controller.getServices().add(interfaceClass, service); - } - } -} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipsePluginConfig.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipsePluginConfig.java deleted file mode 100644 index 2569c12cd9..0000000000 --- a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipsePluginConfig.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.base; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; - -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleActivator; - -import com.diffplug.spotless.extra.eclipse.base.SpotlessEclipseFramework.DefaultPlugins; -import com.diffplug.spotless.extra.eclipse.base.osgi.BundleConfig; - -/** - * Configuration of plugins which shall be provided by the - * {@link SpotlessEclipseFramework}. - *

- * Plugins are registered via the Eclipse registry. Therefore they - * required a {@code plugin.xml} configuration description. - * Note that a plugin does not necessarily derive from the - * Eclipse {@link org.eclipse.core.runtime.Plugin} class. - *

- *

- * Some plugins are pure extensions without any activator. - * For resource and plugin information lookup, a class can be - * specified which is in the JAR containing the resources and - * plugin information. This lookup procedure also supports - * fat JAR lookups as described in the ReadMe.md. - *

- * @see org.eclipse.core.runtime.RegistryFactory - */ -public class SpotlessEclipsePluginConfig extends BundleConfig { - private final List> extensions; - - /** - * Don't instantiate and call {@link SpotlessEclipseConfig} directly. - * Registered plugins and extensions should only be instantiated once, since - * some still abusing singletons for access. - */ - SpotlessEclipsePluginConfig() { - extensions = new ArrayList<>(); - } - - /** Add an extension plugin, identified by a class of the plugin. */ - public void add(Class extensionClass) { - Objects.requireNonNull(extensionClass, "Plugin extension class must nor be null"); - extensions.add(extensionClass); - } - - /** Add a set of default bundles with their default states */ - public void add(Class... extensionClasses) { - Arrays.asList(extensionClasses).forEach(extensionClass -> add(extensionClass)); - } - - /** Returns the current configuration */ - public List> getExtensions() { - return extensions; - } - - @Override - public void applyDefault() { - add(SpotlessEclipseFramework.DefaultPlugins.createAll()); - } - - @Override - protected BundleActivator create(DefaultPlugins bundle) { - return bundle.create(); - } - - @Override - protected int getDefaultState(DefaultPlugins bundle) { - return Bundle.ACTIVE; - } - -} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipseServiceConfig.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipseServiceConfig.java deleted file mode 100644 index f0b9a97cc4..0000000000 --- a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipseServiceConfig.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.base; - -import static com.diffplug.spotless.extra.eclipse.base.SpotlessEclipseFramework.LINE_DELIMITER; - -import java.util.Map; -import java.util.function.BiFunction; - -import org.eclipse.core.runtime.content.IContentTypeManager; -import org.eclipse.core.runtime.preferences.IPreferencesService; -import org.eclipse.equinox.log.ExtendedLogReaderService; -import org.eclipse.equinox.log.ExtendedLogService; -import org.eclipse.osgi.service.datalocation.Location; -import org.eclipse.osgi.service.debug.DebugOptions; -import org.eclipse.osgi.service.environment.EnvironmentInfo; -import org.osgi.framework.ServiceException; -import org.osgi.service.log.LogLevel; - -import com.diffplug.spotless.extra.eclipse.base.service.*; - -/** - * Configuration/Provision of services which shall be provided by the {@link SpotlessEclipseFramework}. - *

- * The services provide basic functions/configuration to the {@link SpotlessEclipseFramework} bundles use the services. - * Hence the services can be used to customize the behavior of core bundles and plugins configured - * in the {@link SpotlessEclipseCoreConfig} and {@link SpotlessEclipsePluginConfig}. - *

- */ -public interface SpotlessEclipseServiceConfig { - - /** Sets property/preference value available to all bundles, plugins and services. */ - void set(String key, String value); - - /** Sets property/preference values available to all bundles, plugins and services. */ - default void set(Map properties) { - properties.forEach((k, v) -> this.set(k, v)); - } - - /** - * Add custom service to collection. - *

- * Only one service per interface is allowed. - * A service instance implementing multiple interfaces, can be added for each interface. - *

- * Please refer to the default method implementation for examples. - * - * @param interfaceClass Service interface - * @param service Service instance - * @throws ServiceException in case service has already been configured - */ - public void add(Class interfaceClass, S service) throws ServiceException; - - /** - * Spotless formatters should not be configured by environment variables, and - * they shall be OS independent. - * @throws ServiceException in case service has already been configured - */ - default public void hideEnvironment() throws ServiceException { - add(EnvironmentInfo.class, new HiddenEnvironment()); - } - - /** - * Eclipse provides means to lookup the file content type, e.g. by file name extensions. - * This possibility is not required by most Spotless formatters. - * @throws ServiceException in case service has already been configured - */ - default public void ignoreContentType() throws ServiceException { - add(IContentTypeManager.class, new NoContentTypeSpecificHandling()); - } - - /** - * Disable Eclipse internal debugging. - * @throws ServiceException in case service has already been configured - */ - default public void disableDebugging() throws ServiceException { - add(DebugOptions.class, new NoDebugging()); - } - - /** - * Ignore accesses of unsupported preference. - * @throws ServiceException in case service has already been configured - */ - default public void ignoreUnsupportedPreferences() throws ServiceException { - add(IPreferencesService.class, new NoEclipsePreferences()); - } - - /** - * Use temporary locations in case plugins require to store file. - * These files (for example workspace preferences) will be deleted - * as soon as the application terminates. - * @throws ServiceException in case service has already been configured - */ - default public void useTemporaryLocations() throws ServiceException { - add(Location.class, new TemporaryLocation()); - } - - /** - * In case the string which will be formatted does not contain any - * line delimiter (single line), Eclipse falls back to use the - * system property. - * Change the system default to the UNIX line separator as required - * by Spotless. - * @throws ServiceException in case service has already been configured - */ - default public void changeSystemLineSeparator() throws ServiceException { - System.setProperty("line.separator", LINE_DELIMITER); - } - - /** - * Adds Eclipse logging service Slf4J binding. - * @throws ServiceException in case service has already been configured - */ - default public void useSlf4J(String loggerName) { - useSlf4J(loggerName, (s, l) -> s); - } - - /** - * Adds Eclipse logging service Slf4J binding with a message customizer function. - * @throws ServiceException in case service has already been configured - */ - default public void useSlf4J(String loggerName, BiFunction messageCustomizer) throws ServiceException { - SingleSlf4JService slf4jServce = new SingleSlf4JService(loggerName, messageCustomizer); - add(ExtendedLogService.class, slf4jServce); - add(ExtendedLogReaderService.class, slf4jServce); - slf4jServce.debug("Initialized Eclipse logging service."); - } - - /** - * Applies the default configurations. - * @throws ServiceException in case a service has already been configured - */ - default public void applyDefault() throws ServiceException { - hideEnvironment(); - ignoreContentType(); - disableDebugging(); - ignoreUnsupportedPreferences(); - useTemporaryLocations(); - changeSystemLineSeparator(); - } -} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/BundleConfig.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/BundleConfig.java deleted file mode 100644 index 8e4b12c8d0..0000000000 --- a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/BundleConfig.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.base.osgi; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.Objects; - -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleActivator; - -/** A bundle configuration is given by its activator and the desired state */ -public abstract class BundleConfig> { - public static class Entry { - public final BundleActivator activator; - public final int state; - - public Entry(BundleActivator activator, int state) { - Objects.requireNonNull(activator, "activator"); - this.activator = activator; - this.state = state; - } - } - - private final List config; - - protected BundleConfig() { - config = new ArrayList(); - } - - /** - * Activate a bundle with a certain state. A non-active state is used by - * some bundles to allow a slim instantiation (for example in a headless - * Eclipse). - */ - public void add(BundleActivator activator, int state) { - config.add(new Entry(activator, state)); - } - - /** Returns the current configuration */ - public List get() { - return config; - } - - /** Activate a set of bundles with certain states */ - public void add(List config) { - this.config.addAll(config); - } - - /** Activate a bundle in active state, which is the nominal choice */ - public void add(BundleActivator activator) { - add(activator, Bundle.ACTIVE); - } - - /** Activate a set of bundles with in active state */ - public void add(Collection config) { - config.stream().forEach(entry -> add(entry)); - } - - /** Activate a default bundle with its default state */ - public void add(T bundle) { - add(create(bundle), getDefaultState(bundle)); - } - - /** Activate a set of default bundles with their default states */ - @SuppressWarnings("unchecked") - public void add(T... bundles) { - Arrays.asList(bundles).forEach(bundle -> add(bundle)); - } - - /** Activate a default bundle with a custom state */ - public void add(T bundle, int state) { - add(create(bundle), state); - } - - /** Applies the default configurations. */ - public abstract void applyDefault(); - - protected abstract BundleActivator create(T bundle); - - protected abstract int getDefaultState(T bundle); - -} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/BundleController.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/BundleController.java deleted file mode 100644 index 3589bd7082..0000000000 --- a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/BundleController.java +++ /dev/null @@ -1,256 +0,0 @@ -/* - * Copyright 2016-2021 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.base.osgi; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; - -import org.eclipse.core.internal.jobs.JobManager; -import org.eclipse.osgi.internal.location.LocationHelper; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.osgi.framework.BundleException; -import org.osgi.framework.Constants; -import org.osgi.framework.Filter; -import org.osgi.framework.InvalidSyntaxException; -import org.osgi.framework.ServiceReference; -import org.osgi.framework.wiring.FrameworkWiring; - -/** - * OSGi bundle controller allowing a minimal Eclipse platform setup - * by bypassing the Eclipse internal platform. - * - * Bundles are loaded by the same class loader, sharing the same context. - * Services do not provide individual properties, but making use of the framework properties. - * All bundles have a persistent state. The OSGi life-cycle is not supported. - */ -public final class BundleController implements StaticBundleContext { - private static final String ECLIPSE_LAUNCHER_SYMBOLIC_NAME = "org.eclipse.osgi"; - - private final SimpleBundle systemBundle; - private final Map properties; - private final ServiceCollection services; - private final BundleSet bundles; - - @SuppressWarnings("deprecation") - public BundleController() throws BundleException { - //OSGI locks are not required, since this framework does not allow changes after initialization. - System.setProperty(LocationHelper.PROP_OSGI_LOCKING, LocationHelper.LOCKING_NONE); - - this.properties = new HashMap(); - //Don't activate all plugin bundles. Activation is triggered by this controller where needed. - properties.put(org.eclipse.core.internal.runtime.InternalPlatform.PROP_ACTIVATE_PLUGINS, Boolean.toString(false)); - - /* - * Used to set-up an internal member of the Eclipse runtime FindSupport, - * which is used during resources look-up from different version of bundles. - * Since the concept of the Spotless Eclipse framework does not allow multiple versions - * for a bundle, this property is never used. - */ - properties.put(org.eclipse.core.internal.runtime.FindSupport.PROP_NL, ""); - - bundles = new BundleSet(); - systemBundle = new SimpleBundle(this, Bundle.ACTIVE); - bundles.add(systemBundle); - - services = new ServiceCollection(systemBundle, properties); - - //Eclipse core (InternalPlatform) still uses PackageAdmin for looking up bundles - EclipseBundleLookup bundleLookup = new EclipseBundleLookup(systemBundle, bundles); - services.add(org.osgi.service.packageadmin.PackageAdmin.class, bundleLookup); - services.add(FrameworkWiring.class, bundleLookup); - - //Redirect framework activator requests to the org.eclipse.osgi bundle to this instance. - bundles.add(new SimpleBundle(systemBundle, ECLIPSE_LAUNCHER_SYMBOLIC_NAME, Bundle.ACTIVE)); - FrameworkBundleRegistry.initialize(this); - } - - /** - * Stop {@link org.eclipse.core.internal.jobs.JobManager} worker pool - * and clean up resources of Spotless bundles and services. - * - * @implNote The {@link org.osgi.framework.BundleActivator}s - * are not stopped, since they are not completely started. - * For example services are suppressed by {@link StaticBundleContext}. - */ - public void shutdown() { - JobManager.shutdown(); - bundles.getAll().forEach(b -> { - try { - b.stop(); - } catch (IllegalStateException | BundleException e) { - //Stop on best effort basis - } - }); - services.stop(); - } - - public ServiceCollection getServices() { - return services; - } - - /** Adds and starts a new bundle. */ - public void addBundle(int bundleState, BundleActivator activator, Function register) throws BundleException { - BundleContext contextFacade = new BundleControllerContextFacade(this, bundleState, activator); - bundles.add(contextFacade.getBundle()); - BundleException exception = register.apply(contextFacade.getBundle()); - if (null != exception) - throw exception; - try { - activator.start(contextFacade); - } catch (Exception e) { - throw new BundleException(String.format("Failed do start %s.", activator.getClass().getName()), BundleException.ACTIVATOR_ERROR, e); - } - } - - /** Adds new bundel whithout activator (e.g. used for only for extensions) */ - public void addBundle(Class clazzInBundleJar, Function register) throws BundleException { - BundleContext contextFacade = new BundleControllerContextFacade(this, clazzInBundleJar); - bundles.add(contextFacade.getBundle()); - BundleException exception = register.apply(contextFacade.getBundle()); - if (null != exception) - throw exception; - } - - /** Creates a context with an individual state if required. */ - public BundleContext createContext(int state) { - if (state == systemBundle.getState()) { - return this; - } - return new BundleControllerContextFacade(systemBundle, state); - } - - @Override - public String getProperty(String key) { - return properties.get(key); - } - - @Override - public Bundle getBundle() { - return systemBundle; - } - - @Override - public Bundle[] getBundles() { - Collection shallowCopy = bundles.getAll(); - return shallowCopy.toArray(new Bundle[shallowCopy.size()]); - } - - @Override - public Bundle getBundle(long id) { - return bundles.get(id); - } - - @Override - public Bundle getBundle(String location) { - if (Constants.SYSTEM_BUNDLE_LOCATION.equals(location)) { - return systemBundle; - } - return null; - } - - @Override - public ServiceReference[] getAllServiceReferences(String clazz, String filter) throws InvalidSyntaxException { - //Filters are based on class names - String interfaceClassName = (null == clazz) ? filter : clazz; - return services.getReferences(interfaceClassName); - } - - @Override - public S getService(ServiceReference reference) { - return services.getService(reference); - } - - @Override - public Filter createFilter(String filter) throws InvalidSyntaxException { - return services.createFilter(filter); - } - - /** - * Facade providing access to an existing controller for a bundle - *

- * All bundles have unrestricted access to the framework services and properties. - * However, each bundle and its context needs to maintain its individual - * symbolic name for look-up. - *

- */ - private static class BundleControllerContextFacade implements StaticBundleContext { - - private final BundleContext context; - private final Bundle bundle; - - private BundleControllerContextFacade(BundleContext context, int bundleState, BundleActivator activator) throws BundleException { - this.context = context; - bundle = new SimpleBundle(this, bundleState, activator); - } - - private BundleControllerContextFacade(BundleContext context, Class clazzInBundleJar) throws BundleException { - this.context = context; - bundle = new SimpleBundle(this, clazzInBundleJar); - } - - /** Fakes an individual bundle state */ - private BundleControllerContextFacade(SimpleBundle bundle, int bundleState) { - this.context = bundle.getBundleContext(); - this.bundle = new SimpleBundle(bundle, bundleState); - } - - @Override - public String getProperty(String key) { - return context.getProperty(key); - } - - @Override - public Bundle getBundle() { - return bundle; - } - - @Override - public Bundle[] getBundles() { - return context.getBundles(); - } - - @Override - public Bundle getBundle(long id) { - return context.getBundle(id); - } - - @Override - public Bundle getBundle(String location) { - return context.getBundle(location); - } - - @Override - public ServiceReference[] getAllServiceReferences(String clazz, String filter) throws InvalidSyntaxException { - return context.getAllServiceReferences(clazz, filter); - } - - @Override - public S getService(ServiceReference reference) { - return context.getService(reference); - } - - @Override - public Filter createFilter(String filter) throws InvalidSyntaxException { - return context.createFilter(filter); - } - - } - -} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/BundleSet.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/BundleSet.java deleted file mode 100644 index 59e15929fd..0000000000 --- a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/BundleSet.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.base.osgi; - -import java.util.Collection; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleException; - -/** Thread save set of bundles, whereas each bundle has a unique symbolic name and a unique ID. */ -class BundleSet { - private final Map symbolicName2bundle; - private final Map id2bundle; - - BundleSet() { - symbolicName2bundle = new ConcurrentHashMap(); - id2bundle = new ConcurrentHashMap(); - } - - /** Get all bundles in collection */ - Collection getAll() { - return symbolicName2bundle.values(); - } - - /** Get bundle by symbolic name or null if collection does not contain the corresponding bundle. */ - Bundle get(String symbolicName) { - return symbolicName2bundle.get(symbolicName); - } - - /** Get bundle by its ID or null if collection does not contain the corresponding bundle. */ - Bundle get(long id) { - return id2bundle.get(id); - } - - /** Add bundle to collection. - * @throws BundleException */ - void add(Bundle bundle) throws BundleException { - Bundle existingBundle = symbolicName2bundle.put(bundle.getSymbolicName(), bundle); - if (null != existingBundle) { - throw new BundleException( - String.format("Bundle '%s' (ID: %d) is already part of collection with ID %d.", - bundle.getSymbolicName(), bundle.getBundleId(), existingBundle.getBundleId()), - BundleException.DUPLICATE_BUNDLE_ERROR); - } - Bundle bundleWithSameID = id2bundle.put(bundle.getBundleId(), bundle); - if (null != bundleWithSameID) { - throw new BundleException( - String.format("Bundle ID '%d' for '%s' is already used by '%s'.", - bundle.getBundleId(), - bundle.getSymbolicName(), - bundleWithSameID.getSymbolicName()), - BundleException.DUPLICATE_BUNDLE_ERROR); - } - } - -} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/EclipseBundleLookup.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/EclipseBundleLookup.java deleted file mode 100644 index 0ec091a58b..0000000000 --- a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/EclipseBundleLookup.java +++ /dev/null @@ -1,182 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.base.osgi; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import org.eclipse.osgi.internal.framework.FilterImpl; -import org.osgi.framework.Bundle; -import org.osgi.framework.FrameworkListener; -import org.osgi.framework.InvalidSyntaxException; -import org.osgi.framework.namespace.IdentityNamespace; -import org.osgi.framework.wiring.BundleCapability; -import org.osgi.framework.wiring.FrameworkWiring; -import org.osgi.resource.Namespace; -import org.osgi.resource.Requirement; -import org.osgi.service.packageadmin.ExportedPackage; -import org.osgi.service.packageadmin.PackageAdmin; -import org.osgi.service.packageadmin.RequiredBundle; - -/** - * - * {@link PackageAdmin} and {@link FrameworkWiring} service for bundle look-up. - *

- * The wiring information will always claim that all required bundles are present, since - * Spotlss does on purpose not provide all dependencies requested by plugins, since - * only small parts of the plugins are used. - * Removal and addition requests for bundles will always claim that there is nothing to do. - *

- * PackageAdmin interface is deprecated, but might still be used by bundles. - * It is kept for backward compatibility until removed from Eclipse. - */ -@SuppressWarnings("deprecation") -class EclipseBundleLookup implements FrameworkWiring, PackageAdmin { - - private static final Set OSGI_KEYS_FOR_SYMBOLIC_NAMES = Collections.unmodifiableSet(Stream.of(IdentityNamespace.IDENTITY_NAMESPACE, IdentityNamespace.TYPE_BUNDLE).collect(Collectors.toSet())); - private final Bundle systemBundle; - private final BundleSet bundles; - - EclipseBundleLookup(final Bundle systemBundle, final BundleSet bundles) { - this.systemBundle = systemBundle; - this.bundles = bundles; - } - - @Override - @Deprecated - public ExportedPackage[] getExportedPackages(Bundle bundle) { - return null; - } - - @Override - @Deprecated - public ExportedPackage[] getExportedPackages(String name) { - return null; - } - - @Override - @Deprecated - public ExportedPackage getExportedPackage(String name) { - return null; - } - - @Override - @Deprecated - public void refreshPackages(Bundle[] bundles) {} - - @Override - public boolean resolveBundles(Bundle[] bundles) { - return true; //All required bundles can be considered available (to be confirmed by UT) - } - - @Override - public RequiredBundle[] getRequiredBundles(String symbolicName) { - return null; // No unresolved required bundles exist - } - - @Override - public Bundle[] getBundles(String symbolicName, String versionRange) { - //Bundles with different versions cannot be supported due to the usage of same class-loader - Bundle bundle = bundles.get(symbolicName); - return (null == bundle) ? null : new Bundle[]{bundle}; - } - - @Override - public Bundle[] getFragments(Bundle bundle) { - return null; //No fragments - } - - @Override - public Bundle[] getHosts(Bundle bundle) { - return null; //No fragments - } - - @Override - public Bundle getBundle(@SuppressWarnings("rawtypes") Class clazz) { - return bundles.get(clazz.getName()); - } - - @Override - public int getBundleType(Bundle bundle) { - return 0; //No fragments - } - - @Override - public Bundle getBundle() { - return systemBundle; - } - - @Override - public void refreshBundles(Collection bundles, FrameworkListener... listeners) { - //Spotless bundles cannot be loaded dynamically - } - - @Override - public boolean resolveBundles(Collection bundles) { - return true; - } - - @Override - public Collection getRemovalPendingBundles() { - return Collections.emptyList(); //Nothing to remove - } - - @Override - public Collection getDependencyClosure(Collection bundles) { - return Collections.emptyList(); //No dependencies - } - - @Override - public Collection findProviders(Requirement requirement) { - // requirement must not be null (according to interface description)! - String filterSpec = requirement.getDirectives().get(Namespace.REQUIREMENT_FILTER_DIRECTIVE); - if (null == filterSpec) { - throw new IllegalArgumentException("Requirement filter diretive '" + Namespace.REQUIREMENT_FILTER_DIRECTIVE + "' not found."); - } - try { - FilterImpl requirementFilter = FilterImpl.newInstance(filterSpec); - Collection requiredSymbolicNames = getRequestedSymbolicNames(requirementFilter); - Collection capabilities = new ArrayList(requiredSymbolicNames.size()); - requiredSymbolicNames.forEach(symbolicName -> { - Bundle bundle = bundles.get(symbolicName); - if (bundle != null) { - capabilities.add(new SimpleBundleCapability(bundle)); - } - }); - return capabilities; - } catch (InvalidSyntaxException e) { - throw new IllegalArgumentException("Filter specifiation invalid:\n" + filterSpec, e); - } - } - - /** - * Simplified parser irgnoreing the version. - * Parser is incomplete since it ignores the filter operation. - * It basicall implements the bespoke way Eclipse maps its old style bundle handling to OSGI. - */ - private static Collection getRequestedSymbolicNames(FilterImpl filter) { - List symbolicNames = filter.getStandardOSGiAttributes().entrySet().stream().filter(entry -> OSGI_KEYS_FOR_SYMBOLIC_NAMES.contains(entry.getKey())).map(entry -> entry.getValue()).collect(Collectors.toList()); - filter.getChildren().forEach(childFilter -> { - symbolicNames.addAll(getRequestedSymbolicNames(childFilter)); - }); - return symbolicNames; - } -} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/FrameworkBundleRegistry.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/FrameworkBundleRegistry.java deleted file mode 100644 index 18d5c4bed4..0000000000 --- a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/FrameworkBundleRegistry.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2016-2020 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.base.osgi; - -import java.util.Optional; - -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleException; -import org.osgi.framework.connect.FrameworkUtilHelper; - -/** - * Framework bundle registry service for bundles which do not come with an activator. - * - * Instead of returning the system bundle, a new bundle is created - * to provide an individual resource accessor, so that - * the correct JAR is searched for relative resource paths. - * Note that this can also be used to override - * original resources by providing a resource in the - * corresponding fat JAR location. - */ -public class FrameworkBundleRegistry implements FrameworkUtilHelper { - static BundleController INSTANCE = null; - - static void initialize(BundleController bundleController) { - if (INSTANCE != null) { - throw new RuntimeException(FrameworkBundleRegistry.class.getName() + " already initialized."); - } - INSTANCE = bundleController; - } - - @Override - public Optional getBundle(Class classFromBundle) { - try { - return Optional.of(new SimpleBundle(INSTANCE, classFromBundle)); - } catch (BundleException e) { - //If the class cannot be associated to a JAR or fat JAR resource location, just retun null - } - return Optional.empty(); - } -} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/ResourceAccessor.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/ResourceAccessor.java deleted file mode 100644 index b75a2835ac..0000000000 --- a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/ResourceAccessor.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright 2016-2021 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.base.osgi; - -import java.io.File; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.util.Enumeration; -import java.util.jar.JarFile; -import java.util.jar.Manifest; - -import org.eclipse.osgi.internal.debug.Debug; -import org.eclipse.osgi.storage.bundlefile.BundleEntry; -import org.eclipse.osgi.storage.bundlefile.BundleFile; -import org.eclipse.osgi.storage.bundlefile.DirBundleFile; -import org.eclipse.osgi.storage.bundlefile.ZipBundleFile; -import org.eclipse.osgi.util.ManifestElement; -import org.osgi.framework.BundleException; -import org.osgi.framework.Constants; - -import com.diffplug.spotless.extra.eclipse.base.service.NoDebugging; - -/** - * Helper to access resources. - *

- * Spotless Eclipse formatters using in many cases fat JARs, compressing multiple - * bundles within one JAR. Their resources can get overridden in a fat JAR. - * Hence they provided under the bundle activators path name. - *

- *

- * The resource overriding prevention is required in case the Spotless - * Eclipse formatters integrate third party JARs, not available via M2. - * Additionally it can be used in case existing third party Eclipse plugins - * are mocked by Spotless, requiring the provision of multiple customized - * plugin information (META-INF, plugin.xml) within one JAR. - *

- */ -class ResourceAccessor { - private static final Debug NO_DEBUGGING = new Debug(new NoDebugging()); - private final String fatJarResourcePath; - private final BundleFile bundleFile; - - /** Resources are located in the SpotlessFramework JAR */ - ResourceAccessor() throws BundleException { - this(ResourceAccessor.class); - } - - /** Resources are located in the JAR of the given class - * @throws BundleException */ - ResourceAccessor(Class clazz) throws BundleException { - String bundleObjPath = clazz.getName(); - fatJarResourcePath = bundleObjPath.substring(0, bundleObjPath.lastIndexOf('.')); - try { - bundleFile = getBundlFile(clazz); - } catch (BundleException e) { - throw new BundleException(String.format("Failed to locate resources for bundle '%s'.", clazz.getName()), e); - } - } - - private static BundleFile getBundlFile(Class clazz) throws BundleException { - URI objUri = getBundleUri(clazz); - File jarOrDirectory = new File(objUri.getPath()); - if (!(jarOrDirectory.exists() && jarOrDirectory.canRead())) { - throw new BundleException(String.format("Path '%s' for '%s' is not accessible exist on local file system.", objUri, clazz.getName()), BundleException.READ_ERROR); - } - try { - return jarOrDirectory.isDirectory() ? new DirBundleFile(jarOrDirectory, false) : new ZipBundleFile(jarOrDirectory, null, null, NO_DEBUGGING, false); - } catch (IOException e) { - throw new BundleException(String.format("Cannot access bundle at '%s'.", jarOrDirectory), BundleException.READ_ERROR, e); - } - } - - private static URI getBundleUri(Class clazz) throws BundleException { - try { - URL objUrl = clazz.getProtectionDomain().getCodeSource().getLocation(); - return objUrl.toURI(); - } catch (NullPointerException e) { - //No bunlde should be used for RT classes lookup. See also org.eclipse.core.runtime.PerformanceStats. - throw new BundleException(String.format("No code source can be located for class '%s'. Class is probably not within a bundle, but part of the RT.", clazz.getName()), BundleException.READ_ERROR, e); - } catch (SecurityException e) { - throw new BundleException(String.format("Access to class '%s' is denied.", clazz.getName()), BundleException.READ_ERROR, e); - } catch (URISyntaxException e) { - throw new BundleException(String.format("Path for '%s' is invalid.", clazz.getName()), BundleException.READ_ERROR, e); - } - } - - /** Get the manifest name from the resources. */ - String getManifestName() throws BundleException { - URL manifestUrl = getEntry(JarFile.MANIFEST_NAME); - if (null != manifestUrl) { - try { - Manifest manifest = new Manifest(manifestUrl.openStream()); - String headerValue = manifest.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME); - if (null == headerValue) { - throw new BundleException(String.format("Symbolic values not found in '%s'.", manifestUrl), BundleException.MANIFEST_ERROR); - } - ManifestElement[] elements = ManifestElement.parseHeader(Constants.BUNDLE_SYMBOLICNAME, headerValue); - if (null == elements) { - throw new BundleException(String.format("Symbolic name not found '%s'. Value is '%s'.", manifestUrl, headerValue), BundleException.MANIFEST_ERROR); - } - //The parser already checked that at least one value exists - return elements[0].getValueComponents()[0]; - - } catch (IOException e) { - throw new BundleException(String.format("Failed to parse Manifest '%s' in '%s'.", manifestUrl, bundleFile.toString()), BundleException.MANIFEST_ERROR, e); - } - } - throw new BundleException(String.format("'%s' in '%s' not found. Tried also fat JAR location '%s'.", JarFile.MANIFEST_NAME, bundleFile.toString(), fatJarResourcePath), BundleException.MANIFEST_ERROR); - } - - /** Get resource URL for relative path, or null if the path is not present */ - URL getEntry(String path) { - BundleEntry entry = bundleFile.getEntry(getFatJarPath(path)); - if (null == entry) { - entry = bundleFile.getEntry(path); - } - return null == entry ? null : entry.getLocalURL(); - } - - /** - * Enumeration of Strings that indicate the paths found or null if the path does not exist. - */ - Enumeration getEntries(String path) { - Enumeration entries = bundleFile.getEntryPaths(getFatJarPath(path)); - if (null == entries) { - entries = bundleFile.getEntryPaths(path); - } - return entries; - } - - private String getFatJarPath(String path) { - return fatJarResourcePath + "/" + path; - } - -} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/ServiceCollection.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/ServiceCollection.java deleted file mode 100644 index 2ea67f712f..0000000000 --- a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/ServiceCollection.java +++ /dev/null @@ -1,229 +0,0 @@ -/* - * Copyright 2016-2021 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.base.osgi; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Dictionary; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -import org.eclipse.osgi.internal.framework.DTOBuilder; -import org.osgi.framework.Bundle; -import org.osgi.framework.Filter; -import org.osgi.framework.ServiceException; -import org.osgi.framework.ServiceReference; -import org.osgi.framework.dto.ServiceReferenceDTO; - -import com.diffplug.spotless.extra.eclipse.base.SpotlessEclipseServiceConfig; - -/** - * Collection of services. - * Eclipse service are not expected to hold any resources. Spotless services - * can implement AutoCloseable in case a resource release is required on shutdown. - * - * Note that the collection access is not thread save, since it is expected - * that the collection is completed before starting any bundles. - */ -public class ServiceCollection implements SpotlessEclipseServiceConfig { - private final Map> className2Service; - private final List servicesWithResources; - private final Bundle systemBundle; - private final Map properties; - - /** - * Collection of services - * @param systemBundle All services will belong to the system bundles - * @param All services share the same properties - */ - ServiceCollection(Bundle systemBundle, Map properties) { - className2Service = new HashMap>(); - servicesWithResources = new ArrayList<>(); - this.systemBundle = systemBundle; - this.properties = properties; - } - - void stop() { - servicesWithResources.stream().forEach(s -> { - try { - s.close(); - } catch (Exception e) { - //Stop on best effort basis - } - }); - } - - @Override - public void set(String key, String value) { - properties.put(key, value); - } - - @Override - public void add(Class interfaceClass, S service) throws ServiceException { - String className = interfaceClass.getName(); - if (null != className2Service.put(interfaceClass.getName(), new FrameworkServiceReference(className, service))) { - throw new ServiceException( - String.format("Service '%s' is already registered.", interfaceClass.getName()), ServiceException.FACTORY_ERROR); - } - if (service instanceof AutoCloseable) { - servicesWithResources.add((AutoCloseable) service); - } - } - - /** Creates filter object suitable to lookup service by its interface name. */ - Filter createFilter(String filterDescr) { - Optional serviceClassName = className2Service.keySet().stream().filter(serviceClazzName -> filterDescr.contains(serviceClazzName)).findFirst(); - return new ClassNameBasedFilter(serviceClassName); - } - - /** - * Get reference matching interface class name or all references - * @param interfaceClassName Class name filter. All references are returned in case filter is null - * @return Matching or all interfaces. If no interface is matching the filter, null is returned. - */ - ServiceReference[] getReferences(String interfaceClassName) { - if (null == interfaceClassName) { - Collection> allServices = className2Service.values(); - return allServices.toArray(new ServiceReference[allServices.size()]); - } - ServiceReference singleService = className2Service.get(interfaceClassName); - return (null == singleService) ? null : new ServiceReference[]{singleService}; - } - - /** - * Return service for reference if it belongs to the system bundle. - * @param reference Service reference - * @return null, if service does not belong to the system bundle - */ - S getService(ServiceReference reference) { - if (systemBundle == reference.getBundle()) { - return ((FrameworkServiceReference) reference).getService(); - } - return null; - } - - /** References to static services (not modifiable at run-time */ - private class FrameworkServiceReference implements ServiceReference { - - private final String className; - private final S service; - - private FrameworkServiceReference(String className, S service) { - this.className = className; - this.service = service; - } - - private S getService() { - return service; - } - - @Override - public java.lang.Object getProperty(String key) { - return properties.get(key); - } - - @Override - public String[] getPropertyKeys() { - return properties.keySet().toArray(new String[properties.size()]); - } - - @Override - public Bundle getBundle() { - return systemBundle; - } - - @Override - public Bundle[] getUsingBundles() { - return new Bundle[]{systemBundle}; - } - - @Override - public boolean isAssignableTo(Bundle bundle, String className) { - // Since only one class loader is used, same class come from the same package - return this.className.equals(className); - } - - @Override - @edu.umd.cs.findbugs.annotations.SuppressFBWarnings(value = "EQ_COMPARETO_USE_OBJECT_EQUALS") - public int compareTo(Object reference) { - return (this == reference) ? 0 : 1; - } - - @Override - public Dictionary getProperties() { - return new Hashtable(properties); - } - - @SuppressWarnings("unchecked") - @Override - public A adapt(Class type) { - if (ServiceReferenceDTO.class.equals(type)) { - return (A) DTOBuilder.newServiceReferenceDTO(this); - } - return null; - } - - } - - /** - * Class name based service filter - *

- * Dictionary and capability look-ups are not supported and marked as deprecated. - */ - private class ClassNameBasedFilter implements Filter { - - private final static String NO_MATCH_CLASS_NAME = ""; - - private final String className; - - private ClassNameBasedFilter(Optional className) { - this.className = className.orElse(NO_MATCH_CLASS_NAME); - } - - @Override - public boolean match(ServiceReference reference) { - return reference.isAssignableTo(systemBundle, className); - } - - @Override - @Deprecated - public boolean match(Dictionary dictionary) { - throw new UnsupportedOperationException("Dictionary based service look-up is not supported."); - } - - @Override - @Deprecated - public boolean matchCase(Dictionary dictionary) { - throw new UnsupportedOperationException("Dictionary based service look-up is not supported."); - } - - @Override - @Deprecated - public boolean matches(Map map) { - throw new UnsupportedOperationException("Capability based service look-up is not supported."); - } - - @Override - public String toString() { - return className; - } - - } - -} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/SimpleBundle.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/SimpleBundle.java deleted file mode 100644 index bdf8888b30..0000000000 --- a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/SimpleBundle.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.base.osgi; - -import java.net.URL; -import java.util.Enumeration; - -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.osgi.framework.BundleException; -import org.osgi.framework.InvalidSyntaxException; -import org.osgi.framework.ServiceReference; - -/** Fixed state simple bundle. */ -class SimpleBundle implements StaticBundle, TemporaryBundle { - private final String name; - private final int state; - private final BundleContext context; - private final int id; - private final ResourceAccessor resources; - - /** System bundle corresponding to the SpotlessFramework JARs manifest */ - SimpleBundle(BundleContext context, int state) throws BundleException { - this(context, state, new ResourceAccessor()); - } - - /** System bundle for a dedicated bundle activator */ - SimpleBundle(BundleContext context, int state, BundleActivator activator) throws BundleException { - this(context, state, new ResourceAccessor(activator.getClass())); - } - - /** System bundle providing only extensions and therefore does not require an activator */ - SimpleBundle(BundleContext context, Class clazzInBundleJar) throws BundleException { - //These bundles are always active (means that resources have been resolved) - this(context, Bundle.ACTIVE, new ResourceAccessor(clazzInBundleJar)); - } - - /** Internal constructor */ - private SimpleBundle(BundleContext context, int state, ResourceAccessor resources) throws BundleException { - this.state = state; - this.context = context; - this.resources = resources; - id = context.getBundles().length; - name = resources.getManifestName(); - } - - /** Additional bundle with a different symbolic name and state */ - SimpleBundle(SimpleBundle master, String name, int state) { - this.name = name; - this.state = state; - context = master.context; - resources = master.resources; - id = context.getBundles().length; - } - - /** Bundle clone with a different state */ - SimpleBundle(SimpleBundle master, int state) { - this.state = state; - context = master.context; - resources = master.resources; - id = master.id; - name = master.name; - } - - @Override - public A adapt(Class type) { - /* - * The adaptation is currently used by the InternalPlugin to get the framework wiring - * implementation from the system bundle. - * The original purpose to provide more specialized access to the Bundle object, - * seems not be used by Eclipse at all. - * Hence the call is mapped to old-style Eclipse services. - */ - try { - - ServiceReference[] references = context.getAllServiceReferences(type.getName(), ""); - if ((null != references) && (0 != references.length)) { - if (1 != references.length) { - throw new IllegalArgumentException("Multiple services found for " + type.getName()); //In Spotless services should always be unique - } - Object obj = context.getService(references[0]); - try { - return type.cast(obj); - } catch (ClassCastException e) { - throw new IllegalArgumentException("Received unexpected class for reference filter " + type.getName(), e); - } - } - return null; - } catch (InvalidSyntaxException e) { - throw new IllegalArgumentException("Unexpected syntax exception", e); //Should never be thrown by Spotless bundle controller - } - } - - @Override - public int getState() { - return state; - } - - @Override - public long getBundleId() { - return id; - } - - @Override - public ServiceReference[] getRegisteredServices() { - try { - return context.getAllServiceReferences(null, null); - } catch (InvalidSyntaxException e) { - throw new RuntimeException(e); //Filter 'null' is valid for 'select all'. - } - } - - @Override - public String getSymbolicName() { - return name; - } - - @Override - public BundleContext getBundleContext() { - return context; - } - - @Override - public Enumeration getEntryPaths(String path) { - return resources.getEntries(path); - } - - @Override - public URL getEntry(String path) { - return resources.getEntry(path); - } - -} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/SimpleBundleCapability.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/SimpleBundleCapability.java deleted file mode 100644 index 66f331807d..0000000000 --- a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/SimpleBundleCapability.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.base.osgi; - -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import org.osgi.framework.Bundle; -import org.osgi.framework.Version; -import org.osgi.framework.wiring.BundleCapability; -import org.osgi.framework.wiring.BundleRequirement; -import org.osgi.framework.wiring.BundleRevision; -import org.osgi.framework.wiring.BundleWiring; -import org.osgi.resource.Capability; -import org.osgi.resource.Requirement; - -/** - * Simplified bundle capability ignoring internal wiring and versions - *

- * Since multiple versions/implementations of bundles for the same - * capability is not supported a split of bundle capability and revision is not required. - */ -class SimpleBundleCapability implements BundleCapability, BundleRevision { - private final Bundle bundle; - - SimpleBundleCapability(Bundle bundle) { - this.bundle = bundle; - } - - @Override - public BundleRevision getRevision() { - return this; - } - - @Override - public String getNamespace() { - return this.getClass().getName(); //All bundles live in th same namespace - } - - @Override - public Map getDirectives() { - return Collections.emptyMap(); - } - - @Override - public Map getAttributes() { - return Collections.emptyMap(); - } - - @Override - public BundleRevision getResource() { - return this; - } - - @Override - public Bundle getBundle() { - return bundle; - } - - @Override - public String getSymbolicName() { - return bundle.getSymbolicName(); - } - - @Override - public Version getVersion() { - return bundle.getVersion(); - } - - @Override - public List getDeclaredCapabilities(String namespace) { - return Collections.emptyList(); - } - - @Override - public List getDeclaredRequirements(String namespace) { - return Collections.emptyList(); - } - - @Override - public int getTypes() { - return 0; //It does not matter whether this bunddle is a fragment of not since all bundles are initially provided - } - - @Override - public BundleWiring getWiring() { - return null; //No wiring information - } - - @Override - public List getCapabilities(String namespace) { - return Collections.emptyList(); - } - - @Override - public List getRequirements(String namespace) { - return Collections.emptyList(); - } - -} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/StaticBundle.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/StaticBundle.java deleted file mode 100644 index 282804a332..0000000000 --- a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/StaticBundle.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.base.osgi; - -import java.io.InputStream; - -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleException; -import org.osgi.framework.ServiceReference; - -/** - * Unmodifiable bundle with a fixed life-cycle. - *

- * All state related modifications are ignored. - * Installation related methods (update/uninstall) are unsupported. - * Unsupported methods are marked as deprecated and causing an exception. - */ -public interface StaticBundle extends Bundle { - - @Override - default public void start(int options) throws BundleException {} - - @Override - default public void start() throws BundleException {} - - @Override - default public void stop(int options) throws BundleException {} - - @Override - default public void stop() throws BundleException {} - - @Override - @Deprecated - default public void update(InputStream input) throws BundleException { - update(); - } - - @Override - @Deprecated - default public void update() throws BundleException { - throw new UnsupportedOperationException("Bundle modifications are not supported."); - } - - @Override - @Deprecated - default public void uninstall() throws BundleException { - throw new UnsupportedOperationException("Bundles cannot be uninstalled."); - } - - @Override - default public long getLastModified() { - return 0; - } - - @Override - @Deprecated - default public String getLocation() { - throw new UnsupportedOperationException("Bundle lookup by location only required for installation/update."); - } - - @Override - default public ServiceReference[] getServicesInUse() { - return getRegisteredServices(); //There is no distinction between available services and services in use. - } - -} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/StaticBundleContext.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/StaticBundleContext.java deleted file mode 100644 index 040ef98444..0000000000 --- a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/StaticBundleContext.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.base.osgi; - -import java.io.File; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Dictionary; -import java.util.Objects; -import java.util.stream.Collectors; - -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.BundleException; -import org.osgi.framework.BundleListener; -import org.osgi.framework.FrameworkListener; -import org.osgi.framework.InvalidSyntaxException; -import org.osgi.framework.ServiceFactory; -import org.osgi.framework.ServiceListener; -import org.osgi.framework.ServiceObjects; -import org.osgi.framework.ServiceReference; -import org.osgi.framework.ServiceRegistration; - -/** - * Restriction of the {@link BundleContext} interface rejecting run-time provision of bundles. - * Services provided at run-time are ignored. - *

- * Multiple service instances per class are not supported, hence the services can be filtered by class name. - * Unsupported methods are marked as deprecated an causing an exception. - * Registration and removal of bundle/service listeners are ignored, since a run-time - * provision of bundles or services is not supported. - */ -interface StaticBundleContext extends BundleContext { - - @Override - @Deprecated - default public Bundle installBundle(String location, InputStream input) throws BundleException { - throw new UnsupportedOperationException("Run-time installation of bundles is not supported."); - } - - @Override - @Deprecated - default public Bundle installBundle(String location) throws BundleException { - throw new UnsupportedOperationException("Run-time installation of bundles is not supported."); - } - - @Override - default public void addServiceListener(ServiceListener listener, String filter) throws InvalidSyntaxException {} - - @Override - default public void addServiceListener(ServiceListener listener) {} - - @Override - default public void removeServiceListener(ServiceListener listener) {} - - @Override - default public void addBundleListener(BundleListener listener) {} - - @Override - default public void removeBundleListener(BundleListener listener) {} - - @Override - default public void addFrameworkListener(FrameworkListener listener) {} - - @Override - default public void removeFrameworkListener(FrameworkListener listener) {} - - @Override - @Deprecated - default public ServiceRegistration registerService(String[] clazzes, Object service, Dictionary properties) { - throw new UnsupportedOperationException("Run-time provision of services is not supported."); - } - - @Override - @Deprecated - default public ServiceRegistration registerService(String clazz, Object service, Dictionary properties) { - return null; //Ignore additional services - } - - @Deprecated - @Override - default public ServiceRegistration registerService(Class clazz, S service, Dictionary properties) { - return null; //Ignore additional services - } - - @Override - @Deprecated - default public ServiceRegistration registerService(Class clazz, ServiceFactory factory, Dictionary properties) { - return null; //Ignore additional services - } - - @SuppressWarnings("unchecked") - @Override - default public ServiceReference getServiceReference(Class clazz) { - Objects.requireNonNull(clazz, "The class under whose name the service was registered must not be null."); - return (ServiceReference) getServiceReference(clazz.getName()); - } - - @Override - default public ServiceReference getServiceReference(String clazz) { - Objects.requireNonNull(clazz, "The class under whose name the service was registered must not be null."); - ServiceReference[] references; - try { - references = getServiceReferences(clazz, null); - } catch (InvalidSyntaxException e) { - throw new RuntimeException(e); //null is always valid - } - return (null == references) ? null : references[0]; - } - - @Override - default public ServiceReference[] getServiceReferences(String clazz, String filter) throws InvalidSyntaxException { - return getAllServiceReferences(clazz, filter); //Services are always considered compatible - } - - @Override - default public ServiceReference[] getAllServiceReferences(String clazz, String filter) throws InvalidSyntaxException { - //Filters are based on class names - ServiceReference reference = (null == clazz) ? getServiceReference(filter) : getServiceReference(clazz); - return (reference == null) ? null : new ServiceReference[]{reference}; - } - - @SuppressWarnings("unchecked") - @Override - default public Collection> getServiceReferences(Class clazz, String filter) throws InvalidSyntaxException { - ServiceReference[] references = getServiceReferences(clazz.getName(), filter); - Collection> result = new ArrayList>(0); - if (null != references) { - result = Arrays.stream(references).map(r -> (ServiceReference) r).collect(Collectors.toList()); - } - return result; - } - - @Override - default public boolean ungetService(ServiceReference reference) { - return true; //Services are persistent and never unregistered - } - - @Override - @Deprecated - default public ServiceObjects getServiceObjects(ServiceReference reference) { - throw new UnsupportedOperationException("Service specific objects are not supported."); - } - - @Override - @Deprecated - default public File getDataFile(String filename) { - throw new UnsupportedOperationException("Persistent data storage provision is handled by the Location service."); - } - -} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/TemporaryBundle.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/TemporaryBundle.java deleted file mode 100644 index 24cfadc8c2..0000000000 --- a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/TemporaryBundle.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.base.osgi; - -import java.io.File; -import java.io.IOException; -import java.net.URL; -import java.security.cert.X509Certificate; -import java.util.Dictionary; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.osgi.framework.Bundle; -import org.osgi.framework.Version; - -/** - * Temporary bundle loaded by common class loader and added temporarily. - * It shall not be recognized as a Eclipse plugin (providing plugin.xml) - * but as a mere OSGI bundle. - *

- * META data look-ups are not supported (only required for Eclipse plugins). - * Entry look-up in the bundle space (findEntries) is not supported. - * Installation related methods (update/uninstall) are not supported. - * Unsupported methods are marked as deprecated and causing an exception. - */ -public interface TemporaryBundle extends Bundle { - - @Override - default public Version getVersion() { - return Version.emptyVersion; //Cannot support multiple version using single class loader. - } - - @Override - default public int compareTo(Bundle o) { - //Symbolic name is sufficient to distinguish bundles - return getSymbolicName().compareTo(o.getSymbolicName()); - } - - @Override - default public A adapt(Class type) { - return null; //Adaptation is not successful - } - - @Override - @Deprecated - default public Dictionary getHeaders() { - throw new UnsupportedOperationException("Bundle META information is not available."); - } - - @Override - @Deprecated - default public Dictionary getHeaders(String locale) { - return getHeaders(); - } - - @Override - default public URL getResource(String name) { - return getClass().getClassLoader().getResource(name); - } - - @Override - default public Enumeration getResources(String name) throws IOException { - return getClass().getClassLoader().getResources(name); - } - - @Override - @Deprecated - default public Enumeration findEntries(String path, String filePattern, boolean recurse) { - return null; //Local JAR look-up are not supported per default - } - - @Override - default public Class loadClass(String name) throws ClassNotFoundException { - return getClass().getClassLoader().loadClass(name); - } - - @Override - default public boolean hasPermission(Object permission) { - return true; //Dedicated permissions are not supported - } - - @Override - default public Map> getSignerCertificates(int signersType) { - return new HashMap>(0); //Bundle is not signed - } - - @Override - default public File getDataFile(String filename) { - return null; //No file system support for persistent files - } - -} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/package-info.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/package-info.java deleted file mode 100644 index da74c0471e..0000000000 --- a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/osgi/package-info.java +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** Simplified OSGIi implementation bypassing Equinox module layer. */ -package com.diffplug.spotless.extra.eclipse.base.osgi; diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/package-info.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/package-info.java deleted file mode 100644 index b82e4d40ca..0000000000 --- a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Common Spotless Eclipse Equinox setup classes. - * Please refer to the {@code eclipse-base} {@code README.md} for - * usage instructions. - */ -@ParametersAreNonnullByDefault -package com.diffplug.spotless.extra.eclipse.base; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/runtime/PluginRegistrar.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/runtime/PluginRegistrar.java deleted file mode 100644 index cdee9893dc..0000000000 --- a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/runtime/PluginRegistrar.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.base.runtime; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.PropertyResourceBundle; -import java.util.ResourceBundle; - -import org.eclipse.core.internal.registry.ExtensionRegistry; -import org.eclipse.core.runtime.IContributor; -import org.eclipse.core.runtime.IExtensionRegistry; -import org.eclipse.core.runtime.RegistryFactory; -import org.eclipse.core.runtime.spi.RegistryContributor; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleException; - -/** Registers Eclipse plugins at runtime based on a loaded bundle. - *

- * Note that the functionality provided by this class uses incubation features of the Eclipse core. - */ -public class PluginRegistrar { - private static final String PLUGIN_XML = "plugin.xml"; - private static final String PLUGIN_PROPERTIES = "plugin.properties"; - - public static BundleException register(Bundle bundle) { - PluginRegistrar registrar = new PluginRegistrar(bundle); - try { - registrar.register(); - } catch (BundleException e) { - return e; - } - return null; - } - - private final Bundle bundle; - - private PluginRegistrar(Bundle bundle) { - this.bundle = bundle; - } - - private void register() throws BundleException { - IExtensionRegistry reg = RegistryFactory.getRegistry(); - Object registryUser = ((ExtensionRegistry) reg).getTemporaryUserToken(); - if (!reg.addContribution(getStreamForEntry(PLUGIN_XML), createContributor(), false, null, getPluginProperties(), registryUser)) { - throw new BundleException("Could not add plugin: " + bundle.getSymbolicName(), BundleException.REJECTED_BY_HOOK); - } - } - - private IContributor createContributor() { - return new RegistryContributor( - Long.toString(bundle.getBundleId()), - bundle.getSymbolicName(), - // Local host - null, - null); - } - - private ResourceBundle getPluginProperties() throws BundleException { - //Some plugins, like the org.codehaus.groovy.eclipse.core, do not provide a property file. - InputStream is = entryExists(PLUGIN_PROPERTIES) ? getStreamForEntry(PLUGIN_PROPERTIES) : new ByteArrayInputStream(new byte[0]); - try { - return new PropertyResourceBundle(is); - } catch (IOException e) { - throw new BundleException(String.format("Bund resource '%s' is not encoded with ISO-8859-1.", PLUGIN_PROPERTIES), BundleException.MANIFEST_ERROR, e); - } - } - - private InputStream getStreamForEntry(String path) throws BundleException { - try { - return getEntry(path).openStream(); - } catch (IOException e) { - throw new BundleException(String.format("Cannot access mandatory resource '%s'.", path), BundleException.MANIFEST_ERROR, e); - } - } - - private URL getEntry(String path) throws BundleException { - URL url = bundle.getEntry(path); - if (null == url) { - throw new BundleException(String.format("Cannot find mandatory resource '%s'.", path), BundleException.MANIFEST_ERROR); - } - return url; - } - - private boolean entryExists(String path) { - return null != bundle.getEntry(path); - } -} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/runtime/package-info.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/runtime/package-info.java deleted file mode 100644 index 5ed08616b9..0000000000 --- a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/runtime/package-info.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Eclipse Core Runtime adapters allowing runtime modifications which normally requires an Eclipse restart. - */ -package com.diffplug.spotless.extra.eclipse.base.runtime; diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/HiddenEnvironment.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/HiddenEnvironment.java deleted file mode 100644 index 8c9c1a6c91..0000000000 --- a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/HiddenEnvironment.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.base.service; - -import java.util.Locale; - -import org.eclipse.osgi.service.environment.Constants; -import org.eclipse.osgi.service.environment.EnvironmentInfo; - -/** Empty default Eclipse environment. No system information is accessible. */ -public class HiddenEnvironment implements EnvironmentInfo { - - @Override - public String[] getCommandLineArgs() { - return new String[0]; - } - - @Override - public String[] getFrameworkArgs() { - return new String[0]; - } - - @Override - public String[] getNonFrameworkArgs() { - return new String[0]; - } - - @Override - public String getOSArch() { - return System.getProperty("os.arch"); - } - - @Override - public String getNL() { - return Locale.getDefault().getLanguage(); - } - - @Override - public String getOS() { - return Constants.OS_UNKNOWN; - } - - @Override - public String getWS() { - return null; //No window system - } - - @Override - public boolean inDebugMode() { - return false; - } - - @Override - public boolean inDevelopmentMode() { - return false; - } - - @Override - public String setProperty(String key, String value) { - return value; //Launcher information is not stored - } - - @Override - public String getProperty(String key) { - return null; //Launcher information/configuration is not required - } - -} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/NoContentTypeSpecificHandling.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/NoContentTypeSpecificHandling.java deleted file mode 100644 index 87e1f2f91b..0000000000 --- a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/NoContentTypeSpecificHandling.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.base.service; - -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.QualifiedName; -import org.eclipse.core.runtime.content.IContentDescription; -import org.eclipse.core.runtime.content.IContentType; -import org.eclipse.core.runtime.content.IContentTypeManager; -import org.eclipse.core.runtime.content.IContentTypeMatcher; -import org.eclipse.core.runtime.preferences.IScopeContext; - -/** No content type specific handling is supported. */ -public class NoContentTypeSpecificHandling implements IContentTypeManager { - - @Override - public IContentType findContentTypeFor(InputStream contents, String fileName) throws IOException { - return null; - } - - @Override - public IContentType findContentTypeFor(String fileName) { - return null; - } - - @Override - public IContentType[] findContentTypesFor(InputStream contents, String fileName) throws IOException { - return null; - } - - @Override - public IContentType[] findContentTypesFor(String fileName) { - return null; - } - - @Override - public IContentDescription getDescriptionFor(InputStream contents, String fileName, QualifiedName[] options) throws IOException { - return null; - } - - @Override - public IContentDescription getDescriptionFor(Reader contents, String fileName, QualifiedName[] options) throws IOException { - return null; - } - - @Override - public void addContentTypeChangeListener(IContentTypeChangeListener listener) {} - - @Override - public IContentType[] getAllContentTypes() { - return null; - } - - @Override - public IContentType getContentType(String contentTypeIdentifier) { - return null; - } - - @Override - public IContentTypeMatcher getMatcher(ISelectionPolicy customPolicy, IScopeContext context) { - return null; - } - - @Override - public void removeContentTypeChangeListener(IContentTypeChangeListener listener) { - - } - - @Override - public IContentType addContentType(String contentTypeIdentifier, String name, IContentType baseType) - throws CoreException { - return null; - } - - @Override - public void removeContentType(String contentTypeIdentifier) throws CoreException {} - -} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/NoDebugging.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/NoDebugging.java deleted file mode 100644 index 095be889e9..0000000000 --- a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/NoDebugging.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.base.service; - -import java.io.File; -import java.util.Map; - -import org.eclipse.osgi.service.debug.DebugOptions; -import org.eclipse.osgi.service.debug.DebugTrace; - -/** No debugging shall be performed */ -public class NoDebugging implements DebugOptions { - - @Override - public boolean getBooleanOption(String option, boolean defaultValue) { - return false; - } - - @Override - public String getOption(String option) { - return null; - } - - @Override - public String getOption(String option, String defaultValue) { - return null; - } - - @Override - public int getIntegerOption(String option, int defaultValue) { - return 0; - } - - @Override - public Map getOptions() { - return null; - } - - @Override - public void setOption(String option, String value) {} - - @Override - public void setOptions(Map options) {} - - @Override - public void removeOption(String option) {} - - @Override - public boolean isDebugEnabled() { - return false; - } - - @Override - public void setDebugEnabled(boolean value) {} - - @Override - public void setFile(File newFile) {} - - @Override - public File getFile() { - return null; - } - - @Override - public DebugTrace newDebugTrace(String bundleSymbolicName) { - return null; - } - - @Override - public DebugTrace newDebugTrace(String bundleSymbolicName, Class traceEntryClass) { - return null; - } - -} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/NoEclipsePreferences.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/NoEclipsePreferences.java deleted file mode 100644 index 7f6bed44ed..0000000000 --- a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/NoEclipsePreferences.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.base.service; - -import java.io.InputStream; -import java.io.OutputStream; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.preferences.DefaultScope; -import org.eclipse.core.runtime.preferences.IEclipsePreferences; -import org.eclipse.core.runtime.preferences.IExportedPreferences; -import org.eclipse.core.runtime.preferences.IPreferenceFilter; -import org.eclipse.core.runtime.preferences.IPreferencesService; -import org.eclipse.core.runtime.preferences.IScopeContext; -import org.osgi.service.prefs.Preferences; - -/** - * The formatters dependents on plugins which access Eclipse core functionality, - * configurable by preferences. This functionality is never used by the formatters itself. - * Hence modifications are ignored and default values are provided on request. - */ -public class NoEclipsePreferences implements IPreferencesService { - private static final String UNUSED = "unused"; - - @Override - public IEclipsePreferences getRootNode() { - //Return value is not effectively used. - return DefaultScope.INSTANCE.getNode(UNUSED); - } - - @Override - public String get(String key, String defaultValue, Preferences[] nodes) { - return null; - } - - @Override - public boolean getBoolean(String qualifier, String key, boolean defaultValue, IScopeContext[] contexts) { - return false; - } - - @Override - public byte[] getByteArray(String qualifier, String key, byte[] defaultValue, IScopeContext[] contexts) { - return null; - } - - @Override - public double getDouble(String qualifier, String key, double defaultValue, IScopeContext[] contexts) { - return 0; - } - - @Override - public float getFloat(String qualifier, String key, float defaultValue, IScopeContext[] contexts) { - return 0; - } - - @Override - public int getInt(String qualifier, String key, int defaultValue, IScopeContext[] contexts) { - return 0; - } - - @Override - public long getLong(String qualifier, String key, long defaultValue, IScopeContext[] contexts) { - return 0; - } - - @Override - public String getString(String qualifier, String key, String defaultValue, IScopeContext[] contexts) { - return null; - } - - @Override - public IStatus exportPreferences(IEclipsePreferences node, OutputStream output, String[] excludesList) throws CoreException { - return null; - } - - @Override - public IStatus importPreferences(InputStream input) throws CoreException { - return null; - } - - @Override - public IStatus applyPreferences(IExportedPreferences preferences) throws CoreException { - return null; - } - - @Override - public IExportedPreferences readPreferences(InputStream input) throws CoreException { - return null; - } - - @Override - public String[] getDefaultLookupOrder(String qualifier, String key) { - return null; - } - - @Override - public String[] getLookupOrder(String qualifier, String key) { - return null; - } - - @Override - public void setDefaultLookupOrder(String qualifier, String key, String[] order) {} - - @Override - public void exportPreferences(IEclipsePreferences node, IPreferenceFilter[] filters, OutputStream output) throws CoreException {} - - @Override - public IPreferenceFilter[] matches(IEclipsePreferences node, IPreferenceFilter[] filters) throws CoreException { - return null; - } - - @Override - public void applyPreferences(IEclipsePreferences node, IPreferenceFilter[] filters) throws CoreException {} - -} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/SingleSlf4JService.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/SingleSlf4JService.java deleted file mode 100644 index 6928621c83..0000000000 --- a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/SingleSlf4JService.java +++ /dev/null @@ -1,533 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.base.service; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.function.BiConsumer; -import java.util.function.BiFunction; -import java.util.function.Consumer; -import java.util.function.Supplier; - -import javax.annotation.Nullable; - -import org.eclipse.core.internal.runtime.InternalPlatform; -import org.eclipse.equinox.log.ExtendedLogReaderService; -import org.eclipse.equinox.log.ExtendedLogService; -import org.eclipse.equinox.log.LogFilter; -import org.eclipse.equinox.log.Logger; -import org.osgi.framework.Bundle; -import org.osgi.framework.ServiceReference; -import org.osgi.service.log.LogEntry; -import org.osgi.service.log.LogLevel; -import org.osgi.service.log.LogListener; -import org.osgi.service.log.LoggerConsumer; - -/** - * Eclipse log service facade that delegates to a Slf4J logger. - * The service does not provide historical log entries (empty history reported). - * No factory service is provided for OSGI logger extensions (method are marked - * as deprecated and raise UnsupportedOperationException). - * All Eclipse logger are delegated to a single Slf4J logger instance. - * The log messages can be formatted by customizer. - */ -public class SingleSlf4JService implements ExtendedLogService, ExtendedLogReaderService { - - private final org.slf4j.Logger delegate; - private final Map logLevel2methods; - private final Set listener; - private final BiFunction messageCustomizer; - - /** Create facade for named logger with customized messages. */ - public SingleSlf4JService(String name, BiFunction messageCustomizer) { - delegate = org.slf4j.LoggerFactory.getLogger(name); - logLevel2methods = new HashMap(); - /* - * Audit message are treated as normal info-messages and might not get logged. - * Logging of Eclipse messages in Spotless formatter is meant for debugging purposes and - * detection of erroneous usage/override of internal Eclipse methods. - * Hence the concept of Audit is not required. - */ - logLevel2methods.put(LogLevel.AUDIT, - create(() -> true, m -> delegate.info(m), (m, e) -> delegate.info(m, e))); - logLevel2methods.put(LogLevel.DEBUG, - create(() -> delegate.isDebugEnabled(), m -> delegate.debug(m), (m, e) -> delegate.debug(m, e))); - logLevel2methods.put(LogLevel.ERROR, - create(() -> delegate.isErrorEnabled(), m -> delegate.error(m), (m, e) -> delegate.error(m, e))); - logLevel2methods.put(LogLevel.INFO, - create(() -> delegate.isInfoEnabled(), m -> delegate.info(m), (m, e) -> delegate.info(m, e))); - logLevel2methods.put(LogLevel.TRACE, - create(() -> delegate.isTraceEnabled(), m -> delegate.trace(m), (m, e) -> delegate.trace(m, e))); - logLevel2methods.put(LogLevel.WARN, - create(() -> delegate.isWarnEnabled(), m -> delegate.warn(m), (m, e) -> delegate.warn(m, e))); - listener = new HashSet(); - this.messageCustomizer = messageCustomizer; - } - - @Override - @Deprecated - //Backward compatibility with Eclipse OSGI 3.12 - public void log(int level, String message) { - log(this, level, message); - } - - @Override - @Deprecated - //Backward compatibility with Eclipse OSGI 3.12 - public void log(int level, String message, @Nullable Throwable exception) { - log(this, level, message, exception); - } - - @SuppressWarnings("rawtypes") - @Override - @Deprecated - //Backward compatibility with Eclipse OSGI 3.12 - public void log(ServiceReference sr, int level, String message) { - log(this, level, message); - } - - @SuppressWarnings("rawtypes") - @Override - @Deprecated - //Backward compatibility with Eclipse OSGI 3.12 - public void log(ServiceReference sr, int level, String message, Throwable exception) { - log(this, level, message, exception); - } - - @Override - public void log(Object context, int level, String message) { - log(context, level, message, null); - } - - @Override - public void log(Object context, int level, String message, @Nullable Throwable exception) { - LogLevel logLevel = convertDeprectatedOsgiLevel(level); - log(new SimpleLogEntry(logLevel, message, exception)); - } - - @Override - public boolean isLoggable(int level) { - LogLevel logLevel = convertDeprectatedOsgiLevel(level); - return logLevel2methods.get(logLevel).isEnabled(); - } - - @SuppressWarnings("deprecation") ////Backward compatibility with Eclipse OSGI 3.12 - private static LogLevel convertDeprectatedOsgiLevel(int level) { - switch (level) { - case SingleSlf4JService.LOG_DEBUG: - return LogLevel.DEBUG; - case SingleSlf4JService.LOG_INFO: - return LogLevel.INFO; - case SingleSlf4JService.LOG_ERROR: - return LogLevel.ERROR; - case SingleSlf4JService.LOG_WARNING: - return LogLevel.WARN; - default: - return LogLevel.AUDIT; - } - } - - @Override - public String getName() { - return delegate.getName(); - } - - @Override - public Logger getLogger(String loggerName) { - return this; - } - - @Override - public Logger getLogger(Bundle bundle, String loggerName) { - return this; - } - - @Override - public void addLogListener(LogListener listener) { - synchronized (this.listener) { - this.listener.add(listener); - } - } - - @Override - public void removeLogListener(LogListener listener) { - synchronized (this.listener) { - this.listener.remove(listener); - } - } - - private void log(LogEntry entry) { - synchronized (listener) { - listener.stream().forEach(l -> l.logged(entry)); - } - String customMessage = messageCustomizer.apply(entry.getMessage(), entry.getLogLevel()); - logLevel2methods.get(entry.getLogLevel()).log(customMessage, entry.getException()); - } - - @Override - @Deprecated - //Backward compatibility with Eclipse OSGI 3.12 - public Enumeration getLog() { - return Collections.emptyEnumeration(); //We do not provide historical information - } - - @Override - public void addLogListener(LogListener listener, LogFilter filter) { - addLogListener(listener); //Listener must filter if required - - } - - @Override - public org.osgi.service.log.Logger getLogger(Class clazz) { - return this; - } - - @Override - @Deprecated - public L getLogger(String name, Class loggerType) { - throw new UnsupportedOperationException("Logger factory for indifivaul types currently not supported."); - } - - @Override - @Deprecated - public L getLogger(Class clazz, Class loggerType) { - return getLogger(getName(), loggerType); - } - - @Override - @Deprecated - public L getLogger(Bundle bundle, String name, Class loggerType) { - return getLogger(getName(), loggerType); - } - - @Override - public boolean isTraceEnabled() { - return delegate.isTraceEnabled(); - } - - @Override - public void trace(String message) { - log(new SimpleLogEntry(LogLevel.TRACE, message)); - } - - @Override - public void trace(String format, Object arg) { - trace(String.format(format, arg)); - } - - @Override - public void trace(String format, Object arg1, Object arg2) { - trace(String.format(format, arg1, arg2)); - } - - @Override - public void trace(String format, Object... arguments) { - trace(String.format(format, arguments)); - } - - @Override - public void trace(LoggerConsumer consumer) throws E { - consumer.accept(this); - } - - @Override - public boolean isDebugEnabled() { - return delegate.isDebugEnabled(); - } - - @Override - public void debug(String message) { - log(new SimpleLogEntry(LogLevel.DEBUG, message)); - } - - @Override - public void debug(String format, Object arg) { - debug(String.format(format, arg)); - } - - @Override - public void debug(String format, Object arg1, Object arg2) { - debug(String.format(format, arg1, arg2)); - } - - @Override - public void debug(String format, Object... arguments) { - debug(String.format(format, arguments)); - } - - @Override - public void debug(LoggerConsumer consumer) throws E { - consumer.accept(this); - } - - @Override - public boolean isInfoEnabled() { - return delegate.isInfoEnabled(); - } - - @Override - public void info(String message) { - log(new SimpleLogEntry(LogLevel.INFO, message)); - } - - @Override - public void info(String format, Object arg) { - info(String.format(format, arg)); - } - - @Override - public void info(String format, Object arg1, Object arg2) { - info(String.format(format, arg1, arg2)); - } - - @Override - public void info(String format, Object... arguments) { - info(String.format(format, arguments)); - } - - @Override - public void info(LoggerConsumer consumer) throws E { - consumer.accept(this); - } - - @Override - public boolean isWarnEnabled() { - return delegate.isWarnEnabled(); - } - - @Override - public void warn(String message) { - log(new SimpleLogEntry(LogLevel.WARN, message)); - } - - @Override - public void warn(String format, Object arg) { - warn(String.format(format, arg)); - } - - @Override - public void warn(String format, Object arg1, Object arg2) { - warn(String.format(format, arg1, arg2)); - } - - @Override - public void warn(String format, Object... arguments) { - warn(String.format(format, arguments)); - } - - @Override - public void warn(LoggerConsumer consumer) throws E { - consumer.accept(this); - } - - @Override - public boolean isErrorEnabled() { - return delegate.isErrorEnabled(); - } - - @Override - public void error(String message) { - log(new SimpleLogEntry(LogLevel.ERROR, message)); - } - - @Override - public void error(String format, Object arg) { - error(String.format(format, arg)); - } - - @Override - public void error(String format, Object arg1, Object arg2) { - error(String.format(format, arg1, arg2)); - } - - @Override - public void error(String format, Object... arguments) { - error(String.format(format, arguments)); - } - - @Override - public void error(LoggerConsumer consumer) throws E { - consumer.accept(this); - } - - @Override - public void audit(String message) { - log(new SimpleLogEntry(LogLevel.AUDIT, message)); - } - - @Override - public void audit(String format, Object arg) { - audit(String.format(format, arg)); - } - - @Override - public void audit(String format, Object arg1, Object arg2) { - audit(String.format(format, arg1, arg2)); - } - - @Override - public void audit(String format, Object... arguments) { - audit(String.format(format, arguments)); - } - - /** Internal wrapper for Eclipse OSGI 3.12 based logs and new log services. */ - private static class SimpleLogEntry implements LogEntry { - - private final LogLevel level; - private final String message; - private final Optional execption; - - public SimpleLogEntry(LogLevel level, String message) { - this(level, message, Optional.empty()); - } - - public SimpleLogEntry(LogLevel level, String message, @Nullable Throwable execption) { - this(level, message, Optional.ofNullable(execption)); - } - - private SimpleLogEntry(LogLevel level, String message, Optional execption) { - this.level = level; - this.message = message; - this.execption = execption; - } - - @Override - public Bundle getBundle() { - //Return the spotless framework bundle - return InternalPlatform.getDefault().getBundleContext().getBundle(); - } - - @SuppressWarnings({"rawtypes", "unchecked"}) - @Override - public ServiceReference getServiceReference() { - return null; - } - - @Override - @Deprecated - //Backward compatibility with Eclipse OSGI 3.12 - public int getLevel() { - switch (level) { - case DEBUG: - case TRACE: - return SingleSlf4JService.LOG_DEBUG; - case AUDIT: - case INFO: - return SingleSlf4JService.LOG_INFO; - case ERROR: - return SingleSlf4JService.LOG_ERROR; - case WARN: - return SingleSlf4JService.LOG_WARNING; - } - return SingleSlf4JService.LOG_ERROR; //Don't fail here. Just log it as error. This is anyway just for debugging internal problems. - } - - @Override - public String getMessage() { - return message; - } - - @Override - public Throwable getException() { - return execption.orElse(null); - } - - @Override - public long getTime() { - return 0; - } - - @Override - public String toString() { - StringWriter result = new StringWriter(); - result.write(message); - if (execption.isPresent()) { - result.write('\n'); - result.write(execption.get().toString()); - result.write('\n'); - execption.get().printStackTrace(new PrintWriter(result)); - } - return result.toString(); - } - - @Override - public LogLevel getLogLevel() { - return level; - } - - @Override - public String getLoggerName() { - return this.getClass().getSimpleName(); - } - - @Override - public long getSequence() { - return 0; - } - - @Override - public String getThreadInfo() { - return null; - } - - @Override - public StackTraceElement getLocation() { - return null; // Not used by SingleSlf4JService - } - - } - - private static LogMethods create(Supplier enabled, Consumer log, BiConsumer logException) { - return new LogMethods(enabled, log, logException); - } - - private static class LogMethods { - private final Supplier enabled; - private final Consumer log; - private final BiConsumer logException; - - private LogMethods(Supplier enabled, Consumer log, BiConsumer logException) { - this.enabled = enabled; - this.log = log; - this.logException = logException; - } - - public boolean isEnabled() { - return enabled.get(); - } - - public void log(String message) { - log.accept(message); - } - - public void log(String message, @Nullable Throwable exception) { - if (null == exception) { - log(message); - } else { - logException.accept(message, exception); - } - } - - }; - -} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/TemporaryLocation.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/TemporaryLocation.java deleted file mode 100644 index 2999014d23..0000000000 --- a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/TemporaryLocation.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Copyright 2016-2021 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.base.service; - -import java.io.File; -import java.io.IOError; -import java.io.IOException; -import java.net.URISyntaxException; -import java.net.URL; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Comparator; - -import org.eclipse.osgi.service.datalocation.Location; - -/** All files generated at runtime are stored in a temporary location. */ -public class TemporaryLocation implements Location, AutoCloseable { - private static final String TEMP_PREFIX = "com_diffplug_spotless_extra_eclipse"; - private final URL location; - private Location parent; - - public TemporaryLocation() { - this(null, createTemporaryDirectory()); - } - - private TemporaryLocation(Location parent, URL defaultValue) { - this.location = defaultValue; - this.parent = parent; - } - - private static URL createTemporaryDirectory() { - try { - Path location = Files.createTempDirectory(TEMP_PREFIX); - return location.toUri().toURL(); - } catch (IOException e) { - throw new IOError(e); - } - } - - @Override - public boolean allowsDefault() { - return false; - } - - @Override - public URL getDefault() { - return null; - } - - @Override - public Location getParentLocation() { - return parent; - } - - @Override - public URL getURL() { - return location; - } - - @Override - public boolean isSet() { - return true; - } - - @Override - public boolean isReadOnly() { - return false; - } - - @Override - @Deprecated - public boolean setURL(URL value, boolean lock) throws IllegalStateException { - throw new IllegalStateException("URL not modifyable."); - } - - @Override - public boolean set(URL value, boolean lock) throws IllegalStateException, IOException { - throw new IllegalStateException("URL not modifyable."); - } - - @Override - public boolean set(URL value, boolean lock, String lockFilePath) throws IllegalStateException, IOException { - throw new IllegalStateException("URL not modifyable."); - } - - @Override - public boolean lock() throws IOException { - return false; //Lock not supported - } - - @Override - public void release() { - //Lock not supported - } - - @Override - public boolean isLocked() throws IOException { - return false; //Lock not supported - } - - @Override - public Location createLocation(Location parent, URL defaultValue, boolean readonly) { - return new TemporaryLocation(parent, defaultValue); - } - - @Override - public URL getDataArea(String path) throws IOException { - try { - Path locationPath = Paths.get(location.toURI()); - return locationPath.resolve(path).toUri().toURL(); - } catch (URISyntaxException e) { - throw new IOException("Location not correctly formatted.", e); - } - } - - @Override - public void close() throws Exception { - try { - Path path = Path.of(location.toURI()); - Files.walk(path) - .sorted(Comparator.reverseOrder()) - .map(Path::toFile) - .forEach(File::delete); - path.toFile().delete(); - } catch (IOException e) { - //At shutdown everything is just done on best-efforts basis - } - } - -} diff --git a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/package-info.java b/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/package-info.java deleted file mode 100644 index b444c0c76a..0000000000 --- a/_ext/eclipse-base/src/main/java/com/diffplug/spotless/extra/eclipse/base/service/package-info.java +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** Mocking Eclipse Equinox OSGi services. */ -package com.diffplug.spotless.extra.eclipse.base.service; diff --git a/_ext/eclipse-base/src/main/resources/META-INF/MANIFEST.MF b/_ext/eclipse-base/src/main/resources/META-INF/MANIFEST.MF deleted file mode 100644 index 348dc4c453..0000000000 --- a/_ext/eclipse-base/src/main/resources/META-INF/MANIFEST.MF +++ /dev/null @@ -1,3 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-SymbolicName: com.diffplug.gradle.spotless.eclipse; singleton:=true diff --git a/_ext/eclipse-base/src/main/resources/META-INF/services/org.osgi.framework.connect.FrameworkUtilHelper b/_ext/eclipse-base/src/main/resources/META-INF/services/org.osgi.framework.connect.FrameworkUtilHelper deleted file mode 100644 index 0bd6c29641..0000000000 --- a/_ext/eclipse-base/src/main/resources/META-INF/services/org.osgi.framework.connect.FrameworkUtilHelper +++ /dev/null @@ -1 +0,0 @@ -com.diffplug.spotless.extra.eclipse.base.osgi.FrameworkBundleRegistry \ No newline at end of file diff --git a/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipseFrameworkTest.java b/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipseFrameworkTest.java deleted file mode 100644 index ca76c92ce1..0000000000 --- a/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/SpotlessEclipseFrameworkTest.java +++ /dev/null @@ -1,330 +0,0 @@ -/* - * Copyright 2016-2021 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.base; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; - -import java.io.PrintStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; - -import org.assertj.core.api.AbstractAssert; -import org.assertj.core.api.ObjectArrayAssert; -import org.assertj.core.api.StringAssert; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.ILog; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.equinox.log.ExtendedLogReaderService; -import org.eclipse.equinox.log.ExtendedLogService; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.BundleException; -import org.osgi.framework.ServiceReference; -import org.osgi.service.log.LogEntry; -import org.osgi.service.log.LogLevel; -import org.osgi.service.log.LogListener; -import org.slf4j.simple.SimpleLogger; - -import com.diffplug.spotless.extra.eclipse.base.service.SingleSlf4JService; - -/** Integration tests */ -class SpotlessEclipseFrameworkTest { - - private final static String TEST_LOGGER_NAME = SpotlessEclipseFrameworkTest.class.getSimpleName(); - private final static String CUSTOM_PREFIX = "prefix\t"; - private final static String CUSTOM_POSTFIX = "\tpostfix"; - private final static String TEST_EXCEPTION_MESSAGE = "MY TEST-EXCEPTION"; - private static Slf4JMesssageListener SLF4J_RECEIVER = null; - - private static boolean TREAT_ERROR_AS_EXCEPTION = false; - - @BeforeAll - static void frameworkTestSetup() throws BundleException { - //Prepare interception of SLF4J messages to System.out - SLF4J_RECEIVER = new Slf4JMesssageListener(); - - //Configure SLF4J-Simple - System.setProperty(SimpleLogger.LOG_FILE_KEY, "System.out"); - System.setProperty(SimpleLogger.SHOW_SHORT_LOG_NAME_KEY, "true"); - System.setProperty(SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "warn"); - - //Instantiate default framework + SLF4J logger - SpotlessEclipseFramework.setup(new SpotlessEclipseConfig() { - @Override - public void registerServices(SpotlessEclipseServiceConfig config) { - config.applyDefault(); - config.useSlf4J(TEST_LOGGER_NAME, (s, l) -> { - if (TREAT_ERROR_AS_EXCEPTION && (LogLevel.ERROR == l)) { - throw new IllegalArgumentException(TEST_EXCEPTION_MESSAGE); - } - return CUSTOM_PREFIX + s + CUSTOM_POSTFIX; - }); - } - }); - } - - @AfterAll - static void deregisterSlf4JReceiver() { - SLF4J_RECEIVER.deregister(); - } - - private EclipseMessageListener eclipseMessageListener; - - @BeforeEach - void eclipseReceiverSetup() { - ExtendedLogReaderService service = getService(ExtendedLogReaderService.class); - eclipseMessageListener = new EclipseMessageListener(); - service.addLogListener(eclipseMessageListener); - SLF4J_RECEIVER.clear(); - } - - @AfterEach - void logReceiverTearDown() { - ExtendedLogReaderService service = getService(ExtendedLogReaderService.class); - service.removeLogListener(eclipseMessageListener); - } - - @Test - void testCustomizedLogMessage() { - ResourcesPlugin.getPlugin().getLog().log(new Status(IStatus.ERROR, "Some plugin", "Hello World!")); - assertSlf4J() - .as("Error message logged.").received("Hello World!").contains(TEST_LOGGER_NAME) - .as("Customization method has been applied.").contains(CUSTOM_PREFIX, CUSTOM_POSTFIX) - .as("Status level has been converted to simple SLF4J level").contains("ERROR"); - assertEclipse() - .as("Warning message received.").received("Hello World!") - .as("Customization method is only for SLF4J").doesNotContain(CUSTOM_PREFIX); - } - - @Test - void testCustomizedLogException() { - assertThatExceptionOfType(IllegalArgumentException.class) - .isThrownBy(() -> { - try { - TREAT_ERROR_AS_EXCEPTION = true; - ResourcesPlugin.getPlugin().getLog().log(new Status(IStatus.ERROR, "Some plugin", "Hello World!")); - } finally { - TREAT_ERROR_AS_EXCEPTION = false; - } - }) - .withMessage(TEST_EXCEPTION_MESSAGE); - } - - @Test - void testPluginLog() { - List logLevels = Arrays.asList(IStatus.CANCEL, IStatus.ERROR, IStatus.INFO, IStatus.OK, IStatus.WARNING); - List enabledLogLevels = Arrays.asList(IStatus.ERROR, IStatus.WARNING); - List disabledLogLevels = logLevels.stream().filter(level -> !enabledLogLevels.contains(level)).collect(Collectors.toList()); - ILog logger = ResourcesPlugin.getPlugin().getLog(); - logLevels.forEach(logLevel -> logger.log(new Status(logLevel, "Some plugin", logLevel.toString()))); - assertSlf4J() - .as("Messages for all enabled levels are logged.").received( - enabledLogLevels.stream().map(i -> i.toString()).collect(Collectors.toList())); - assertSlf4J() - .as("Messages all disabled levels are not logged.").notReceived( - disabledLogLevels.stream().map(i -> i.toString()).collect(Collectors.toList())); - assertEclipse() - .as("All messages received.").received( - logLevels.stream().map(i -> i.toString()).collect(Collectors.toList())); - } - - @Test - void testLogServiceLevel() { - ExtendedLogService service = getService(ExtendedLogService.class); - assertThat(service.isErrorEnabled()).as("Error log level is enabled").isTrue(); - assertThat(service.isWarnEnabled()).as("Warning log level is enabled").isTrue(); - assertThat(service.isInfoEnabled()).as("Info log level is disabled").isFalse(); - assertThat(service.isDebugEnabled()).as("Debug log level is disabled").isFalse(); - assertThat(service.isTraceEnabled()).as("Trace log level is disabled").isFalse(); - } - - @Test - void testLogServiceLog() { - ExtendedLogService service = getService(ExtendedLogService.class); - service.info("Log Info"); - service.warn("Log Warn"); - assertSlf4J().received("Log Warn"); - assertSlf4J().notReceived("Log Info"); - assertEclipse().received(Arrays.asList("Log Warn", "Log Info")); - } - - @Test - @Deprecated - void testLogServiceLog_3_12() { - ExtendedLogService service = getService(ExtendedLogService.class); - service.log(SingleSlf4JService.LOG_INFO, "Log Info"); - try { - throw new IllegalArgumentException(TEST_EXCEPTION_MESSAGE); - } catch (Exception e) { - service.log(SingleSlf4JService.LOG_WARNING, "Log Warn", e); - } - assertSlf4J().received(Arrays.asList("Log Warn", TEST_EXCEPTION_MESSAGE)); - assertSlf4J().notReceived("Log Info"); - assertEclipse().received(Arrays.asList("Log Warn", TEST_EXCEPTION_MESSAGE, "Log Info")); - } - - private static T getService(Class serviceClass) { - ResourcesPlugin plugin = ResourcesPlugin.getPlugin(); - assertThat(plugin).as("ResourcesPlugin instantiated as part of framework defaults").isNotNull(); - Bundle bundle = plugin.getBundle(); - assertThat(bundle).as("ResourcesPlugin has been started.").isNotNull(); - BundleContext context = bundle.getBundleContext(); - assertThat(context).as("ResourcesPlugin has been started.").isNotNull(); - ServiceReference reference = context.getServiceReference(serviceClass); - assertThat(reference).as(serviceClass.getSimpleName() + " has been registered.").isNotNull(); - T service = context.getService(reference); - assertThat(service).as(serviceClass.getSimpleName() + " can be resolved.").isNotNull(); - return service; - } - - private static interface IMessageListener { - Collection getMessages(); - } - - private static class EclipseMessageListener implements LogListener, IMessageListener { - - private final List messages; - - public EclipseMessageListener() { - messages = new ArrayList(); - } - - @Override - public Collection getMessages() { - return Collections.unmodifiableList(messages); - } - - @Override - public void logged(LogEntry entry) { - messages.add(entry.getMessage()); - if (null != entry.getException()) { - messages.add(entry.getException().getMessage()); - } - } - } - - private final static class Slf4JMesssageListener extends PrintStream implements IMessageListener { - - private final List messages; - private final PrintStream originalStream; - - public Slf4JMesssageListener() { - super(System.out); - messages = new ArrayList(); - originalStream = System.out; - System.setOut(this); - } - - @Override - public void println(String x) { - if (x.contains(TEST_LOGGER_NAME)) { - messages.add(x); - } else { - super.println(x); - } - } - - @Override - public void println(Object x) { - if (x instanceof Exception) { - Exception e = (Exception) x; - if (TEST_EXCEPTION_MESSAGE == e.getMessage()) { - messages.add(TEST_EXCEPTION_MESSAGE); - } - } - super.println(x); - } - - public void deregister() { - System.setOut(originalStream); - } - - public void clear() { - messages.clear(); - } - - @Override - public Collection getMessages() { - return Collections.unmodifiableList(messages); - } - } - - private static class MessageListenerAssert extends AbstractAssert, T> { - - public MessageListenerAssert(T actual) { - super(actual, MessageListenerAssert.class); - } - - public ObjectArrayAssert received(Collection unformattedMessages) { - List formattedMessages = unformattedMessages.stream() - .map(unformattedMessage -> getReceivedMessage(unformattedMessage, false)) - .collect(Collectors.toList()); - return new ObjectArrayAssert(formattedMessages.toArray(new String[0])); - } - - public StringAssert received(String unformattedMessage) { - return new StringAssert(getReceivedMessage(unformattedMessage, false)); - } - - public MessageListenerAssert notReceived(String unformattedMessage) { - getReceivedMessage(unformattedMessage, true); - return this; - } - - public MessageListenerAssert notReceived(Collection unformattedMessages) { - unformattedMessages.forEach(unformattedMessage -> getReceivedMessage(unformattedMessage, true)); - return this; - } - - private String getReceivedMessage(String unformattedMessage, boolean negate) { - isNotNull(); - String receivedMessage = null; - for (String formattedMessage : actual.getMessages()) { - if (formattedMessage.contains(unformattedMessage)) { - receivedMessage = formattedMessage; - break; - } - } - if ((!negate) && (null == receivedMessage)) { - failWithMessage("Message <%s> not received.", unformattedMessage); - } - if (negate && (null != receivedMessage)) { - failWithMessage("Message <%s> has been received. Formatted message is: %s", unformattedMessage, receivedMessage); - } - return receivedMessage; - } - - } - - private static MessageListenerAssert assertSlf4J() { - return new MessageListenerAssert(SLF4J_RECEIVER).as("SLF4J"); - } - - private MessageListenerAssert assertEclipse() { - return new MessageListenerAssert(eclipseMessageListener).as("Eclipse"); - } -} diff --git a/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/osgi/BundleSetTest.java b/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/osgi/BundleSetTest.java deleted file mode 100644 index 9c5c97ddb8..0000000000 --- a/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/osgi/BundleSetTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2016-2021 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.base.osgi; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.*; - -import java.util.Arrays; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleException; - -class BundleSetTest { - - BundleSet instance; - - @BeforeEach - void initialize() { - instance = new BundleSet(); - } - - @Test - void testAddGet() throws BundleException { - Bundle testBundle1 = new TestBundle(1, "a"); - Bundle testBundle2 = new TestBundle(2, "b"); - instance.add(testBundle1); - instance.add(testBundle2); - assertEquals(testBundle1, instance.get(1), "Get by ID 1"); - assertEquals(testBundle2, instance.get(2), "Get by ID 2"); - assertEquals(testBundle1, instance.get("a"), "Get by symbolic name 'a'"); - assertEquals(testBundle2, instance.get("b"), "Get by symbolic name 'b'"); - assertTrue(instance.getAll().containsAll(Arrays.asList(testBundle1, testBundle2)), "Contains all"); - } - - @Test - void testSameSymbolicName() throws BundleException { - final String symbolicName = "sym.a"; - final long id1 = 12345; - final long id2 = 23456; - Bundle testBundle1 = new TestBundle(id1, symbolicName); - Bundle testBundle2 = new TestBundle(id2, symbolicName); - instance.add(testBundle1); - BundleException e = assertThrows(BundleException.class, () -> instance.add(testBundle2)); - assertThat(e.getMessage()).as("BundleException does not contain symbolic name.").contains(symbolicName); - assertThat(e.getMessage()).as("BundleException does not contain ID of exisiting bundle.").contains(Long.toString(id1)); - assertThat(e.getMessage()).as("BundleException does not contain ID of new bundle.").contains(Long.toString(id2)); - } - - @Test - void testSameID() throws BundleException { - final String symbolicName1 = "sym.a"; - final String symbolicName2 = "sym.b"; - final long id = 12345; - Bundle testBundle1 = new TestBundle(id, symbolicName1); - Bundle testBundle2 = new TestBundle(id, symbolicName2); - instance.add(testBundle1); - BundleException e = assertThrows(BundleException.class, () -> instance.add(testBundle2)); - assertThat(e.getMessage()).as("BundleException does not contain ID.").contains(Long.toString(id)); - assertThat(e.getMessage()).as("BundleException does not contain symbolic name of exisiting bundle.").contains(symbolicName1); - assertThat(e.getMessage()).as("BundleException does not contain symbolic name of new bundle.").contains(symbolicName2); - } - -} diff --git a/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/osgi/ServiceCollectionTest.java b/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/osgi/ServiceCollectionTest.java deleted file mode 100644 index 05f18c475c..0000000000 --- a/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/osgi/ServiceCollectionTest.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright 2016-2021 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.base.osgi; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.*; - -import java.util.HashMap; - -import org.assertj.core.api.AbstractAssert; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.osgi.framework.Bundle; -import org.osgi.framework.ServiceException; -import org.osgi.framework.ServiceReference; - -class ServiceCollectionTest { - - ServiceCollection instance; - - @BeforeEach - void initialize() { - Bundle systemBundle = new TestBundle(0, "test.system"); - instance = new ServiceCollection(systemBundle, new HashMap()); - } - - @Test - void testAddGet() { - Service1 service1 = new Service1(); - Service2 service2 = new Service2(); - instance.add(Interf1.class, service1); - instance.add(Interf2a.class, service2); - instance.add(Interf2b.class, service2); - assertFor(instance).getServiceForReferences(Interf1.class).matchesService(service1); - assertFor(instance).getServiceForReferences(Interf2a.class).matchesService(service2); - assertFor(instance).getServiceForReferences(Interf2b.class).matchesService(service2); - } - - @Test - void testMultipleServicesPerInterface() { - Service1 serviceX = new Service1(); - Service1 serviceY = new Service1(); - instance.add(Interf1.class, serviceX); - ServiceException e = assertThrows(ServiceException.class, () -> instance.add(Interf1.class, serviceY)); - assertThat(e.getMessage()).as("ServiceException does not contain interface class name.").contains(Interf1.class.getName()); - } - - private static class ServiceReferenceAssert extends AbstractAssert { - - private final ServiceCollection actual; - private final ServiceReference reference; - - public ServiceReferenceAssert(ServiceCollection actual) { - this(actual, null); - } - - public ServiceReferenceAssert(ServiceCollection actual, ServiceReference reference) { - super(actual, ServiceReferenceAssert.class); - this.reference = reference; - this.actual = actual; - - } - - ServiceReferenceAssert getServiceForReferences(Class interfaceClass) { - ServiceReference[] references = actual.getReferences(interfaceClass.getName()); - int numberOfFoundReferences = null == references ? 0 : references.length; - if (numberOfFoundReferences != 1) { - failWithMessage("Expected to find exactly 1 reference for <%s> , but found %d.", interfaceClass.getName(), numberOfFoundReferences); - } - return new ServiceReferenceAssert(actual, references[0]); - } - - ServiceReferenceAssert matchesService(Object expected) { - if (null == reference) { - failWithMessage("No reference requested."); - } - Object serviceForRef = actual.getService(reference); - if (null == serviceForRef) { - failWithMessage("No service provided for reference."); - } - if (!serviceForRef.equals(expected)) { - failWithMessage("Unexpected service found."); - } - - return this; - } - } - - private static ServiceReferenceAssert assertFor(ServiceCollection actual) { - return new ServiceReferenceAssert(actual); - } - - private static interface Interf1 {}; - - private static interface Interf2a {}; - - private static interface Interf2b {}; - - private static class Service1 implements Interf1 {}; - - private static class Service2 implements Interf2a, Interf2b {}; -} diff --git a/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/osgi/TestBundle.java b/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/osgi/TestBundle.java deleted file mode 100644 index 177442101d..0000000000 --- a/_ext/eclipse-base/src/test/java/com/diffplug/spotless/extra/eclipse/base/osgi/TestBundle.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.base.osgi; - -import java.io.File; -import java.io.IOException; -import java.net.URL; -import java.security.cert.X509Certificate; -import java.util.Dictionary; -import java.util.Enumeration; -import java.util.List; -import java.util.Map; - -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceReference; -import org.osgi.framework.Version; - -/** Helper for testing */ -public class TestBundle implements StaticBundle, TemporaryBundle { - private final String symbolicName; - private final long id; - - public TestBundle(long id, String symbolicName) { - this.id = id; - this.symbolicName = symbolicName; - } - - @Override - public int getState() { - return 0; - } - - @Override - @Deprecated - public Dictionary getHeaders() { - return null; - } - - @Override - public long getBundleId() { - return id; - } - - @Override - public ServiceReference[] getRegisteredServices() { - return null; - } - - @Override - public boolean hasPermission(Object permission) { - return false; - } - - @Override - public URL getResource(String name) { - return null; - } - - @Override - @Deprecated - public Dictionary getHeaders(String locale) { - return null; - } - - @Override - public String getSymbolicName() { - return symbolicName; - } - - @Override - public Class loadClass(String name) throws ClassNotFoundException { - return null; - } - - @Override - public Enumeration getResources(String name) throws IOException { - return null; - } - - @Override - public Enumeration getEntryPaths(String path) { - return null; - } - - @Override - public URL getEntry(String path) { - return null; - } - - @Override - @Deprecated - public Enumeration findEntries(String path, String filePattern, boolean recurse) { - return null; - } - - @Override - public BundleContext getBundleContext() { - return null; - } - - @Override - public Map> getSignerCertificates(int signersType) { - return null; - } - - @Override - public Version getVersion() { - return null; - } - - @Override - public A adapt(Class type) { - return null; - } - - @Override - public File getDataFile(String filename) { - return null; - } - - @Override - public int compareTo(Bundle o) { - return 0; - } - -} diff --git a/_ext/eclipse-wtp/CHANGES.md b/_ext/eclipse-wtp/CHANGES.md deleted file mode 100644 index d57618ad8c..0000000000 --- a/_ext/eclipse-wtp/CHANGES.md +++ /dev/null @@ -1,76 +0,0 @@ -# spotless-eclipse-wtp - -We adhere to the [keepachangelog](https://keepachangelog.com/en/1.0.0/) format (starting after version `3.15.1`). - -## [Unreleased] -### Fixed -* Fix typo in Gradle variable names ([#1425](https://github.com/diffplug/spotless/pull/1425)) - -## [3.23.0] - 2021-09-22 -### Added -* Switch to Web Tools Platform release 3.23.0 for Eclipse 4.21. - -## [3.22.0] - 2021-06-27 -### Added -* Switch to Web Tools Platform release 3.22.0 for Eclipse 4.20. - -## [3.21.0] - 2021-06-07 -### Added -* Switch to Web Tools Platform release 3.21.0 for Eclipse 4.19. Minimum required Java version changed from 8 to 11. - -## [3.20.0] - 2020-12-26 -### Added -* Switch to Web Tools Platform release 3.20.0 for Eclipse 4.18. - -## [3.19.0] - 2020-10-17 -### Added -* Fixed version number determined by change log. - -## [3.18.1] - 2020-10-17 -### Added -* Switch to Web Tools Platform release 3.19.0 for Eclipse 4.17. - -## [3.18.0] - 2020-10-03 -### Added -* Switch to Web Tools Platform release 3.18.0 for Eclipse 4.16. - -## [3.17.0] - 2020-10-03 -### Added -* Switch to Web Tools Platform release 3.17.0 for Eclipse 4.15. - -## [3.16.0] - 2020-09-26 -### Added -* Switch to Web Tools Platform release 3.16.0 for Eclipse 4.14. - -## [3.15.3] - 2020-03-26 -### Fixed -* Handling of character encodings on OS with non-unicode default file encoding format. CSS, HTML and JSON formatter steps encoded intermediately the input using the default file encoding, which was not lossless if the default file encoding did not support the full unicode character set. ([#545](https://github.com/diffplug/spotless/issues/545)). - -## [3.15.2] - 2020-03-04 -### Fixed -* Racing conditions in WTP formatter configurations. Multiple configurations within the same project are no longer supported. ([#492](https://github.com/diffplug/spotless/pull/492)). - -## [3.15.1] - 2019-11-27 -* Bugfix: Fix NPE in EclipseXmlFormatterStepImpl ([#490](https://github.com/diffplug/spotless/pull/490)). - -## [3.15.0] - 2019-11-06 -* Switch to Web Tools Platform release 3.15.0 for Eclipse 4.13 ([#480](https://github.com/diffplug/spotless/issues/480)). - -## [3.14.0] - 2019-06-24 -* Switch to Web Tools Platform release 3.14.0 for Eclipse 4.12 ([#423](https://github.com/diffplug/spotless/pull/423)). - -## [3.10.0] - 2019-03-17 -* Switch to Web Tools Platform release 3.10.0 for Eclipse 4.8 ([#378](https://github.com/diffplug/spotless/pull/378)). -* Include Eclipse logging allowing formatter warnings/errors to be logged via SLF4J ([#236](https://github.com/diffplug/spotless/issues/236)). - -## [3.9.8] - 2019-03-10 -* XML formatter ignores external URIs per default. ([#369](https://github.com/diffplug/spotless/issues/369)). Add `resolveExternalURI=true` property to switch to previous behavior. - -## [3.9.7] - 2019-02-25 -* Replaced `http` update-site with `https` ([#360](https://github.com/diffplug/spotless/issues/360)). - -## [3.9.6] - 2019-02-11 -* Fixed formatting of JSON arrays ([#344](https://github.com/diffplug/spotless/issues/344)). - -## [3.9.5] - 2018-08-08 -* Initial release! diff --git a/_ext/eclipse-wtp/LICENSE.txt b/_ext/eclipse-wtp/LICENSE.txt deleted file mode 100644 index 3d967aee74..0000000000 --- a/_ext/eclipse-wtp/LICENSE.txt +++ /dev/null @@ -1,70 +0,0 @@ -Eclipse Public License - v 1.0 - -THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. - -1. DEFINITIONS - -"Contribution" means: - -a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and -b) in the case of each subsequent Contributor: -i) changes to the Program, and -ii) additions to the Program; -where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program. -"Contributor" means any person or entity that distributes the Program. - -"Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program. - -"Program" means the Contributions distributed in accordance with this Agreement. - -"Recipient" means anyone who receives the Program under this Agreement, including all Contributors. - -2. GRANT OF RIGHTS - -a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form. -b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder. -c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program. -d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement. -3. REQUIREMENTS - -A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that: - -a) it complies with the terms and conditions of this Agreement; and -b) its license agreement: -i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose; -ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits; -iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and -iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange. -When the Program is made available in source code form: - -a) it must be made available under this Agreement; and -b) a copy of this Agreement must be included with each copy of the Program. -Contributors may not remove or alter any copyright notices contained within the Program. - -Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution. - -4. COMMERCIAL DISTRIBUTION - -Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense. - -For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages. - -5. NO WARRANTY - -EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations. - -6. DISCLAIMER OF LIABILITY - -EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -7. GENERAL - -If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. - -If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed. - -All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive. - -Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved. - -This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation. \ No newline at end of file diff --git a/_ext/eclipse-wtp/README.md b/_ext/eclipse-wtp/README.md deleted file mode 100644 index 41dd58ff9b..0000000000 --- a/_ext/eclipse-wtp/README.md +++ /dev/null @@ -1,10 +0,0 @@ -# spotless-eclipse-wtp - -Eclipse WTP is not available in a form which can be easily consumed by maven or gradle. To fix this, we publish Eclipse's WTP formatters, along with a small amount of glue code, into the `com.diffplug.spotless.extra:spotless-eclipse-wtp` artifact. - -To publish a new version, update the `_ext/eclipse-wtp/gradle.properties` appropriately and see [CONTRIBUTING.md](../../CONTRIBUTING.md) how to enable -`_ext` projects. - -## License - -Spotless at large is under the Apache 2.0 license, but this jar is under the EPL v1. diff --git a/_ext/eclipse-wtp/build.gradle b/_ext/eclipse-wtp/build.gradle deleted file mode 100644 index feacfbf4c1..0000000000 --- a/_ext/eclipse-wtp/build.gradle +++ /dev/null @@ -1,126 +0,0 @@ -ext { - developers = [ - fvgh: [ name: 'Frank Vennemeyer', email: 'frankgh@zoho.com' ], - ] - - p2Repository = "https://download.eclipse.org/webtools/repository/${VER_ECLIPSE_WTP}" - - p2Dependencies = [ - // XML/HTML Formatter - Dependencies - 'org.eclipse.wst.xml.core':'+', // DefaultXMLPartitionFormatter and XMLAssociationProvider - 'org.eclipse.wst.sse.core':'+', // Structure models - 'org.eclipse.wst.common.uriresolver':'+', // URI resolver for model queries - 'org.eclipse.wst.dtd.core':'+', // Support DTD extensions - - // XML Formatter - Dependencies - 'org.eclipse.wst.xsd.core':'+', // Support XSD extensions - - // JS Formatter - Dependencies - 'org.eclipse.wst.jsdt.core':'+', // DefaultCodeFormatter and related - 'org.eclipse.wst.jsdt.ui':'+', // Functionality to format comments - - // JSON Formatter - Dependencies - 'org.eclipse.wst.json.core':'+', // FormatProcessorJSON and related - 'org.eclipse.json':'+', // Provides JSON node interfaces - - // CSS Formatter - Dependencies - 'org.eclipse.wst.css.core':'+', // FormatProcessorCSS and related - - // HTML Formatter - Dependencies - 'org.eclipse.wst.html.core':'+', // HTMLFormatProcessorImpl and related - ] - - jarInclude = [ - '**/*.class', - // Take all classes - '**/*.properties', - // Text resources (for messages, etc) - '**/*.rsc', - // JSDT requires gramar files - '**/*.xml', - // Plugin XML and other resources - '*.html', - // License information about the included JARs, - 'META-INF/**' // Plugin manifest and addtional information - ] - - fatJarResourcesMap = [ - 'org.eclipse.wst.common.uriresolver': 'org.eclipse.wst.common.uriresolver.internal.provisional', - 'org.eclipse.wst.css.core': 'org.eclipse.wst.css.core.internal', - 'org.eclipse.wst.dtd.core': 'org.eclipse.wst.dtd.core.internal', - 'org.eclipse.wst.html.core': 'org.eclipse.wst.html.core.internal', - 'org.eclipse.wst.sse.core': 'org.eclipse.wst.sse.core.internal.encoding.util', - 'org.eclipse.wst.xml.core': 'org.eclipse.wst.xml.core.internal', - 'org.eclipse.wst.xsd.core': 'org.eclipse.wst.xsd.core.internal' - ] -} - -apply from: rootProject.file('_ext/gradle/update-lockfile.gradle') -apply from: rootProject.file('_ext/gradle/p2-fat-jar-setup.gradle') -apply from: rootProject.file('gradle/java-publish.gradle') - -dependencies { - implementation "com.diffplug.spotless:spotless-eclipse-base:${VER_SPOTLESS_ECLIPSE_BASE}" - // Required by most WPT formatters - implementation "com.ibm.icu:icu4j:${VER_IBM_ICU}" - // The XSD/DTD and other models are defined with EMF. - implementation "org.eclipse.emf:org.eclipse.emf.common:${VER_ECLIPSE_EMF}" - implementation "org.eclipse.emf:org.eclipse.emf.ecore:${VER_ECLIPSE_EMF}" - // Some WPT plugins requires OSGI bundle interfaces (but not effectively used) - implementation "org.eclipse.platform:org.eclipse.osgi.services:${VER_ECLIPSE_OSGI_SERVICES}" - // Provides document data structure and file buffers for formatters - implementation "org.eclipse.platform:org.eclipse.core.filebuffers:${VER_ECLIPSE_FILE_BUFFERS}" - // Provides text partitioners for formatters - implementation ("org.eclipse.platform:org.eclipse.jface.text:${VER_ECLIPSE_JFACE}") { - exclude group: 'org.eclipse.platform', module: 'org.eclipse.swt' - } - // Some WPT plugins use the EFS for storing temporary worspace data - implementation "org.eclipse.platform:org.eclipse.core.filesystem:${VER_ECLIPSE_EFS}" - // Required by org.eclipse.wst.xsd.core - implementation "org.eclipse.emf:org.eclipse.xsd:${VER_ECLIPSE_XSD}" - - testImplementation("org.slf4j:slf4j-simple:${VER_SLF4J}") -} - -jar { - manifest { - from 'src/main/resources/META-INF/MANIFEST.MF' - } -} - -////////// -// Test // -////////// -sourceSets { - // Use JAR file with all resources for Eclipse-WTP integration-tests - test.runtimeClasspath = jar.outputs.files + sourceSets.test.output + sourceSets.test.compileClasspath -} - -/* - * All test classes need to run separately since they all instatiate different setups of the - * Eclipse framework. - */ -tasks.withType(Test).configureEach { - //Skip default tests, which would run every test case. - exclude '**' -} - -//Instead make a separate test task per case -def testLocation = 'src/test/java' -fileTree(dir: testLocation).include('**/*Test.java').each { file -> - def testFile = file.getName().replace(".java", "") - def filePath = file.getAbsolutePath().replace(".java", "**") //Don't ask me why the task is not happy when it gets no asterisk - filePath = filePath.substring(filePath.lastIndexOf(testLocation) + testLocation.length() + 1) - task "${testFile}"(type: Test) { - group = LifecycleBasePlugin.VERIFICATION_GROUP - description = "Runs ${testFile} integration test." - include "${filePath}" - reports { - html.destination = new File("$buildDir/reports/${testFile}") - junitXml.destination = new File("$buildDir/${testFile}") - } - //classpath = jar.outputs.files + sourceSets.test.output + sourceSets.test.compileClasspath - mustRunAfter tasks.jar - } - test.dependsOn "${testFile}" -} diff --git a/_ext/eclipse-wtp/gradle.properties b/_ext/eclipse-wtp/gradle.properties deleted file mode 100644 index a341c0fb49..0000000000 --- a/_ext/eclipse-wtp/gradle.properties +++ /dev/null @@ -1,16 +0,0 @@ -artifactId=spotless-eclipse-wtp -description=Eclipse's WTP formatters bundled for Spotless - -# Build requirements -VER_JAVA=11 - -# Compile -VER_ECLIPSE_WTP=2021-09 -VER_SPOTLESS_ECLIPSE_BASE=[3.5.0,4.0.0[ -VER_IBM_ICU=[67.1,68[ -VER_ECLIPSE_EMF=[2.22.0,3.0.0[ -VER_ECLIPSE_OSGI_SERVICES=[3.10.0,4.0.0[ -VER_ECLIPSE_FILE_BUFFERS=[3.7.0,4.0.0[ -VER_ECLIPSE_JFACE=[3.18.0,4.0.0[ -VER_ECLIPSE_EFS=[1.9.0,2.0.0[ -VER_ECLIPSE_XSD=[2.18.0,3.0.0[ diff --git a/_ext/eclipse-wtp/spotless.xmlformat.prefs b/_ext/eclipse-wtp/spotless.xmlformat.prefs deleted file mode 100644 index 3bbd7ecd72..0000000000 --- a/_ext/eclipse-wtp/spotless.xmlformat.prefs +++ /dev/null @@ -1,4 +0,0 @@ -eclipse.preferences.version=1 -indentationChar=space -indentationSize=2 -lineWidth=999 diff --git a/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseCssFormatterStepImpl.java b/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseCssFormatterStepImpl.java deleted file mode 100644 index fb0e1ffeac..0000000000 --- a/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseCssFormatterStepImpl.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.wtp; - -import java.util.Properties; - -import org.eclipse.wst.css.core.internal.CSSCorePlugin; -import org.eclipse.wst.css.core.internal.cleanup.CleanupProcessorCSS; -import org.eclipse.wst.css.core.internal.preferences.CSSCorePreferenceInitializer; -import org.eclipse.wst.sse.core.internal.cleanup.AbstractStructuredCleanupProcessor; - -import com.diffplug.spotless.extra.eclipse.base.SpotlessEclipsePluginConfig; -import com.diffplug.spotless.extra.eclipse.wtp.sse.CleanupStep; -import com.diffplug.spotless.extra.eclipse.wtp.sse.PluginPreferences; - -/** Formatter step which calls out to the Eclipse CSS cleanup and formatter. */ -public class EclipseCssFormatterStepImpl extends CleanupStep { - - public EclipseCssFormatterStepImpl(Properties properties) throws Exception { - super(new CleanupProcessor(), new FrameworkConfig(properties)); - PluginPreferences.assertNoChanges(CSSCorePlugin.getDefault(), properties); - } - - /** - * The FormatProcessorCSS does not allow a strict case formatting. - * Hence additionally the CleanupProcessorCSS is used. - */ - private static class CleanupProcessor extends CleanupProcessorCSS implements CleanupStep.ProcessorAccessor { - @Override - public String getTypeId() { - return getContentType(); - } - - @Override - public void refreshPreferences() { - refreshCleanupPreferences(); - } - - @Override - public AbstractStructuredCleanupProcessor get() { - return this; - } - } - - static class FrameworkConfig extends CleanupStep.FrameworkConfig { - private final Properties properties; - - FrameworkConfig(Properties properties) { - this.properties = properties; - } - - @Override - public void activatePlugins(SpotlessEclipsePluginConfig config) { - super.activatePlugins(config); - activateCssPlugins(config); - } - - static void activateCssPlugins(SpotlessEclipsePluginConfig config) { - config.add(new CSSCorePlugin()); - } - - @Override - public void customize() { - PluginPreferences.configure(CSSCorePlugin.getDefault(), new CSSCorePreferenceInitializer(), properties); - } - } -} diff --git a/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseHtmlFormatterStepImpl.java b/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseHtmlFormatterStepImpl.java deleted file mode 100644 index 4b7f592c3c..0000000000 --- a/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseHtmlFormatterStepImpl.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.wtp; - -import static com.diffplug.spotless.extra.eclipse.base.SpotlessEclipseFramework.LINE_DELIMITER; - -import java.util.Arrays; -import java.util.List; -import java.util.Properties; - -import org.eclipse.wst.html.core.internal.HTMLCorePlugin; -import org.eclipse.wst.html.core.internal.cleanup.HTMLCleanupProcessorImpl; -import org.eclipse.wst.html.core.internal.encoding.HTMLDocumentLoader; -import org.eclipse.wst.html.core.internal.format.HTMLFormatProcessorImpl; -import org.eclipse.wst.html.core.internal.preferences.HTMLCorePreferenceInitializer; -import org.eclipse.wst.html.core.text.IHTMLPartitions; -import org.eclipse.wst.jsdt.core.JavaScriptCore; -import org.eclipse.wst.jsdt.core.ToolFactory; -import org.eclipse.wst.jsdt.core.formatter.CodeFormatter; -import org.eclipse.wst.sse.core.internal.cleanup.AbstractStructuredCleanupProcessor; -import org.eclipse.wst.sse.core.internal.format.IStructuredFormatProcessor; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; - -import com.diffplug.spotless.extra.eclipse.base.SpotlessEclipseConfig; -import com.diffplug.spotless.extra.eclipse.base.SpotlessEclipseCoreConfig; -import com.diffplug.spotless.extra.eclipse.base.SpotlessEclipsePluginConfig; -import com.diffplug.spotless.extra.eclipse.wtp.html.JsRegionProcessor; -import com.diffplug.spotless.extra.eclipse.wtp.html.StructuredDocumentProcessor; -import com.diffplug.spotless.extra.eclipse.wtp.sse.CleanupStep; -import com.diffplug.spotless.extra.eclipse.wtp.sse.PluginPreferences; - -/** Formatter step which calls out to the Eclipse HTML cleanup and formatter. */ -public class EclipseHtmlFormatterStepImpl extends CleanupStep { - - private final String htmlFormatterIndent; - private final CodeFormatter jsFormatter; - - public EclipseHtmlFormatterStepImpl(Properties properties) throws Exception { - super(new CleanupProcessor(), new FrameworkConfig(properties)); - PluginPreferences.assertNoChanges(HTMLCorePlugin.getDefault(), properties); - htmlFormatterIndent = ((CleanupProcessor) processorAccessor).getIndent(); - jsFormatter = ToolFactory.createCodeFormatter(JavaScriptCore.getOptions(), ToolFactory.M_FORMAT_EXISTING); - } - - @Override - public String format(String raw) throws Exception { - raw = super.format(raw); - - // Not sure how Eclipse binds the JS formatter to HTML. The formatting is accomplished manually instead. - IStructuredDocument document = (IStructuredDocument) new HTMLDocumentLoader().createNewStructuredDocument(); - document.setPreferredLineDelimiter(LINE_DELIMITER); - document.set(raw); - StructuredDocumentProcessor jsProcessor = new StructuredDocumentProcessor( - document, IHTMLPartitions.SCRIPT, JsRegionProcessor.createFactory(htmlFormatterIndent)); - jsProcessor.apply(jsFormatter); - - return document.get(); - } - - /** - * * The WTP {@link HTMLFormatProcessorImpl} does not allow a strict case formatting. - * Hence additionally the {@link HTMLCleanupProcessorImpl} is used. - *

- * Note that a preferences like {@code TAG_NAME_CASE} are not used by the - * formatter, though configurable in the formatters preference GUI. - * The user must instead configure for example {@code CLEANUP_TAG_NAME_CASE} - * in the cleanup GUI. - *

- */ - private static class CleanupProcessor extends HTMLCleanupProcessorImpl implements CleanupStep.ProcessorAccessor { - private HTMLFormatProcessorImpl processor; - - CleanupProcessor() { - processor = new HTMLFormatProcessorImpl(); - } - - @Override - public String getTypeId() { - return getContentType(); - } - - @Override - public void refreshPreferences() { - refreshCleanupPreferences(); - processor = new HTMLFormatProcessorImpl(); //Constructor reads new preferences - processor.refreshFormatPreferences = false; //Don't refresh when cloning - } - - @Override - public AbstractStructuredCleanupProcessor get() { - return this; - } - - @Override - protected IStructuredFormatProcessor getFormatProcessor() { - return processor; - } - - String getIndent() { - return processor.getFormatPreferences().getIndent(); - } - - } - - private static class FrameworkConfig extends CleanupStep.FrameworkConfig { - private final List dependentConfigs; - private final Properties properties; - - public FrameworkConfig(Properties properties) { - dependentConfigs = Arrays.asList( - new EclipseCssFormatterStepImpl.FrameworkConfig(properties), - new EclipseJsFormatterStepImpl.FrameworkConfig(properties), - new EclipseXmlFormatterStepImpl.FrameworkConfig(properties)); - this.properties = properties; - } - - @Override - public void registerBundles(SpotlessEclipseCoreConfig config) { - EclipseJsFormatterStepImpl.FrameworkConfig.registerNonHeadlessBundles(config); - } - - @Override - public void activatePlugins(SpotlessEclipsePluginConfig config) { - super.activatePlugins(config); - EclipseCssFormatterStepImpl.FrameworkConfig.activateCssPlugins(config); - EclipseJsFormatterStepImpl.FrameworkConfig.activateJsPlugins(config); - /* - * The HTML formatter only uses the DOCTYPE/SCHEMA for content model selection. - * Hence no external URIs are required. - */ - boolean allowExternalURI = false; - EclipseXmlFormatterStepImpl.FrameworkConfig.activateXmlPlugins(config, allowExternalURI); - config.add(new HTMLCorePlugin()); - } - - @Override - public void customize() { - dependentConfigs.stream().forEach(c -> { - c.customize(); - }); - PluginPreferences.configure(HTMLCorePlugin.getDefault(), new HTMLCorePreferenceInitializer(), properties); - } - - } - -} diff --git a/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseJsFormatterStepImpl.java b/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseJsFormatterStepImpl.java deleted file mode 100644 index c101b1a27a..0000000000 --- a/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseJsFormatterStepImpl.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.wtp; - -import static com.diffplug.spotless.extra.eclipse.base.SpotlessEclipseFramework.DefaultBundles.*; -import static com.diffplug.spotless.extra.eclipse.base.SpotlessEclipseFramework.LINE_DELIMITER; - -import java.util.AbstractMap.SimpleEntry; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.Document; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IDocumentPartitioner; -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.jface.text.TextUtilities; -import org.eclipse.jface.text.TypedPosition; -import org.eclipse.jface.text.formatter.FormattingContextProperties; -import org.eclipse.jface.text.formatter.IFormattingContext; -import org.eclipse.jface.text.rules.FastPartitioner; -import org.eclipse.text.edits.MultiTextEdit; -import org.eclipse.text.edits.TextEdit; -import org.eclipse.wst.jsdt.core.JavaScriptCore; -import org.eclipse.wst.jsdt.core.ToolFactory; -import org.eclipse.wst.jsdt.core.formatter.CodeFormatter; -import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants; -import org.eclipse.wst.jsdt.internal.ui.text.FastJavaPartitionScanner; -import org.eclipse.wst.jsdt.internal.ui.text.comment.CommentFormattingContext; -import org.eclipse.wst.jsdt.internal.ui.text.comment.CommentFormattingStrategy; -import org.eclipse.wst.jsdt.ui.text.IJavaScriptPartitions; -import org.osgi.framework.Bundle; - -import com.diffplug.spotless.extra.eclipse.base.SpotlessEclipseConfig; -import com.diffplug.spotless.extra.eclipse.base.SpotlessEclipseCoreConfig; -import com.diffplug.spotless.extra.eclipse.base.SpotlessEclipseFramework; -import com.diffplug.spotless.extra.eclipse.base.SpotlessEclipsePluginConfig; -import com.diffplug.spotless.extra.eclipse.base.SpotlessEclipseServiceConfig; -import com.diffplug.spotless.extra.eclipse.wtp.sse.PluginPreferences; - -/** Formatter step which calls out to the Eclipse JS formatter. */ -public class EclipseJsFormatterStepImpl { - - private final static String[] COMMENT_TYPES = { - IJavaScriptPartitions.JAVA_DOC, - IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT, - IJavaScriptPartitions.JAVA_SINGLE_LINE_COMMENT, - IJavaScriptPartitions.JAVA_STRING, - IJavaScriptPartitions.JAVA_CHARACTER - }; - - private final static Map OPTION_2_COMMENT_TYPE = Collections.unmodifiableMap(Stream.of( - new SimpleEntry<>(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_LINE_COMMENT, IJavaScriptPartitions.JAVA_SINGLE_LINE_COMMENT), - new SimpleEntry<>(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_BLOCK_COMMENT, IJavaScriptPartitions.JAVA_MULTI_LINE_COMMENT), - new SimpleEntry<>(DefaultCodeFormatterConstants.FORMATTER_COMMENT_FORMAT_JAVADOC_COMMENT, IJavaScriptPartitions.JAVA_DOC)).collect(Collectors.toMap((e) -> e.getKey(), (e) -> e.getValue()))); - - private final CodeFormatter formatter; - private final Hashtable options; - private final Set commentTypesToBeFormatted; - - public EclipseJsFormatterStepImpl(Properties properties) throws Exception { - SpotlessEclipseFramework.setup(new FrameworkConfig(properties)); - PluginPreferences.assertNoChanges(JavaScriptCore.getPlugin(), properties); - options = JavaScriptCore.getOptions(); - commentTypesToBeFormatted = OPTION_2_COMMENT_TYPE.entrySet().stream().filter(x -> DefaultCodeFormatterConstants.TRUE.equals(options.get(x.getKey()))).map(x -> x.getValue()).collect(Collectors.toSet()); - formatter = ToolFactory.createCodeFormatter(options, ToolFactory.M_FORMAT_EXISTING); - } - - /** Formatting JavaScript string */ - public String format(String raw) throws Exception { - raw = formatComments(raw); - // The comment formatter messed up the code a little bit (adding some line breaks). Now we format the code. - IDocument doc = new Document(raw); - TextEdit edit = formatter.format(CodeFormatter.K_JAVASCRIPT_UNIT, raw, 0, raw.length(), 0, LINE_DELIMITER); - if (edit == null) { - throw new IllegalArgumentException("Invalid JavaScript syntax for formatting."); - } else { - edit.apply(doc); - } - return doc.get(); - } - - /** - * Comment formats like it would be accomplished by the JDTS UI, without setting up the UI. - * @see org.eclipse.wst.jsdt.internal.ui.fix.CommentFormatFix - */ - private String formatComments(String raw) { - Document doc = new Document(raw); - IDocumentPartitioner commentPartitioner = new FastPartitioner(new FastJavaPartitionScanner(), COMMENT_TYPES); - doc.setDocumentPartitioner(IJavaScriptPartitions.JAVA_PARTITIONING, commentPartitioner); - commentPartitioner.connect(doc); - CommentFormattingStrategy commentFormatter = new CommentFormattingStrategy(); - IFormattingContext context = new CommentFormattingContext(); - context.setProperty(FormattingContextProperties.CONTEXT_PREFERENCES, options); - context.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.TRUE); - context.setProperty(FormattingContextProperties.CONTEXT_MEDIUM, doc); - try { - ITypedRegion[] regions = TextUtilities.computePartitioning(doc, IJavaScriptPartitions.JAVA_PARTITIONING, 0, doc.getLength(), false); - MultiTextEdit resultEdit = new MultiTextEdit(); - Arrays.asList(regions).stream().filter(reg -> commentTypesToBeFormatted.contains(reg.getType())).forEach(region -> { - TypedPosition typedPosition = new TypedPosition(region.getOffset(), region.getLength(), region.getType()); - context.setProperty(FormattingContextProperties.CONTEXT_PARTITION, typedPosition); - commentFormatter.formatterStarts(context); - TextEdit edit = commentFormatter.calculateTextEdit(); - commentFormatter.formatterStops(); - if (null != edit && edit.hasChildren()) { - resultEdit.addChild(edit); - } - }); - resultEdit.apply(doc); - return doc.get(); - } catch (BadLocationException e) { - //Silently ignore comment formatting exceptions and return the original string - return raw; - } - } - - static class FrameworkConfig implements SpotlessEclipseConfig { - private final Properties properties; - - FrameworkConfig(Properties properties) { - this.properties = properties; - } - - @Override - public void registerServices(SpotlessEclipseServiceConfig config) { - config.applyDefault(); - config.useSlf4J(this.getClass().getPackage().getName()); - } - - @Override - public void registerBundles(SpotlessEclipseCoreConfig config) { - registerNonHeadlessBundles(config); - } - - static void registerNonHeadlessBundles(SpotlessEclipseCoreConfig config) { - //The JS model requires the JDT indexer, hence a headless Eclipse cannot be used. - config.add(PLATFORM, Bundle.ACTIVE); - config.add(REGISTRY, PREFERENCES, COMMON); - } - - @Override - public void activatePlugins(SpotlessEclipsePluginConfig config) { - config.applyDefault(); - activateJsPlugins(config); - } - - static void activateJsPlugins(SpotlessEclipsePluginConfig config) { - // The JS core uses EFS for determination of temporary storage location - config.add(org.eclipse.core.filesystem.EFS.class); - // The JS core provides the JSDT formatter - config.add(new org.eclipse.wst.jsdt.core.JavaScriptCore()); - } - - @Override - @SuppressWarnings("unchecked") - public void customize() { - PluginPreferences.store(JavaScriptCore.getPlugin(), properties); - Hashtable options = JavaScriptCore.getDefaultOptions(); - options.putAll(DefaultCodeFormatterConstants.getJSLintConventionsSettings()); - options.putAll(new HashMap(properties)); - JavaScriptCore.setOptions(options); - } - - } - -} diff --git a/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseJsonFormatterStepImpl.java b/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseJsonFormatterStepImpl.java deleted file mode 100644 index 91d8516b24..0000000000 --- a/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseJsonFormatterStepImpl.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.wtp; - -import java.io.IOException; -import java.util.Properties; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.wst.json.core.JSONCorePlugin; -import org.eclipse.wst.json.core.cleanup.CleanupProcessorJSON; -import org.eclipse.wst.json.core.format.FormatProcessorJSON; -import org.eclipse.wst.json.core.internal.preferences.JSONCorePreferenceInitializer; -import org.eclipse.wst.sse.core.internal.cleanup.AbstractStructuredCleanupProcessor; - -import com.diffplug.spotless.extra.eclipse.base.SpotlessEclipsePluginConfig; -import com.diffplug.spotless.extra.eclipse.wtp.sse.CleanupStep; -import com.diffplug.spotless.extra.eclipse.wtp.sse.PluginPreferences; - -/** - * Formatter step which calls out to the Eclipse JSON cleanup processor and formatter. - * Note that the cleanup is escaped, since it has known bugs and is currently not used by Eclipse. - */ -public class EclipseJsonFormatterStepImpl extends CleanupStep { - - public EclipseJsonFormatterStepImpl(Properties properties) throws Exception { - super(new CleanupProcessor(), new FrameworkConfig(properties)); - PluginPreferences.assertNoChanges(JSONCorePlugin.getDefault(), properties); - } - - /** - * The JSON CleanUp is partly implemented. - *

- * For example the abstract formatter supports the - * CASE_PROPERTY_NAME configuration item. - * However, this seems to be all dead code and there seems - * to be no way in the latest Eclipse GUI to configure - * or trigger the clean-up process. - *

- *

- * Here we just use the CleanupProcessorJSON to reuse the common - * interface to trigger the formatting. - *

- * See {@code org.eclipse.wst.json.core.internal.format.AbstractJSONSourceFormatter} for details. - */ - private static class CleanupProcessor extends CleanupProcessorJSON implements CleanupStep.ProcessorAccessor { - private final FormatProcessorJSON formatter; - - CleanupProcessor() { - formatter = new FormatProcessorJSON(); - } - - @Override - public String getTypeId() { - return getContentType(); - } - - @Override - public AbstractStructuredCleanupProcessor get() { - return this; - } - - @Override - public void refreshPreferences() { - refreshCleanupPreferences(); - } - - @Override - public String cleanupContent(String input) throws IOException, CoreException { - /* - * The CleanupProcessorJSON.cleanupContent is erroneous and disabled in IDE. - * Hence the clean-up itself is replaced by a format processor. - * The SpotlessJsonCleanup still derives from the CleanupStep base class - * to use the common Spotless WTP configuration. - * - * See Spotless issue #344 for details. - */ - return formatter.formatContent(input); - } - } - - private static class FrameworkConfig extends CleanupStep.FrameworkConfig { - private final Properties properties; - - FrameworkConfig(Properties properties) { - this.properties = properties; - } - - @Override - public void activatePlugins(SpotlessEclipsePluginConfig config) { - super.activatePlugins(config); - config.add(new JSONCorePlugin()); - } - - @Override - public void customize() { - PluginPreferences.configure(JSONCorePlugin.getDefault(), new JSONCorePreferenceInitializer(), properties); - } - } - -} diff --git a/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseXmlFormatterStepImpl.java b/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseXmlFormatterStepImpl.java deleted file mode 100644 index 57fce0d503..0000000000 --- a/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseXmlFormatterStepImpl.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.wtp; - -import static com.diffplug.spotless.extra.eclipse.base.SpotlessEclipseFramework.LINE_DELIMITER; -import static org.eclipse.wst.xml.core.internal.preferences.XMLCorePreferenceNames.*; - -import java.util.Properties; - -import org.eclipse.jface.text.IDocumentPartitioner; -import org.eclipse.text.edits.TextEdit; -import org.eclipse.wst.common.uriresolver.internal.provisional.URIResolverPlugin; -import org.eclipse.wst.dtd.core.internal.DTDCorePlugin; -import org.eclipse.wst.sse.core.internal.provisional.INodeAdapterFactory; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; -import org.eclipse.wst.sse.core.internal.text.BasicStructuredDocument; -import org.eclipse.wst.xml.core.internal.XMLCorePlugin; -import org.eclipse.wst.xml.core.internal.catalog.Catalog; -import org.eclipse.wst.xml.core.internal.contentmodel.modelquery.CMDocumentManager; -import org.eclipse.wst.xml.core.internal.contentmodel.modelquery.ModelQuery; -import org.eclipse.wst.xml.core.internal.document.DOMModelImpl; -import org.eclipse.wst.xml.core.internal.formatter.DefaultXMLPartitionFormatter; -import org.eclipse.wst.xml.core.internal.formatter.XMLFormattingPreferences; -import org.eclipse.wst.xml.core.internal.modelquery.ModelQueryAdapterFactoryForXML; -import org.eclipse.wst.xml.core.internal.modelquery.ModelQueryUtil; -import org.eclipse.wst.xml.core.internal.parser.XMLSourceParser; -import org.eclipse.wst.xml.core.internal.preferences.XMLCorePreferenceInitializer; -import org.eclipse.wst.xml.core.internal.text.rules.StructuredTextPartitionerForXML; -import org.eclipse.wst.xsd.core.internal.XSDCorePlugin; -import org.eclipse.xsd.util.XSDSchemaBuildingTools; - -import com.diffplug.spotless.extra.eclipse.base.SpotlessEclipseConfig; -import com.diffplug.spotless.extra.eclipse.base.SpotlessEclipseFramework; -import com.diffplug.spotless.extra.eclipse.base.SpotlessEclipsePluginConfig; -import com.diffplug.spotless.extra.eclipse.base.SpotlessEclipseServiceConfig; -import com.diffplug.spotless.extra.eclipse.wtp.sse.PluginPreferences; -import com.diffplug.spotless.extra.eclipse.wtp.sse.PreventExternalURIResolverExtension; - -/** Formatter step which calls out to the Eclipse XML formatter. */ -public class EclipseXmlFormatterStepImpl { - private final DefaultXMLPartitionFormatter formatter; - private final XMLFormattingPreferences preferences; - private final INodeAdapterFactory xmlAdapterFactory; - - public EclipseXmlFormatterStepImpl(Properties properties) throws Exception { - SpotlessEclipseFramework.setup(new FrameworkConfig(properties)); - PluginPreferences.assertNoChanges(XMLCorePlugin.getDefault(), properties); - preferences = new XMLFormattingPreferences(); - formatter = new DefaultXMLPartitionFormatter(); - //The adapter factory maintains the common CMDocumentCache - xmlAdapterFactory = new ModelQueryAdapterFactoryForXML(); - } - - static class FrameworkConfig implements SpotlessEclipseConfig { - private final Properties properties; - - FrameworkConfig(Properties properties) { - /* - * The cache is only used for system catalogs, but not for user catalogs. - * It requires the SSECorePLugin, which has either a big performance overhead, - * or needs a dirty mocking (we don't really require its functions but it needs to be there). - * So we disable the cache for now. - * This might cause a performance drop in case for example XSDs are formatted. - * But these standard/system restriction files contain anyway no formatting rules. - * So in case of performance inconveniences, we could add a Spotless property to disable the - * XSD/DTD parsing entirely (for example by adding an own URI resolver). - */ - properties.setProperty(CMDOCUMENT_GLOBAL_CACHE_ENABLED, Boolean.toString(false)); - this.properties = properties; - } - - @Override - public void registerServices(SpotlessEclipseServiceConfig config) { - config.applyDefault(); - config.useSlf4J(EclipseXmlFormatterStepImpl.class.getPackage().getName()); - } - - @Override - public void activatePlugins(SpotlessEclipsePluginConfig config) { - config.applyDefault(); - activateXmlPlugins(config, PluginPreferences.isExternalUriAllowed(properties)); - } - - static void activateXmlPlugins(SpotlessEclipsePluginConfig config, boolean allowExternalURI) { - //The WST XML formatter - config.add(new XMLCorePlugin()); - //XSDs/DTDs must be resolved by URI - config.add(new URIResolverPlugin()); - //Support formatting based on DTD restrictions - config.add(new DTDCorePlugin()); - //Support formatting based on XSD restrictions - config.add(new XSDCorePlugin()); - if (!allowExternalURI) { - config.add(new PreventExternalURIResolverExtension()); - } - } - - @Override - public void customize() { - //Register required EMF factories - XSDSchemaBuildingTools.getXSDFactory(); - PluginPreferences.configure(XMLCorePlugin.getDefault(), new XMLCorePreferenceInitializer(), properties); - PluginPreferences.configureCatalog(properties, (Catalog) XMLCorePlugin.getDefault().getDefaultXMLCatalog()); - } - - }; - - /** Formatting XML string resolving URIs according its base location */ - public String format(String raw, String baseLocation) throws Exception { - IStructuredDocument document = new BasicStructuredDocument(new XMLSourceParser()); - document.setPreferredLineDelimiter(LINE_DELIMITER); - IDocumentPartitioner partitioner = new StructuredTextPartitionerForXML(); - document.setDocumentPartitioner(new StructuredTextPartitionerForXML()); - partitioner.connect(document); - document.set(raw); - DOMModelImpl xmlDOM = new DOMModelImpl(); - xmlDOM.setBaseLocation(baseLocation); - xmlDOM.getFactoryRegistry().addFactory(xmlAdapterFactory); - xmlDOM.setStructuredDocument(document); - ModelQuery modelQuery = ModelQueryUtil.getModelQuery(xmlDOM); - modelQuery.getCMDocumentManager().setPropertyEnabled(CMDocumentManager.PROPERTY_USE_CACHED_RESOLVED_URI, true); - TextEdit formatterChanges = formatter.format(xmlDOM, 0, document.getLength(), preferences); - formatterChanges.apply(document); - return document.get(); - } - -} diff --git a/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/html/JsRegionProcessor.java b/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/html/JsRegionProcessor.java deleted file mode 100644 index d856335c1b..0000000000 --- a/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/html/JsRegionProcessor.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.wtp.html; - -import static com.diffplug.spotless.extra.eclipse.base.SpotlessEclipseFramework.LINE_DELIMITER; - -import java.util.function.BiFunction; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.text.edits.MalformedTreeException; -import org.eclipse.text.edits.MultiTextEdit; -import org.eclipse.text.edits.TextEdit; -import org.eclipse.wst.jsdt.core.formatter.CodeFormatter; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; - -import com.diffplug.spotless.extra.eclipse.wtp.html.StructuredDocumentProcessor.RegionProcessor; - -/** - * Provides additional formating to the plain JS {@link CodeFormatter}: - *
    - *
  • Eclipse HTML places the embedded JS in separated lines by adding a line break after/before <script/> tag.
  • - *
  • Eclipse HTML treats the text before the closing </script> tag as part of the script region.
  • - *
- *

- * Note that the closing tag is indented by Eclipse using the embedded formatters indentation, - * whereas the opening tag indentation is configured by the HTML preferences. - * This is more a bug than a feature, but Spotless formatter output shall be identical - * to the one of Eclipse. - *

- */ -public class JsRegionProcessor extends RegionProcessor { - public JsRegionProcessor(IStructuredDocument document, ITypedRegion scriptRegion, String htmlIndent) { - super(document, scriptRegion, htmlIndent); - } - - @Override - protected void applyFirst(CodeFormatter formatter) throws MalformedTreeException, BadLocationException { - MultiTextEdit modifications = new MultiTextEdit(); - String jsSource = document.get(region.getOffset(), region.getLength()); - TextEdit jsEdit = formatter.format(CodeFormatter.K_JAVASCRIPT_UNIT, jsSource, 0, jsSource.length(), indentationLevel + 1, LINE_DELIMITER); - if (null != jsEdit) { - jsEdit.moveTree(region.getOffset()); - modifications.addChild(jsEdit); - } - modifications.apply(document); - } - - @Override - protected void applySecond(CodeFormatter formatter) throws MalformedTreeException, BadLocationException { - MultiTextEdit modifications = new MultiTextEdit(); - int regionEnd = region.getOffset() + region.getLength(); - regionEnd += fixDelimiter(modifications, region.getOffset(), false); - regionEnd += fixDelimiter(modifications, region.getOffset() + region.getLength() - 1, true); - modifications.apply(document); - modifications.removeChildren(); - fixTagIndent(modifications, regionEnd, formatter.createIndentationString(indentationLevel)); - modifications.apply(document); - } - - /** Factory for {@link StructuredDocumentProcessor}*/ - public static BiFunction createFactory(String htmlIndent) { - return new BiFunction() { - - @Override - public JsRegionProcessor apply(IStructuredDocument document, ITypedRegion region) { - return new JsRegionProcessor(document, region, htmlIndent); - } - - }; - } - -} diff --git a/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/html/StructuredDocumentProcessor.java b/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/html/StructuredDocumentProcessor.java deleted file mode 100644 index 6adc258c78..0000000000 --- a/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/html/StructuredDocumentProcessor.java +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.wtp.html; - -import static com.diffplug.spotless.extra.eclipse.base.SpotlessEclipseFramework.LINE_DELIMITER; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.function.BiFunction; -import java.util.stream.Collectors; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.ITypedRegion; -import org.eclipse.text.edits.InsertEdit; -import org.eclipse.text.edits.MalformedTreeException; -import org.eclipse.text.edits.MultiTextEdit; -import org.eclipse.text.edits.ReplaceEdit; -import org.eclipse.text.edits.TextEdit; -import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument; - -/** - * The HTML formatter uses for different regions of the structured document, - * other formatters, explicitly for CSS and JS. - * Adaptations of the current formatter modifications are tedious, - * since the adaptations e.g. overlap with the required additional modifications. - * Hence the modifications is split in steps, whereas the regions of the - * structured documents and their offsets are regenerate between the first - * ad second step. - */ -public class StructuredDocumentProcessor { - private final String type; - private final BiFunction> factory; - private final IStructuredDocument document; - private final int numberOfRegions; - - /** - * Constructs a document processor - * @param document Document to be processed - * @param type Document type ID recognized by {@code IContentTypeManager} service - * @param factory Factory for structured document processor - */ - public StructuredDocumentProcessor(IStructuredDocument document, String type, - BiFunction> factory) { - this.type = type; - this.factory = factory; - this.document = document; - numberOfRegions = getRegions().size(); - } - - /** Applies processor on document, using a given formatter */ - public void apply(T formatter) { - for (int currentRegionId = 0; currentRegionId < numberOfRegions; currentRegionId++) { - applyOnRegion(currentRegionId, formatter); - } - } - - private List getRegions() { - try { - return Arrays.asList(document.computePartitioning(0, document.getLength())).stream().filter(reg -> type == reg.getType()).collect(Collectors.toList()); - } catch (BadLocationException e) { - /* - * This prevents the processing in case the entire document - * cannot be processed (e.g. the document is incomplete). - */ - return new ArrayList(0); - } - } - - private void applyOnRegion(int number, T formatter) { - RegionProcessor adapter = getRegionProcessor(number); - try { - adapter.applyFirst(formatter); - adapter = getRegionProcessor(number); - adapter.applySecond(formatter); - } catch (MalformedTreeException | BadLocationException e) { - throw new IllegalArgumentException( - String.format("%s formatting failed between lines %d and %d. Most likely the syntax is not recognized.", - type, adapter.getFirstLine(), adapter.getLastLine()), - e); - } - } - - private RegionProcessor getRegionProcessor(int number) { - List regions = getRegions(); - if (numberOfRegions != regions.size()) { - //Don't catch this. This is a severe internal bug! - throw new IllegalArgumentException( - String.format( - "During first '%s' formatting step, the number of detected regions changed from '%d' to '%d'", - type, numberOfRegions, regions.size())); - } - ITypedRegion region = regions.get(number); - return factory.apply(document, region); - } - - /** Base class for region adaptations. */ - public static abstract class RegionProcessor { - protected final IStructuredDocument document; - protected final ITypedRegion region; - protected final int indentationLevel; - protected final int firstLine; - protected final int lastLine; - - protected RegionProcessor(IStructuredDocument document, ITypedRegion region, String htmlIndent) { - this.document = document; - this.region = region; - indentationLevel = computeIndent(document, region, htmlIndent); - firstLine = document.getLineOfOffset(region.getOffset()); - lastLine = document.getLineOfOffset(region.getOffset() + region.getLength()); - } - - public int getFirstLine() { - return firstLine; - } - - public int getLastLine() { - return lastLine; - } - - private static int computeIndent(IStructuredDocument document, ITypedRegion region, String htmlIndent) { - int indent = 0; - try { - int lineNumber = document.getLineOfOffset(region.getOffset()); - document.getNumberOfLines(); - int lineOffset = document.getLineOffset(lineNumber); - String lineStart = document.get(lineOffset, region.getOffset() - lineOffset); - while (lineStart.length() > htmlIndent.length()) { - if (lineStart.startsWith(htmlIndent)) { - indent++; - } else { - break; - } - lineStart = lineStart.substring(htmlIndent.length()); - } - } catch (BadLocationException e) { - /* - * Skip addition indentation. This normally indicates a malformed HTML - * outside of this region, which cannot be handled here. - */ - indent = 0; - } - return indent; - } - - /** Add delimiter at or after given offset, if there is none at the offset position. Returns the number of characters inserted. */ - protected int fixDelimiter(MultiTextEdit modifications, int offset, boolean addAfter) throws BadLocationException { - int delimiterLength = LINE_DELIMITER.length(); - String delimiter = document.get(offset, delimiterLength); - if (!LINE_DELIMITER.equals(delimiter)) { - if (addAfter) { - offset += 1; - } - modifications.addChild(new InsertEdit(offset, LINE_DELIMITER)); - return LINE_DELIMITER.length(); - } - return 0; - } - - /** Fix the tag indentation at a given position with a predefined indentation. */ - protected void fixTagIndent(MultiTextEdit modifications, int offset, String indentString) throws BadLocationException { - int lineNumber = document.getLineOfOffset(offset); - if (lineNumber >= document.getNumberOfLines()) { - //Nothing to change for last line. If syntax is correct, there is no indentation. If syntax is not correct, there is nothing to do. - return; - } - int lineStart = document.getLineOffset(lineNumber); - int lineEnd = document.getLineOffset(lineNumber + 1); - String lineContent = document.get(lineStart, lineEnd - lineStart); - StringBuilder currentIndent = new StringBuilder(); - lineContent.chars().filter(c -> { - if (c == ' ' || c == '\t') { - currentIndent.append(c); - return false; - } - return true; - }).findFirst(); - if (!indentString.equals(currentIndent.toString())) { - TextEdit replaceIndent = new ReplaceEdit(lineStart, currentIndent.length(), indentString); - replaceIndent.apply(document); - } - } - - /** First application of modifications */ - abstract protected void applyFirst(T formatter) throws MalformedTreeException, BadLocationException; - - /** Second application of modifications (based on new regions) */ - abstract protected void applySecond(T formatter) throws MalformedTreeException, BadLocationException; - - } - -} diff --git a/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/html/package-info.java b/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/html/package-info.java deleted file mode 100644 index 770e126a1b..0000000000 --- a/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/html/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** Eclipse WTP HTML formatter helper */ -@ParametersAreNonnullByDefault -package com.diffplug.spotless.extra.eclipse.wtp.html; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/package-info.java b/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/package-info.java deleted file mode 100644 index 6cf6f0bfff..0000000000 --- a/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** Eclipse WTP based Spotless formatters */ -@ParametersAreNonnullByDefault -package com.diffplug.spotless.extra.eclipse.wtp; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/sse/CleanupStep.java b/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/sse/CleanupStep.java deleted file mode 100644 index 01be583bd8..0000000000 --- a/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/sse/CleanupStep.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.wtp.sse; - -import org.eclipse.core.internal.preferences.PreferencesService; -import org.eclipse.core.runtime.content.IContentTypeManager; -import org.eclipse.core.runtime.preferences.IPreferencesService; -import org.eclipse.wst.sse.core.internal.cleanup.AbstractStructuredCleanupProcessor; - -import com.diffplug.spotless.extra.eclipse.base.SpotlessEclipseConfig; -import com.diffplug.spotless.extra.eclipse.base.SpotlessEclipseFramework; -import com.diffplug.spotless.extra.eclipse.base.SpotlessEclipsePluginConfig; -import com.diffplug.spotless.extra.eclipse.base.SpotlessEclipseServiceConfig; - -/** - * Common base class for step implementations based on an SSE cleanup processor. - *

- * Some WTP formatters do not apply all formatting within a formatter process, - * but provide a cleanup and a formatter process, whereas the cleanup process - * calls the formatter process. - *

- *

- * Not all cleanup processes provided by WTP are suitable for Spotless formatting. - * For example the XML cleanup processor focus on syntax and line delimiter - * corrections. The syntax correction is based on the corresponding XSD/DTD, - * but it must be assumed by the Spotless formatter that the provided files - * are valid. It cannot be the purpose of a formatter to correct syntax. - * A Java formatter should also not attempt to correct compilation errors. - * A line delimiter correction would furthermore violate the Spotless rule - * that the strings processed by a Spotless formatter chain must use - * UNIX style delimiters. - *

- * @see org.eclipse.wst.sse.core.internal.cleanup.AbstractStructuredCleanupProcessor - */ -public class CleanupStep { - - /** Make some of the protected SEE AbstractStructuredCleanupProcessor methods public. */ - public interface ProcessorAccessor { - - /** Configure from Eclipse framework preferences */ - void refreshPreferences(); - - /** Get underlying processor */ - AbstractStructuredCleanupProcessor get(); - - /** Get processor content type */ - String getTypeId(); - } - - /** Framework configuration public to all formatters using the Cleanup step */ - public static abstract class FrameworkConfig implements SpotlessEclipseConfig { - - private String processorContentTypeID; - - protected FrameworkConfig() { - processorContentTypeID = "none"; - } - - void setProcessorTypeID(String contentTypeID) { - processorContentTypeID = contentTypeID; - } - - @Override - public void registerServices(SpotlessEclipseServiceConfig config) { - config.disableDebugging(); - config.hideEnvironment(); - config.useTemporaryLocations(); - config.changeSystemLineSeparator(); - config.useSlf4J(this.getClass().getPackage().getName() + "-" + processorContentTypeID); - - //Assure that all file content processed by this formatter step are associated to this cleanup-step - config.add(IContentTypeManager.class, new ContentTypeManager(processorContentTypeID)); - - //The preference lookup via the ContentTypeManager, requires a preference service - config.add(IPreferencesService.class, PreferencesService.getDefault()); - } - - @Override - public void activatePlugins(SpotlessEclipsePluginConfig config) { - config.applyDefault(); - /* - * The core preferences require do lookup the resources "config/override.properties" - * from the plugin ID. - * The values are never used, nor do we require the complete SSE core plugin to be started. - * Hence we just provide the internal plugin. - */ - config.add(new org.eclipse.wst.sse.core.internal.encoding.util.CodedResourcePlugin()); - } - } - - protected final ProcessorAccessor processorAccessor; - - protected CleanupStep(ProcessorAccessor processorAccessor, FrameworkConfig config) throws Exception { - config.setProcessorTypeID(processorAccessor.getTypeId()); - SpotlessEclipseFramework.setup(config); - this.processorAccessor = processorAccessor; - this.processorAccessor.refreshPreferences(); - /* - * Don't refresh the preferences every time a clone of the processor is created. - * All processors shall use the preferences of its parent. - */ - processorAccessor.get().refreshCleanupPreferences = false; - } - - /** - * Calls the cleanup and formatting task of the processor and returns the formatted string. - * @param raw Dirty string - * @return Formatted string - * @throws Exception All exceptions are considered fatal to the build process (Gradle, Maven, ...) and should not be caught. - */ - public String format(String raw) throws Exception { - return processorAccessor.get().cleanupContent(raw); - } - -} diff --git a/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/sse/ContentTypeManager.java b/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/sse/ContentTypeManager.java deleted file mode 100644 index 499a147ae9..0000000000 --- a/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/sse/ContentTypeManager.java +++ /dev/null @@ -1,235 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.wtp.sse; - -import java.io.IOException; -import java.io.InputStream; -import java.io.Reader; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.QualifiedName; -import org.eclipse.core.runtime.content.IContentDescription; -import org.eclipse.core.runtime.content.IContentType; -import org.eclipse.core.runtime.content.IContentTypeSettings; -import org.eclipse.core.runtime.preferences.IScopeContext; -import org.eclipse.wst.css.core.internal.provisional.contenttype.ContentTypeIdForCSS; -import org.eclipse.wst.html.core.internal.provisional.contenttype.ContentTypeIdForHTML; -import org.eclipse.wst.json.core.contenttype.ContentTypeIdForJSON; -import org.eclipse.wst.xml.core.internal.provisional.contenttype.ContentTypeIdForXML; - -import com.diffplug.spotless.extra.eclipse.base.service.NoContentTypeSpecificHandling; - -/** - - * WTP ModelHandlerRegistry uses the content type mamanger clean-up formatters - * to provide association of content to content type related functionality. - *

- * Preference lookup per content type is accomplished via the - * Eclipse PreferencesService, which must be provided in combination with - * this service. - *

- * The input byte steam encoding detection is accomplished by the - * content type manager. Normally the encoding is bount do a document/file. - * Spotless applies the formatting on strings already decoded. - * The WTP AbstractStructuredCleanupProcessor provides for non-documents - * a clean-up function converting the decoded string into an UTF-8 encoded byte stream. - * WTP AbstractDocumentLoader uses content type mamanger to determine the encoding - * of the input stream. - * Only the steps are affected that are using the - * AbstractStructuredCleanupProcessor. All other steps creating an empty document - * (e.g. via WTP AbstractDocumentLoader) and setting the textual content of the new document. - * - * @see org.eclipse.core.internal.preferences.PreferencesService - * @see org.eclipse.wst.sse.core.internal.cleanup.AbstractStructuredCleanupProcessor - * @see org.eclipse.wst.sse.core.internal.document.AbstractDocumentLoader - * @see org.eclipse.wst.sse.core.internal.modelhandler.ModelHandlerRegistry - */ -class ContentTypeManager extends NoContentTypeSpecificHandling { - private final Map id2Object; - private final IContentType processorStepType; - private final IContentDescription processorStepDescription; - - /** - * Content type manager as required for cleanup steps. - * @param formatterContentTypeID The content type of the formatter step - */ - ContentTypeManager(String formatterContentTypeID) { - id2Object = new HashMap(); - Arrays.asList( - ContentTypeIdForCSS.ContentTypeID_CSS, - ContentTypeIdForXML.ContentTypeID_XML, - ContentTypeIdForHTML.ContentTypeID_HTML, - ContentTypeIdForJSON.ContentTypeID_JSON) - .stream().forEach(id -> id2Object.put(id, new ContentTypeId(id))); - processorStepType = id2Object.get(formatterContentTypeID); - if (null == processorStepType) { - throw new IllegalArgumentException("The manager does not support content type " + formatterContentTypeID); - } - processorStepDescription = new StringDescription(processorStepType); - } - - @Override - public IContentType getContentType(String contentTypeIdentifier) { - /* - * It is OK to return null here since the manager is only used as an additional - * helper to alter default behavior. - */ - return id2Object.get(contentTypeIdentifier); - } - - @Override - public IContentType findContentTypeFor(InputStream contents, String fileName) throws IOException { - //We only format things here with the given processor, so this answer is always correct. - return processorStepType; - } - - @Override - public IContentDescription getDescriptionFor(InputStream contents, String fileName, QualifiedName[] options) throws IOException { - return processorStepDescription; - } - - private static class StringDescription implements IContentDescription { - - private final IContentType type; - - public StringDescription(IContentType type) { - this.type = type; - } - - @Override - public boolean isRequested(QualifiedName key) { - return false; //Don't use set Property - } - - @Override - public String getCharset() { - //Called by AbstractDocumentLoader.readInputStream - return "UTF-8"; //UTF-8 encoded by AbstractStructuredCleanupProcessor.cleanupContent - } - - @Override - public IContentType getContentType() { - return type; - } - - @Override - public Object getProperty(QualifiedName key) { - return null; //Assume that the property map is empty - } - - @Override - public void setProperty(QualifiedName key, Object value) { - throw new IllegalArgumentException("Content description key cannot be set: " + key); - } - } - - /** - * The WTP uses the manager mainly for ID mapping, so most of the methods are not used. - * Actually it has a hand stitched way for transforming the content type ID - * {@code org.eclipse.wst...source} to the plugin ID {@code org.eclipse.wst...core}. - * @see org.eclipse.wst.sse.core.internal.encoding.ContentBasedPreferenceGateway - */ - private static class ContentTypeId implements IContentType { - - private final String id; - - ContentTypeId(String id) { - this.id = id; - } - - @Override - public void addFileSpec(String fileSpec, int type) throws CoreException {} - - @Override - public void removeFileSpec(String fileSpec, int type) throws CoreException {} - - @Override - public void setDefaultCharset(String userCharset) throws CoreException {} - - @Override - public boolean isUserDefined() { - return false; - } - - @Override - public IContentType getBaseType() { - return null; - } - - @Override - public IContentDescription getDefaultDescription() { - return null; - } - - @Override - public IContentDescription getDescriptionFor(InputStream contents, QualifiedName[] options) throws IOException { - return null; - } - - @Override - public IContentDescription getDescriptionFor(Reader contents, QualifiedName[] options) throws IOException { - return null; - } - - @Override - public String getDefaultCharset() { - return null; - } - - @Override - public String[] getFileSpecs(int type) { - return null; - } - - @Override - public String getId() { - return id; - } - - @Override - public String getName() { - return id; - } - - @Override - public boolean isAssociatedWith(String fileName) { - return false; - } - - @Override - public boolean isAssociatedWith(String fileName, IScopeContext context) { - return false; - } - - @Override - public boolean isKindOf(IContentType another) { - if (null == another) { - return false; - } - return this.id.equals(another.getId()); - } - - @Override - public IContentTypeSettings getSettings(IScopeContext context) throws CoreException { - return null; - } - - } - -} diff --git a/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/sse/PluginPreferences.java b/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/sse/PluginPreferences.java deleted file mode 100644 index 81aa772617..0000000000 --- a/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/sse/PluginPreferences.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.wtp.sse; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Properties; - -import org.eclipse.core.runtime.Plugin; -import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer; -import org.eclipse.core.runtime.preferences.DefaultScope; -import org.eclipse.core.runtime.preferences.IEclipsePreferences; -import org.eclipse.wst.xml.core.internal.catalog.Catalog; -import org.eclipse.wst.xml.core.internal.catalog.CatalogReader; -import org.eclipse.wst.xml.core.internal.catalog.provisional.ICatalog; - -/** - * The plugin preference configuration of most WTP formatters is accomplished via the - * globabl Eclipse preference lookup. - * Spotless allows different formatter configurations per sub-projects. - * Fortunately most formatters only perform a lookup on instantiation and not afterwards. - * This is sometimes not true for all preferences of the formatter. - * - * - */ -public class PluginPreferences { - /** - * Optional XML catalog for XSD/DTD lookup. - * Catalog versions 1.0 and 1.1 are supported. - *

- * Value is of type {@code Path}. - *

- */ - public static final String USER_CATALOG = "userCatalog"; - - /** - * Indicates if external URIs (location hints) should be resolved - * and the referenced DTD/XSD shall be applied. Per default - * external URIs are ignored. - *

- * Value is of type Boolean. - *

- */ - public static final String RESOLVE_EXTERNAL_URI = "resolveExternalURI"; - - /** Storage of latest global configuration */ - private static final Map CONFIG = new HashMap<>(); - - /** \return True if user explicitly set the */ - public static boolean isExternalUriAllowed(Properties properties) { - return Boolean.parseBoolean(properties.getProperty(PluginPreferences.RESOLVE_EXTERNAL_URI, "false")); - } - - /** Configures persistent Eclipse properties */ - public static void configure(Plugin plugin, AbstractPreferenceInitializer defaultInitializer, Properties properties) { - defaultInitializer.initializeDefaultPreferences(); - IEclipsePreferences globalPreferences = DefaultScope.INSTANCE.getNode(getPluginId(plugin)); - properties.forEach((key, value) -> { - globalPreferences.put((String) key, (String) value); - }); - store(plugin, properties); - } - - /** Stores Eclipse properties for later comparison */ - public static void store(Plugin plugin, Properties properties) { - CONFIG.put(getPluginId(plugin), properties); - } - - /** Keep in mind that the ID is e.g. equal for all plugins. So assure that all user properties ge stored. */ - private static String getPluginId(Plugin plugin) { - return plugin.getBundle().getSymbolicName(); - } - - public static void configureCatalog(final Properties properties, final ICatalog defaultCatalogInterface) { - Objects.requireNonNull(properties, "Property values are missing."); - Objects.requireNonNull(defaultCatalogInterface, "Default catalog missing."); - if (!(defaultCatalogInterface instanceof Catalog)) { - throw new IllegalArgumentException("Internal error: Catalog implementation '" + defaultCatalogInterface.getClass().getCanonicalName() + "' unsupported."); - } - Catalog defaultCatalog = (Catalog) defaultCatalogInterface; - String catalogProperty = properties.getProperty(USER_CATALOG, ""); - if (!catalogProperty.isEmpty()) { - final File catalogFile = new File(catalogProperty); - try { - InputStream inputStream = new FileInputStream(catalogFile); - String orgBase = defaultCatalog.getBase(); - defaultCatalog.setBase(catalogFile.toURI().toString()); - CatalogReader.read((Catalog) defaultCatalog, inputStream); - defaultCatalog.setBase(orgBase); - } catch (IOException e) { - throw new IllegalArgumentException( - String.format("Value of '%s' refers to '%s', which cannot be read.", USER_CATALOG, catalogFile)); - } - } else { - defaultCatalog.clear(); - } - } - - /** Throws exception in case configuration has changed */ - public static void assertNoChanges(Plugin plugin, Properties properties) { - Objects.requireNonNull(properties, "Property values are missing."); - final String preferenceId = plugin.getBundle().getSymbolicName(); - Properties originalValues = CONFIG.get(preferenceId); - if (null == originalValues) { - throw new IllegalArgumentException("No configuration found for " + preferenceId); - } - if (!originalValues.equals(properties)) { - throw new IllegalArgumentException("The Eclipse formatter does not support multiple configurations."); - } - } - -} diff --git a/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/sse/PreventExternalURIResolverExtension.java b/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/sse/PreventExternalURIResolverExtension.java deleted file mode 100644 index d0b95e5632..0000000000 --- a/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/sse/PreventExternalURIResolverExtension.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.wtp.sse; - -import org.eclipse.core.resources.IFile; -import org.eclipse.emf.common.util.URI; -import org.eclipse.wst.common.uriresolver.internal.provisional.URIResolverExtension; -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; - -/** - * The URI resolver extension - */ -public class PreventExternalURIResolverExtension implements URIResolverExtension, BundleActivator { - - private static final String REFUSE_EXTERNAL_URI = "file://refused.external.uri"; - - /** - * @param file the in-workspace base resource, if one exists - * @param baseLocation - the location of the resource that contains the uri - * @param publicId - an optional public identifier (i.e. namespace name), or null if none - * @param systemId - an absolute or relative URI, or null if none - * - * @return an absolute URI or null if this extension can not resolve this reference - */ - @Override - public String resolve(IFile file, String baseLocation, String publicId, String systemId) { - if (null != systemId) { - try { - URI proposalByPreviousResolver = org.eclipse.emf.common.util.URI.createURI(systemId); - String host = proposalByPreviousResolver.host(); - /* - * The host is empty (not null) - */ - if (!(null == host || host.isEmpty())) { - return REFUSE_EXTERNAL_URI; - } - } catch (IllegalArgumentException ignore) { - //If it is no a valid URI, there is nothing to do here. - } - } - return null; //Don't alter the proposal of previous resolver extensions by proposing something else - } - - @Override - public void start(BundleContext context) throws Exception { - //Nothing to do. The bundle-activator interface only allows to load this extension as a stand-alone plugin. - } - - @Override - public void stop(BundleContext context) throws Exception { - //Nothing to do. The bundle-activator interface only allows to load this extension as a stand-alone plugin. - } - -} diff --git a/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/sse/package-info.java b/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/sse/package-info.java deleted file mode 100644 index 931b7e085e..0000000000 --- a/_ext/eclipse-wtp/src/main/java/com/diffplug/spotless/extra/eclipse/wtp/sse/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** Eclipse WTP Structured Source Editing (SEE) formatter helper */ -@ParametersAreNonnullByDefault -package com.diffplug.spotless.extra.eclipse.wtp.sse; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/_ext/eclipse-wtp/src/main/resources/META-INF/MANIFEST.MF b/_ext/eclipse-wtp/src/main/resources/META-INF/MANIFEST.MF deleted file mode 100644 index 9f785fea6c..0000000000 --- a/_ext/eclipse-wtp/src/main/resources/META-INF/MANIFEST.MF +++ /dev/null @@ -1,3 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-SymbolicName: com.diffplug.gradle.spotless.eclipse.wtp; singleton:=true diff --git a/_ext/eclipse-wtp/src/main/resources/plugin.xml b/_ext/eclipse-wtp/src/main/resources/plugin.xml deleted file mode 100644 index 7ffd251c94..0000000000 --- a/_ext/eclipse-wtp/src/main/resources/plugin.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - diff --git a/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseCssFormatterStepImplTest.java b/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseCssFormatterStepImplTest.java deleted file mode 100644 index 8dda3149c0..0000000000 --- a/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseCssFormatterStepImplTest.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2016-2021 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.wtp; - -import static com.diffplug.spotless.extra.eclipse.base.SpotlessEclipseFramework.LINE_DELIMITER; -import static org.assertj.core.api.Assertions.assertThat; -import static org.eclipse.wst.css.core.internal.preferences.CSSCorePreferenceNames.*; -import static org.junit.jupiter.api.Assertions.*; - -import java.util.Properties; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -class EclipseCssFormatterStepImplTest { - - private final static String ILLEGAL_CHAR = Character.toString((char) 254); - private final static String UNFORMATTED = " body {a: v; b: v;}\n".replaceAll("\n", LINE_DELIMITER); - private final static String FORMATTED = "BODY {\n a: v;\n b: v;\n}".replaceAll("\n", LINE_DELIMITER); - private final static String PRE_CODE_UNFORMATTED = "/**
\"Hello\"
*/\n".replaceAll("\n", LINE_DELIMITER); - - private EclipseCssFormatterStepImpl formatter; - - @BeforeEach - void initialize() throws Exception { - /* - * The instantiation can be repeated for each step, but only with the same configuration - * All formatter configuration is stored in - * org.eclipse.core.runtime/.settings/org.eclipse.wst.css.core.prefs. - */ - Properties properties = new Properties(); - properties.put(INDENTATION_SIZE, "3"); - properties.put(INDENTATION_CHAR, SPACE); //Default is TAB - properties.put(CLEANUP_CASE_SELECTOR, Integer.toString(UPPER)); //Done by cleanup - formatter = new EclipseCssFormatterStepImpl(properties); - } - - @Test - void format() throws Exception { - String output = formatter.format(UNFORMATTED); - assertEquals(FORMATTED, - output, "Unexpected formatting with default preferences."); - } - - @Test - void illegalCharacter() throws Exception { - String output = formatter.format(ILLEGAL_CHAR + UNFORMATTED); - assertThat(output).as("Illeagl characters are not handled on best effort basis.").contains("BODY {"); - } - - @Test - void illegalSyntax() throws Exception { - String output = formatter.format("{" + UNFORMATTED); - assertEquals("{" + LINE_DELIMITER + FORMATTED, - output, "Illeagl syntax is not handled on best effort basis."); - } - - @Test - void formatComment() throws Exception { - String output = formatter.format(PRE_CODE_UNFORMATTED + UNFORMATTED); - assertEquals(PRE_CODE_UNFORMATTED + FORMATTED, - output, "Unexpected formatting of cpomments."); - } - - @Test - void configurationChange() throws Exception { - assertThrows(IllegalArgumentException.class, () -> new EclipseCssFormatterStepImpl(new Properties())); - } - -} diff --git a/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseHtmlFormatterStepImplTest.java b/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseHtmlFormatterStepImplTest.java deleted file mode 100644 index b75421692a..0000000000 --- a/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseHtmlFormatterStepImplTest.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright 2016-2021 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.wtp; - -import static org.eclipse.wst.html.core.internal.preferences.HTMLCorePreferenceNames.*; -import static org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants.*; -import static org.junit.jupiter.api.Assertions.*; - -import java.util.Properties; - -import org.eclipse.wst.html.core.internal.preferences.HTMLCorePreferenceNames; -import org.eclipse.wst.jsdt.core.JavaScriptCore; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -class EclipseHtmlFormatterStepImplTest { - - private TestData testData = null; - private EclipseHtmlFormatterStepImpl formatter; - - @BeforeEach - void initialize() throws Exception { - testData = TestData.getTestDataOnFileSystem("html"); - /* - * The instantiation can be repeated for each step, but only with the same configuration - * All formatter configuration is stored in - * org.eclipse.core.runtime/.settings/org.eclipse.wst.xml.core.prefs. - * So a simple test of one configuration item change is considered sufficient. - */ - Properties properties = new Properties(); - properties.put(CLEANUP_TAG_NAME_CASE, Integer.toString(HTMLCorePreferenceNames.UPPER)); //HTML config - properties.put(FORMATTER_INSERT_SPACE_BEFORE_SEMICOLON, JavaScriptCore.INSERT); //JS config - properties.put(QUOTE_ATTR_VALUES, "TRUE"); //CSS config - formatter = new EclipseHtmlFormatterStepImpl(properties); - } - - @Test - void formatHtml4() throws Exception { - String[] input = testData.input("html4.html"); - String output = formatter.format(input[0]); - assertEquals(testData.expected("html4.html"), - output, "Unexpected HTML4 formatting."); - } - - @Test - void formatHtml5() throws Exception { - String[] input = testData.input("html5.html"); - String output = formatter.format(input[0]); - assertEquals(testData.expected("html5.html"), - output, "Unexpected HTML5 formatting."); - } - - @Test - void invalidSyntax() throws Exception { - String[] input = testData.input("invalid_syntax.html"); - String output = formatter.format(input[0]); - assertEquals(testData.expected("invalid_syntax.html"), - output, "Unexpected HTML formatting in case syntax is not valid."); - } - - @Test - void formatJavaScript() throws Exception { - String[] input = testData.input("javascript.html"); - String output = formatter.format(input[0]); - assertEquals(testData.expected("javascript.html"), - output, "Unexpected JS formatting."); - } - - @Test - void formatCSS() throws Exception { - String[] input = testData.input("css.html"); - String output = formatter.format(input[0]); - assertEquals(testData.expected("css.html"), - output, "Unexpected CSS formatting."); - } - - @Test - void checkCleanupForNonUtf8() throws Exception { - String osEncoding = System.getProperty("file.encoding"); - System.setProperty("file.encoding", "ISO-8859-1"); //Simulate a non UTF-8 OS - String[] input = testData.input("utf-8.html"); - String output = formatter.format(input[0]); - System.setProperty("file.encoding", osEncoding); - assertEquals(testData.expected("utf-8.html"), output, "Unexpected formatting of UTF-8"); - } - - @Test - void checkBOMisStripped() throws Exception { - String[] input = testData.input("bom.html"); - String[] inputWithoutBom = testData.input("utf-8.html"); - //The UTF-8 BOM is interpreted as on UTF-16 character. - assertEquals(input[0].length() - 1, inputWithoutBom[0].length(), "BOM input invalid"); - String output = formatter.format(input[0]); - assertEquals(testData.expected("utf-8.html"), output, "BOM is not stripped"); - } - - @Test - void configurationChange() throws Exception { - assertThrows(IllegalArgumentException.class, () -> new EclipseHtmlFormatterStepImpl(new Properties())); - } -} diff --git a/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseJsFormatterStepImplTest.java b/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseJsFormatterStepImplTest.java deleted file mode 100644 index 0858c3a04d..0000000000 --- a/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseJsFormatterStepImplTest.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright 2016-2021 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.wtp; - -import static com.diffplug.spotless.extra.eclipse.base.SpotlessEclipseFramework.LINE_DELIMITER; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.*; - -import java.util.Arrays; -import java.util.Properties; - -import org.eclipse.wst.jsdt.core.JavaScriptCore; -import org.eclipse.wst.jsdt.core.formatter.DefaultCodeFormatterConstants; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -class EclipseJsFormatterStepImplTest { - private final static String ILLEGAL_CHAR = Character.toString((char) 254); - private final static String UNFORMATTED = "var TEST = TEST || {};\n" + - "TEST.say = function() {\n" + - " console.log(\"Hello world!\"); }\n".replaceAll("\n", LINE_DELIMITER); - private final static String FORMATTED = "var TEST = TEST || {};\n" + - "TEST.say = function () {\n" + - "\tconsole.log(\"Hello world!\");\n}\n".replaceAll("\n", LINE_DELIMITER); - // Single line comment remains untouched - private final static String SINGLE_LINE_COMMENT = "// One line \"hello world\"\n".replaceAll("\n", LINE_DELIMITER); - // JavaDoc comment get indentation. Within PPRE code, HTML entities are escaped. - private final static String PRE_CODE_UNFORMATTED = "/**
\"Hello\"
*/\n".replaceAll("\n", LINE_DELIMITER); - private final static String PRE_CODE_FORMATTED = "/**\n *
\n * "Hello"\n * 
\n */\n".replaceAll("\n", LINE_DELIMITER); - - private EclipseJsFormatterStepImpl formatter; - - @BeforeEach - void initialize() throws Exception { - /* - * The instantiation can be repeated for each step, but only with the same configuration - * All formatter configuration is stored in - * org.eclipse.core.runtime/.settings/org.eclipse.jst.jsdt.core.prefs. - */ - Properties properties = new Properties(); - properties.setProperty(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaScriptCore.TAB); - formatter = new EclipseJsFormatterStepImpl(properties); - } - - @Test - void invalidSyntax() throws Exception { - IllegalArgumentException error = assertThrows(IllegalArgumentException.class, () -> formatter.format(UNFORMATTED.replace("()", ""))); - assertThat(error.getMessage()).as("Exception has no hint about invalid syntax.").contains(Arrays.asList("Invalid", "syntax")); - } - - @Test - void illegalCharacter() throws Exception { - String output = formatter.format(UNFORMATTED.replace("function", "function" + ILLEGAL_CHAR)); - assertThat(output).as("Illegal ASCII charactes are not treated on best effort basis.").contains("function" + ILLEGAL_CHAR); - } - - @Test - void nominal() throws Exception { - String output = formatter.format(UNFORMATTED); - assertEquals(FORMATTED, output, "User configuration ignored by formatter."); - } - - @Test - void formatComments() throws Exception { - String output = formatter.format(SINGLE_LINE_COMMENT + PRE_CODE_UNFORMATTED + UNFORMATTED); - assertEquals(SINGLE_LINE_COMMENT + PRE_CODE_FORMATTED + FORMATTED, - output, "Invalid user configuration not treated on best effort basis."); - } - - @Test - void configurationChange() throws Exception { - assertThrows(IllegalArgumentException.class, () -> new EclipseJsFormatterStepImpl(new Properties())); - } - -} diff --git a/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseJsonFormatterStepImplTest.java b/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseJsonFormatterStepImplTest.java deleted file mode 100644 index 3bb3b7c988..0000000000 --- a/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseJsonFormatterStepImplTest.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2016-2021 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.wtp; - -import static com.diffplug.spotless.extra.eclipse.base.SpotlessEclipseFramework.LINE_DELIMITER; -import static org.eclipse.wst.json.core.preferences.JSONCorePreferenceNames.*; -import static org.junit.jupiter.api.Assertions.*; - -import java.util.Properties; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -class EclipseJsonFormatterStepImplTest { - private final static String ILLEGAL_CHAR = Character.toString((char) 254); - private final static String UNFORMATTED_OBJECT = "{\n \"x\": { \"a\" : \"v\",\"properties\" : \"v\" }}".replaceAll("\n", LINE_DELIMITER); - private final static String FORMATTED_OBJECT = "{\n \"x\": {\n \"a\": \"v\",\n \"properties\": \"v\"\n }\n}".replaceAll("\n", LINE_DELIMITER); - private final static String UNFORMATTED_ARRAY = "[\n { \"a\" : \"v\",\"properties\" : \"v\" }]".replaceAll("\n", LINE_DELIMITER); - private final static String FORMATTED_ARRAY = "[\n {\n \"a\": \"v\",\n \"properties\": \"v\"\n }\n]".replaceAll("\n", LINE_DELIMITER); - - private EclipseJsonFormatterStepImpl formatter; - - @BeforeEach - void initialize() throws Exception { - /* - * The instantiation can be repeated for each step, but only with the same configuration - * All formatter configuration is stored in - * org.eclipse.core.runtime/.settings/org.eclipse.wst.json.core.prefs. - * So a simple test of one configuration item change is considered sufficient. - */ - Properties properties = new Properties(); - properties.put(INDENTATION_SIZE, "3"); //Default is 1 - properties.put(INDENTATION_CHAR, SPACE); //Default is TAB - properties.put(CASE_PROPERTY_NAME, Integer.toString(UPPER)); //Dead code, ignored - formatter = new EclipseJsonFormatterStepImpl(properties); - } - - @Test - void formatObject() throws Exception { - String output = formatter.format(UNFORMATTED_OBJECT); - assertEquals(FORMATTED_OBJECT, - output, "Unexpected formatting with default preferences."); - } - - @Test - void formatArray() throws Exception { - String output = formatter.format(UNFORMATTED_ARRAY); - assertEquals(FORMATTED_ARRAY, - output, "Unexpected formatting with default preferences."); - } - - @Test - void illegalCharacter() throws Exception { - String output = formatter.format(ILLEGAL_CHAR + UNFORMATTED_OBJECT); - assertEquals(ILLEGAL_CHAR + FORMATTED_OBJECT, - output, "Illeagl characteds are not ignored."); - } - - @Test - void illegalSyntax() throws Exception { - String output = formatter.format("{" + UNFORMATTED_OBJECT); - assertEquals(FORMATTED_OBJECT, - output, "Illeagl syntax is not handled on best effort basis."); - } - - @Test - void configurationChange() throws Exception { - assertThrows(IllegalArgumentException.class, () -> new EclipseJsonFormatterStepImpl(new Properties())); - } -} diff --git a/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseXmlFormatterStepImplAllowExternalURIsTest.java b/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseXmlFormatterStepImplAllowExternalURIsTest.java deleted file mode 100644 index ac3b2c45f6..0000000000 --- a/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseXmlFormatterStepImplAllowExternalURIsTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2016-2021 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.wtp; - -import static org.eclipse.wst.xml.core.internal.preferences.XMLCorePreferenceNames.INDENTATION_CHAR; -import static org.eclipse.wst.xml.core.internal.preferences.XMLCorePreferenceNames.INDENTATION_SIZE; -import static org.eclipse.wst.xml.core.internal.preferences.XMLCorePreferenceNames.SPACE; -import static org.junit.jupiter.api.Assertions.*; - -import java.util.Properties; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import com.diffplug.spotless.extra.eclipse.wtp.sse.PluginPreferences; - -/** Test configuration allowExternalURI=false */ -class EclipseXmlFormatterStepImplAllowExternalURIsTest { - private TestData testData = null; - private EclipseXmlFormatterStepImpl formatter; - - @BeforeEach - void initializeStatic() throws Exception { - testData = TestData.getTestDataOnFileSystem("xml"); - /* - * The instantiation can be repeated for each step, but only with the same configuration - * All formatter configuration is stored in - * org.eclipse.core.runtime/.settings/org.eclipse.wst.xml.core.prefs. - * So a simple test of one configuration item change is considered sufficient. - */ - Properties properties = new Properties(); - properties.put(PluginPreferences.RESOLVE_EXTERNAL_URI, "TRUE"); - properties.put(INDENTATION_SIZE, "2"); - properties.put(INDENTATION_CHAR, SPACE); //Default is TAB - formatter = new EclipseXmlFormatterStepImpl(properties); - } - - @Test - void dtdExternalPath() throws Throwable { - String[] input = testData.input("dtd_external.test"); - String output = formatter.format(input[0], input[1]); - assertEquals(testData.expected("dtd_external.test"), - output, "External DTD not resolved. Restrictions are not applied by formatter."); - } - - @Test - void xsdExternalPath() throws Throwable { - String[] input = testData.input("xsd_external.test"); - String output = formatter.format(input[0], input[1]); - assertEquals(testData.expected("xsd_external.test"), - output, "External XSD not resolved. Restrictions are not applied by formatter."); - } -} diff --git a/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseXmlFormatterStepImplCatalogLookupTest.java b/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseXmlFormatterStepImplCatalogLookupTest.java deleted file mode 100644 index a9ccd85720..0000000000 --- a/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseXmlFormatterStepImplCatalogLookupTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2016-2021 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.wtp; - -import static org.eclipse.wst.xml.core.internal.preferences.XMLCorePreferenceNames.INDENTATION_CHAR; -import static org.eclipse.wst.xml.core.internal.preferences.XMLCorePreferenceNames.INDENTATION_SIZE; -import static org.eclipse.wst.xml.core.internal.preferences.XMLCorePreferenceNames.SPACE; -import static org.junit.jupiter.api.Assertions.*; - -import java.util.Properties; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import com.diffplug.spotless.extra.eclipse.wtp.sse.PluginPreferences; - -/** Test configuration allowExternalURI=false */ -class EclipseXmlFormatterStepImplCatalogLookupTest { - private TestData testData = null; - private EclipseXmlFormatterStepImpl formatter; - - @BeforeEach - void initializeStatic() throws Exception { - testData = TestData.getTestDataOnFileSystem("xml"); - /* - * The instantiation can be repeated for each step, but only with the same configuration - * All formatter configuration is stored in - * org.eclipse.core.runtime/.settings/org.eclipse.wst.xml.core.prefs. - * So a simple test of one configuration item change is considered sufficient. - */ - Properties properties = new Properties(); - properties.put(INDENTATION_SIZE, "2"); - properties.put(INDENTATION_CHAR, SPACE); //Default is TAB - properties.put(PluginPreferences.USER_CATALOG, testData.getRestrictionsPath("catalog.xml").toString()); - formatter = new EclipseXmlFormatterStepImpl(properties); - } - - @Test - void catalogLookup() throws Throwable { - String[] input = testData.input("xsd_not_found.test"); - String output = formatter.format(input[0], input[1]); - assertEquals(testData.expected("xsd_not_found.test").replace(" remove spaces ", "remove spaces"), - output, "XSD not resolved by catalog. Restrictions are not applied by formatter."); - } -} diff --git a/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseXmlFormatterStepImplTest.java b/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseXmlFormatterStepImplTest.java deleted file mode 100644 index 88b15c42e2..0000000000 --- a/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/EclipseXmlFormatterStepImplTest.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright 2016-2021 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.wtp; - -import static com.diffplug.spotless.extra.eclipse.base.SpotlessEclipseFramework.LINE_DELIMITER; -import static org.eclipse.wst.xml.core.internal.preferences.XMLCorePreferenceNames.*; -import static org.junit.jupiter.api.Assertions.*; - -import java.util.Properties; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -/** Eclipse WST wrapper integration tests */ -class EclipseXmlFormatterStepImplTest { - - private final static String INCOMPLETE = ""; - private final static String ILLEGAL_CHAR = "\0"; - - private TestData testData = null; - private EclipseXmlFormatterStepImpl formatter; - - @BeforeEach - void initialize() throws Exception { - testData = TestData.getTestDataOnFileSystem("xml"); - /* - * The instantiation can be repeated for each step, but only with the same configuration - * All formatter configuration is stored in - * org.eclipse.core.runtime/.settings/org.eclipse.wst.xml.core.prefs. - * So a simple test of one configuration item change is considered sufficient. - */ - Properties properties = new Properties(); - properties.put(INDENTATION_SIZE, "2"); - properties.put(INDENTATION_CHAR, SPACE); //Default is TAB - formatter = new EclipseXmlFormatterStepImpl(properties); - } - - @Test - void simpleDefaultFormat() throws Throwable { - String[] input = testData.input("xml_space.test"); - String output = formatter.format(input[0], input[1]); - assertEquals(testData.expected("xml_space.test"), - output, "Unexpected formatting with default preferences."); - } - - @Test - void invalidXmlFormat() throws Throwable { - String[] input = testData.input("xml_space.test"); - input[0] += INCOMPLETE; - String output = formatter.format(input[0], input[1]); - String expected = testData.expected("xml_space.test") + LINE_DELIMITER + INCOMPLETE; - assertEquals(expected, - output, "Incomplete XML not formatted on best effort basis."); - } - - @Test - void illegalXmlCharater() throws Throwable { - String[] input = testData.input("xml_space.test"); - input[0] = ILLEGAL_CHAR + input[0]; - String output = formatter.format(input[0], input[1]); - String expected = LINE_DELIMITER + LINE_DELIMITER + testData.expected("xml_space.test"); - assertEquals(expected, output, "Illegal character not replaced by line delimiter."); - } - - @Test - void dtdRelativePath() throws Throwable { - String[] input = testData.input("dtd_relative.test"); - String output = formatter.format(input[0], input[1]); - assertEquals(testData.expected("dtd_relative.test"), - output, "Relative DTD not resolved. Restrictions are not applied by formatter."); - } - - @Test - void dtdExternalPath() throws Throwable { - String[] input = testData.input("dtd_external.test"); - String output = formatter.format(input[0], input[1]); - assertNotEquals(testData.expected("dtd_external.test"), - output, "External DTD resolved by default. Restrictions are applied by formatter."); - } - - @Test - void xsdRelativePath() throws Throwable { - String[] input = testData.input("xsd_relative.test"); - String output = formatter.format(input[0], input[1]); - assertEquals(testData.expected("xsd_relative.test"), - output, "Relative XSD not resolved. Restrictions are not applied by formatter."); - } - - @Test - void xsdExternalPath() throws Throwable { - String[] input = testData.input("xsd_external.test"); - String output = formatter.format(input[0], input[1]); - assertNotEquals(testData.expected("xsd_external.test"), - output, "External XSD resolved per default. Restrictions are applied by formatter."); - } - - @Test - void xsdNotFound() throws Throwable { - String[] input = testData.input("xsd_not_found.test"); - String output = formatter.format(input[0], input[1]); - assertEquals(testData.expected("xsd_not_found.test"), - output, "Unresolved XSD/DTD not silently ignored."); - } - - @Test - void configurationChange() throws Exception { - assertThrows(IllegalArgumentException.class, () -> new EclipseXmlFormatterStepImpl(new Properties())); - } -} diff --git a/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/TestData.java b/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/TestData.java deleted file mode 100644 index d767337970..0000000000 --- a/_ext/eclipse-wtp/src/test/java/com/diffplug/spotless/extra/eclipse/wtp/TestData.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2016 DiffPlug - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.diffplug.spotless.extra.eclipse.wtp; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; - -public class TestData { - public static TestData getTestDataOnFileSystem(String kind) { - final String userDir = System.getProperty("user.dir", "."); - Path dataPath = Paths.get(userDir, "src", "test", "resources", kind); - if (Files.isDirectory(dataPath)) { - return new TestData(dataPath); - } - return null; - } - - private final Path inputPath; - private final Path expectedPath; - private final Path restrictionsPath; - - private TestData(Path dataPath) { - inputPath = dataPath.resolve("input").toAbsolutePath(); - expectedPath = dataPath.resolve("expected").toAbsolutePath(); - restrictionsPath = dataPath.resolve("restrictions").toAbsolutePath(); - for (Path testDataDir : new Path[]{inputPath, expectedPath, restrictionsPath}) { - if (!Files.isDirectory(testDataDir)) { - throw new IllegalArgumentException(String.format("'%1$s' is not a directory.", testDataDir)); - } - } - } - - public String[] input(final String fileName) throws Exception { - Path xmlPath = inputPath.resolve(fileName); - return new String[]{read(xmlPath), xmlPath.toString()}; - } - - public String expected(final String fileName) { - Path xmlPath = expectedPath.resolve(fileName); - return read(xmlPath); - } - - private String read(final Path xmlPath) { - if (!Files.isRegularFile(xmlPath)) { - throw new IllegalArgumentException(String.format("'%1$s' is not a regular file.", xmlPath)); - } - try { - String checkedOutFileContent = new String(java.nio.file.Files.readAllBytes(xmlPath), "UTF8"); - return checkedOutFileContent.replace("\r", ""); //Align GIT end-of-line normalization - } catch (IOException e) { - throw new IllegalArgumentException(String.format("Failed to read '%1$s'.", xmlPath), e); - } - } - - public Path getRestrictionsPath(String fileName) { - Path filePath = restrictionsPath.resolve(fileName); - if (!Files.exists(filePath)) { - throw new IllegalArgumentException(String.format("'%1$s' is not a restrictions file.", fileName)); - } - return filePath; - } -} diff --git a/_ext/eclipse-wtp/src/test/resources/html/expected/css.html b/_ext/eclipse-wtp/src/test/resources/html/expected/css.html deleted file mode 100644 index cfaea67cd0..0000000000 --- a/_ext/eclipse-wtp/src/test/resources/html/expected/css.html +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/_ext/eclipse-wtp/src/test/resources/html/expected/html4.html b/_ext/eclipse-wtp/src/test/resources/html/expected/html4.html deleted file mode 100644 index a344ed08a0..0000000000 --- a/_ext/eclipse-wtp/src/test/resources/html/expected/html4.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - Before -
After - -
- - \ No newline at end of file diff --git a/_ext/eclipse-wtp/src/test/resources/html/expected/html5.html b/_ext/eclipse-wtp/src/test/resources/html/expected/html5.html deleted file mode 100644 index c79dfdce62..0000000000 --- a/_ext/eclipse-wtp/src/test/resources/html/expected/html5.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - Before -
After - - - - \ No newline at end of file diff --git a/_ext/eclipse-wtp/src/test/resources/html/expected/invalid_syntax.html b/_ext/eclipse-wtp/src/test/resources/html/expected/invalid_syntax.html deleted file mode 100644 index 9c05557bb7..0000000000 --- a/_ext/eclipse-wtp/src/test/resources/html/expected/invalid_syntax.html +++ /dev/null @@ -1,7 +0,0 @@ - - - - -T<WHATSOEVER></WHATSOEVER> - - \ No newline at end of file diff --git a/_ext/eclipse-wtp/src/test/resources/html/expected/javascript.html b/_ext/eclipse-wtp/src/test/resources/html/expected/javascript.html deleted file mode 100644 index a33ea60503..0000000000 --- a/_ext/eclipse-wtp/src/test/resources/html/expected/javascript.html +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/_ext/eclipse-wtp/src/test/resources/html/expected/utf-8.html b/_ext/eclipse-wtp/src/test/resources/html/expected/utf-8.html deleted file mode 100644 index 4bcd6a03c1..0000000000 --- a/_ext/eclipse-wtp/src/test/resources/html/expected/utf-8.html +++ /dev/null @@ -1,7 +0,0 @@ - - - - -ÄÜ€ - - \ No newline at end of file diff --git a/_ext/eclipse-wtp/src/test/resources/html/input/bom.html b/_ext/eclipse-wtp/src/test/resources/html/input/bom.html deleted file mode 100644 index 3fe6abe797..0000000000 --- a/_ext/eclipse-wtp/src/test/resources/html/input/bom.html +++ /dev/null @@ -1,2 +0,0 @@ - -ÄÜ€ \ No newline at end of file diff --git a/_ext/eclipse-wtp/src/test/resources/html/input/css.html b/_ext/eclipse-wtp/src/test/resources/html/input/css.html deleted file mode 100644 index 8ccbc4dcc8..0000000000 --- a/_ext/eclipse-wtp/src/test/resources/html/input/css.html +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/_ext/eclipse-wtp/src/test/resources/html/input/html4.html b/_ext/eclipse-wtp/src/test/resources/html/input/html4.html deleted file mode 100644 index 45aa7b56f7..0000000000 --- a/_ext/eclipse-wtp/src/test/resources/html/input/html4.html +++ /dev/null @@ -1,10 +0,0 @@ - - - -Before -
-After - - - - \ No newline at end of file diff --git a/_ext/eclipse-wtp/src/test/resources/html/input/html5.html b/_ext/eclipse-wtp/src/test/resources/html/input/html5.html deleted file mode 100644 index 216c53e8e3..0000000000 --- a/_ext/eclipse-wtp/src/test/resources/html/input/html5.html +++ /dev/null @@ -1,10 +0,0 @@ - - - -Before -
-After - - - - \ No newline at end of file diff --git a/_ext/eclipse-wtp/src/test/resources/html/input/invalid_syntax.html b/_ext/eclipse-wtp/src/test/resources/html/input/invalid_syntax.html deleted file mode 100644 index 04c6cf7f2a..0000000000 --- a/_ext/eclipse-wtp/src/test/resources/html/input/invalid_syntax.html +++ /dev/null @@ -1,4 +0,0 @@ - - - -T</whatsoever> \ No newline at end of file diff --git a/_ext/eclipse-wtp/src/test/resources/html/input/javascript.html b/_ext/eclipse-wtp/src/test/resources/html/input/javascript.html deleted file mode 100644 index dccde2c2dd..0000000000 --- a/_ext/eclipse-wtp/src/test/resources/html/input/javascript.html +++ /dev/null @@ -1,34 +0,0 @@ -<!DOCTYPE html> -<html> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> -<script type="text/javascript">console.log("One line")</script> -<script type="text/javascript"> -console.log("Line break, no indent"); -</script> -<script type="text/javascript"> - console.log("Line break, wrong indent") -</script> -</head> -<body> -<nav> -<script type="text/javascript">console.log("One line, nested")</script> -<script type="text/javascript"> -console.log("Line break, no indent, nested") -</script> -<script type="text/javascript"> - console.log("Line break, wrong indent, nested"); -</script> - <script type="text/javascript"> -console.log("Wrong tag indents") - </script> -<script type="text/javascript"> -console.log("Empty lines when closing."); - - </script> -<script>console.log("Script without type")</script> -<script type="text/javascript"></script> -<script type="text/javascript"> if (condition) { console.log("Missing end of JS block")</script> -</nav> -</body> -</html> \ No newline at end of file diff --git a/_ext/eclipse-wtp/src/test/resources/html/input/utf-8.html b/_ext/eclipse-wtp/src/test/resources/html/input/utf-8.html deleted file mode 100644 index abf1a7d9a7..0000000000 --- a/_ext/eclipse-wtp/src/test/resources/html/input/utf-8.html +++ /dev/null @@ -1,2 +0,0 @@ -<!DOCTYPE html> -<html><head><meta charset="UTF-8"><title>ÄÜ€ \ No newline at end of file diff --git a/_ext/eclipse-wtp/src/test/resources/html/restrictions/ReadMe.txt b/_ext/eclipse-wtp/src/test/resources/html/restrictions/ReadMe.txt deleted file mode 100644 index 37c58641d8..0000000000 --- a/_ext/eclipse-wtp/src/test/resources/html/restrictions/ReadMe.txt +++ /dev/null @@ -1,9 +0,0 @@ -Various manual tests have been performed with external and internal DTDs. -They seem not to be used by the HTML formatter. Instead they are a -helper to parse the DOCTYPE and select the right content model. -The DTDParser.parse throws a SAXParseException when parsing the -HTML DTDs provided with the WST JARs (accessed by the System catalog). -This nominal and expected exception is eaten (DTDParser.currentDTD not set). - -Since currently there seems to be no use case for DTD/XSD/catalog, -we omit it for Spotless integration. \ No newline at end of file diff --git a/_ext/eclipse-wtp/src/test/resources/xml/expected/dtd_external.test b/_ext/eclipse-wtp/src/test/resources/xml/expected/dtd_external.test deleted file mode 100644 index 6f383afaa7..0000000000 --- a/_ext/eclipse-wtp/src/test/resources/xml/expected/dtd_external.test +++ /dev/null @@ -1,8 +0,0 @@ - - - - indent - this text - preserve - spaces - \ No newline at end of file diff --git a/_ext/eclipse-wtp/src/test/resources/xml/expected/dtd_relative.test b/_ext/eclipse-wtp/src/test/resources/xml/expected/dtd_relative.test deleted file mode 100644 index 37c565592b..0000000000 --- a/_ext/eclipse-wtp/src/test/resources/xml/expected/dtd_relative.test +++ /dev/null @@ -1,8 +0,0 @@ - - - - indent - this text - preserve - spaces - \ No newline at end of file diff --git a/_ext/eclipse-wtp/src/test/resources/xml/expected/xml_space.test b/_ext/eclipse-wtp/src/test/resources/xml/expected/xml_space.test deleted file mode 100644 index 8bc506f692..0000000000 --- a/_ext/eclipse-wtp/src/test/resources/xml/expected/xml_space.test +++ /dev/null @@ -1,4 +0,0 @@ - - foo bar - preserve space - \ No newline at end of file diff --git a/_ext/eclipse-wtp/src/test/resources/xml/expected/xsd_external.test b/_ext/eclipse-wtp/src/test/resources/xml/expected/xsd_external.test deleted file mode 100644 index 0456632618..0000000000 --- a/_ext/eclipse-wtp/src/test/resources/xml/expected/xsd_external.test +++ /dev/null @@ -1,7 +0,0 @@ - - - remove spaces - preserve spaces - \ No newline at end of file diff --git a/_ext/eclipse-wtp/src/test/resources/xml/expected/xsd_not_found.test b/_ext/eclipse-wtp/src/test/resources/xml/expected/xsd_not_found.test deleted file mode 100644 index 78a27d902c..0000000000 --- a/_ext/eclipse-wtp/src/test/resources/xml/expected/xsd_not_found.test +++ /dev/null @@ -1,7 +0,0 @@ - - - remove spaces - preserve spaces - \ No newline at end of file diff --git a/_ext/eclipse-wtp/src/test/resources/xml/expected/xsd_relative.test b/_ext/eclipse-wtp/src/test/resources/xml/expected/xsd_relative.test deleted file mode 100644 index 93e86ab38e..0000000000 --- a/_ext/eclipse-wtp/src/test/resources/xml/expected/xsd_relative.test +++ /dev/null @@ -1,7 +0,0 @@ - - - remove spaces - preserve spaces - \ No newline at end of file diff --git a/_ext/eclipse-wtp/src/test/resources/xml/input/dtd_external.test b/_ext/eclipse-wtp/src/test/resources/xml/input/dtd_external.test deleted file mode 100644 index 1293b55e18..0000000000 --- a/_ext/eclipse-wtp/src/test/resources/xml/input/dtd_external.test +++ /dev/null @@ -1,8 +0,0 @@ - - - - indent - this text - preserve - spaces - \ No newline at end of file diff --git a/_ext/eclipse-wtp/src/test/resources/xml/input/dtd_relative.test b/_ext/eclipse-wtp/src/test/resources/xml/input/dtd_relative.test deleted file mode 100644 index 431354868c..0000000000 --- a/_ext/eclipse-wtp/src/test/resources/xml/input/dtd_relative.test +++ /dev/null @@ -1,8 +0,0 @@ - - - - indent - this text - preserve - spaces - \ No newline at end of file diff --git a/_ext/eclipse-wtp/src/test/resources/xml/input/xml_space.test b/_ext/eclipse-wtp/src/test/resources/xml/input/xml_space.test deleted file mode 100644 index 2ddd865f1c..0000000000 --- a/_ext/eclipse-wtp/src/test/resources/xml/input/xml_space.test +++ /dev/null @@ -1 +0,0 @@ - foo bar preserve space \ No newline at end of file diff --git a/_ext/eclipse-wtp/src/test/resources/xml/input/xsd_external.test b/_ext/eclipse-wtp/src/test/resources/xml/input/xsd_external.test deleted file mode 100644 index e75b7ca06f..0000000000 --- a/_ext/eclipse-wtp/src/test/resources/xml/input/xsd_external.test +++ /dev/null @@ -1,4 +0,0 @@ - - - remove spaces preserve spaces - \ No newline at end of file diff --git a/_ext/eclipse-wtp/src/test/resources/xml/input/xsd_not_found.test b/_ext/eclipse-wtp/src/test/resources/xml/input/xsd_not_found.test deleted file mode 100644 index 483be84785..0000000000 --- a/_ext/eclipse-wtp/src/test/resources/xml/input/xsd_not_found.test +++ /dev/null @@ -1,4 +0,0 @@ - - - remove spaces preserve spaces - \ No newline at end of file diff --git a/_ext/eclipse-wtp/src/test/resources/xml/input/xsd_relative.test b/_ext/eclipse-wtp/src/test/resources/xml/input/xsd_relative.test deleted file mode 100644 index ce8392adf8..0000000000 --- a/_ext/eclipse-wtp/src/test/resources/xml/input/xsd_relative.test +++ /dev/null @@ -1,4 +0,0 @@ - - - remove spaces preserve spaces - \ No newline at end of file diff --git a/_ext/eclipse-wtp/src/test/resources/xml/restrictions/catalog.xml b/_ext/eclipse-wtp/src/test/resources/xml/restrictions/catalog.xml deleted file mode 100644 index 2fba8dc2b9..0000000000 --- a/_ext/eclipse-wtp/src/test/resources/xml/restrictions/catalog.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/_ext/eclipse-wtp/src/test/resources/xml/restrictions/test.dtd b/_ext/eclipse-wtp/src/test/resources/xml/restrictions/test.dtd deleted file mode 100644 index 5076fd91e0..0000000000 --- a/_ext/eclipse-wtp/src/test/resources/xml/restrictions/test.dtd +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/_ext/eclipse-wtp/src/test/resources/xml/restrictions/test.xsd b/_ext/eclipse-wtp/src/test/resources/xml/restrictions/test.xsd deleted file mode 100644 index 6b0e3b5e00..0000000000 --- a/_ext/eclipse-wtp/src/test/resources/xml/restrictions/test.xsd +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/_ext/gradle/java-setup.gradle b/_ext/gradle/java-setup.gradle deleted file mode 100644 index 0007407250..0000000000 --- a/_ext/gradle/java-setup.gradle +++ /dev/null @@ -1,28 +0,0 @@ -////////// -// JAVA // -////////// -apply from: rootProject.file('gradle/changelog.gradle') -version = spotlessChangelog.versionNext -apply from: rootProject.file('gradle/java-setup.gradle') - -// Allow declaration of api/compile dependencies -apply plugin: 'java-library' - -// Show warning locations, fail on warnings -tasks.withType(JavaCompile).configureEach { - options.compilerArgs << "-Xlint:unchecked" - options.compilerArgs << "-Xlint:deprecation" - options.compilerArgs << "-Werror" -} - -//Currently testlib is not used by _ext. Hence the external dependencies are added here. -dependencies { - testImplementation "org.junit.jupiter:junit-jupiter:${VER_JUNIT}" - testImplementation "org.assertj:assertj-core:${VER_ASSERTJ}" - testImplementation projects.testlib - testRuntimeOnly "org.junit.platform:junit-platform-launcher" -} - -tasks.withType(Test).configureEach { - useJUnitPlatform() -} diff --git a/_ext/gradle/p2-fat-jar-setup.gradle b/_ext/gradle/p2-fat-jar-setup.gradle deleted file mode 100644 index 0bba3c43c2..0000000000 --- a/_ext/gradle/p2-fat-jar-setup.gradle +++ /dev/null @@ -1,169 +0,0 @@ -apply from: rootProject.file('_ext/gradle/java-setup.gradle') - -apply plugin: 'com.diffplug.p2.asmaven' - -ext { - // P2 Repository URL - if (!project.hasProperty('p2Repository')) { - p2Repository = "p2Repository not defined in project" - } - // P2 dependencies - if (!project.hasProperty('p2Dependencies')) { - p2Dependencies = "p2Dependencies not defined in project" - } - - // Some JARs may include JARs themselfs, which shall be unpacked and added to the embedded class folder. - if (!project.hasProperty('internalJars')) { - internalJars = [] - } - - // Include form the JARs, which goes into a fat-jar with the spottless formatter interface. - if (!project.hasProperty('jarInclude')) { - jarInclude = [ - '**/*.class', // Take all classes - '**/*.properties', // Text resources (for messages, etc) - '**/*.xml', // Plugin XML and other resources - '*.html', // License information about the included JARs, - 'META-INF/**' // Plugin manifest and addtional information - ] - } - - // Exclude form the JARs, which goes into a fat-jar with the spottless formatter interface. - if (!project.hasProperty('jarExclude')) { - jarExclude = [ - 'META-INF/*.RSA', // The eclipse jars are signed, and our fat-jar breaks the signatures - 'META-INF/*.SF', // ... so all signatures are filtered - ] - } - - // Map fat-JAR resources path if JAR file name does not correspond to plugin package name (e.g. required for internal plugins) - if (!project.hasProperty('fatJarResourcesMap')) { - fatJarResourcesMap = [:] - } - - - // The directory contains all external classes for the fat-jar - embeddedClassesDirName = 'build/embeddedClasses' - embeddedClassesDir = project.file(embeddedClassesDirName) -} - -if (gradle.startParameter.projectProperties.get('com.diffplug.spotless.include.ext.nop2') != 'true') { - // build a maven repo in our build folder containing these artifacts - p2AsMaven { - group 'p2', { - repo project.p2Repository - p2Dependencies.keySet.each { p2.addIU(it) } - p2ant { - /* - Define p2ant proxy settings as a closure. Refer to the API documents for instructions: - https://diffplug.github.io/goomph/javadoc/3.17.4/com/diffplug/gradle/p2/AsMavenPlugin.html - */ - if (project.hasProperty('setP2AntProxy')) { - setP2AntProxy(it) - } - } - } - } -} - -configurations { - embeddedJars // P2 JARs the fat-JAR is based uppon -} - -dependencies { - p2Dependencies.each { groupArtifact, version -> - embeddedJars "p2:${groupArtifact}:${version}" - } - // Includes the classes from P2 JARs during compilation - implementation files(embeddedClassesDir) -} - -jar { - // Add P2 clases to fat-JAR - from embeddedClassesDir -} - -////////////////////////// -// Unpack External Deps // -////////////////////////// -import java.io.File - -task unjarEmbeddedClasses { - description = "Copies filtered set of embedded classes from the Eclise/GrEclipse dependencies to '${project.relativePath(embeddedClassesDir)}'." - inputs.files(configurations.embeddedJars) - inputs.property('internalJars', internalJars) - inputs.property('jarInclude', jarInclude) - inputs.property('jarExclude', jarExclude) - inputs.property('fatJarResourcesMap', fatJarResourcesMap) - outputs.dir(embeddedClassesDir) - - doLast { - embeddedClassesDir.deleteDir() - embeddedClassesDir.mkdirs() - configurations.embeddedJars.each { - unjar(it, embeddedClassesDir) - } - // Unpack internal JARs. Maintain the order defined in internalJars - internalJars.each { - fileTree(embeddedClassesDir).include("${it}.jar").each { - unjar(it, embeddedClassesDir) - delete(it) - } - } - } -} - -def unjar(File jarFile, File destDir) { - ant.unjar(src: jarFile, dest: destDir) { - patternset { - jarInclude.each { - include(name: "${it}") - } - internalJars.each { - include(name: "**/${it}.jar") - } - jarExclude.each { - exclude(name: "${it}") - } - } - } - // Provide Fat JAR resources (following naming convention of spotless-eclipse-base) - def fat_jar_resource_dir = jarFile.getName().split('-')[0] - fat_jar_resource_dir = fatJarResourcesMap.getOrDefault(fat_jar_resource_dir, fat_jar_resource_dir) - ant.move(todir: "${destDir}/${fat_jar_resource_dir}/META-INF", quiet: 'true', failonerror: 'false') { - fileset(dir: "${destDir}/META-INF") - } - //Keep licenses and other human readable information for transparency - ant.move(todir: "${destDir}/${fat_jar_resource_dir}", quiet: 'true') { - fileset(dir: destDir) { - include(name: '*') - type(type: 'file') - exclude(name: '*jar-*') - exclude(name: '*.jar') - } - } - -} - -tasks.compileJava.dependsOn(unjarEmbeddedClasses) - -///////// -// IDE // -///////// - -apply plugin: 'eclipse' - -// always create fresh projects -tasks.eclipse.dependsOn(cleanEclipse) -// Encure that the dependent classes are preovided for compilation if project is build via Eclipse instead of command line -tasks.eclipseClasspath.dependsOn(unjarEmbeddedClasses) - -apply plugin: 'idea' - -// Encure that the dependent classes are preovided for compilation if project is build via Eclipse instead of command line -tasks.idea.dependsOn(unjarEmbeddedClasses) - -tasks.named('ideaModule') { - notCompatibleWithConfigurationCache("https://github.com/gradle/gradle/issues/13480") -} - diff --git a/_ext/gradle/update-lockfile.gradle b/_ext/gradle/update-lockfile.gradle deleted file mode 100644 index 3c23bb860b..0000000000 --- a/_ext/gradle/update-lockfile.gradle +++ /dev/null @@ -1,6 +0,0 @@ -// Use file locking -configurations.configureEach { - resolutionStrategy { - activateDependencyLocking() - } -} diff --git a/settings.gradle b/settings.gradle index 4e81688d29..d01f901ee6 100644 --- a/settings.gradle +++ b/settings.gradle @@ -15,9 +15,6 @@ plugins { id 'com.github.spotbugs' version '6.0.1' apply false // https://github.com/diffplug/spotless-changelog/blob/main/CHANGELOG.md id 'com.diffplug.spotless-changelog' version '3.0.2' apply false - // https://github.com/diffplug/goomph/blob/main/CHANGES.md - // DO NOT UPDATE, see https://github.com/diffplug/spotless/pull/874 - id 'com.diffplug.p2.asmaven' version '3.27.0' apply false // https://github.com/radarsh/gradle-test-logger-plugin/blob/develop/CHANGELOG.md id 'com.adarshr.test-logger' version '4.0.0' apply false // https://github.com/davidburstrom/version-compatibility-gradle-plugin/tags @@ -98,31 +95,3 @@ def getStartProperty(java.lang.String name) { if (System.getenv('SPOTLESS_EXCLUDE_MAVEN') != 'true' && getStartProperty('SPOTLESS_EXCLUDE_MAVEN') != 'true') { include 'plugin-maven' // maven-specific glue code } - -// include external (_ext) projects from development builds -if (getStartProperty('com.diffplug.spotless.include.ext') == 'true') { - file('_ext').eachDirMatch(~/^(?!(\.|gradle)).*/) { dir -> - include dir.name - project(":${dir.name}").projectDir = dir - } -} - -// include external (_ext) projects from development builds, but disable the p2 parts -if (getStartProperty('com.diffplug.spotless.include.ext.nop2') == 'true') { - file('_ext').eachDirMatch(~/^(?!(\.|gradle)).*/) { dir -> - include dir.name - project(":${dir.name}").projectDir = dir - } -} - -// the p2-based projects are too expensive for routine CI builds, so they have to be invoked explicitly -for (kind in [ - 'cdt', - 'groovy', - 'wtp' - ]) { - if (getStartProperty("com.diffplug.spotless.include.ext.${kind}") == 'true') { - include "eclipse-${kind}" - project(":eclipse-${kind}").projectDir = file("_ext/eclipse-${kind}") - } -}