Adding ability to produce output limited by an incoming patch.
diff --git a/.travis.yml b/.travis.yml
index e4effbf..32d137f 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -24,8 +24,8 @@
jdk:
- openjdk11
before_script:
- - wget 'https://www.apache.org/dist/netbeans/netbeans/11.1/netbeans-11.1-bin.zip' -O /tmp/netbeans-11.1-bin.zip
- - (cd $HOME; unzip /tmp/netbeans-11.1-bin.zip)
+ - wget 'https://archive.apache.org/dist/netbeans/netbeans/11.3/netbeans-11.3-bin.zip' -O /tmp/netbeans-11.3-bin.zip
+ - (cd $HOME; unzip /tmp/netbeans-11.3-bin.zip)
- unset _JAVA_OPTIONS
script:
- export JDK11=$JAVA_HOME
diff --git a/cmdline/lib/test/unit/src/org/netbeans/modules/jackpot30/cmdline/lib/CreateStandaloneJar.java b/cmdline/lib/test/unit/src/org/netbeans/modules/jackpot30/cmdline/lib/CreateStandaloneJar.java
index bc095a6..77e5abe 100644
--- a/cmdline/lib/test/unit/src/org/netbeans/modules/jackpot30/cmdline/lib/CreateStandaloneJar.java
+++ b/cmdline/lib/test/unit/src/org/netbeans/modules/jackpot30/cmdline/lib/CreateStandaloneJar.java
@@ -563,6 +563,8 @@
"org.openide.",
"org.apache.",
"net.bytebuddy.",
- "joptsimple."
+ "joptsimple.",
+ "io.reflectoring.diffparser.",
+ "org.slf4j."
));
}
diff --git a/cmdline/maven/tests/sl-17/jackpot-settings.xml b/cmdline/maven/tests/sl-17/jackpot-settings.xml
index a0a69de..0461d8a 100644
--- a/cmdline/maven/tests/sl-17/jackpot-settings.xml
+++ b/cmdline/maven/tests/sl-17/jackpot-settings.xml
@@ -22,5 +22,8 @@
<node name="Javac_canUseLambda">
<attribute name="enabled" value="true"/>
</node>
+ <node name="org.netbeans.modules.java.hints.AddOverrideAnnotation">
+ <attribute name="enabled" value="false"/>
+ </node>
</tool>
</configuration>
diff --git a/cmdline/maven/tests/sl-18/jackpot-settings.xml b/cmdline/maven/tests/sl-18/jackpot-settings.xml
index a0a69de..0461d8a 100644
--- a/cmdline/maven/tests/sl-18/jackpot-settings.xml
+++ b/cmdline/maven/tests/sl-18/jackpot-settings.xml
@@ -22,5 +22,8 @@
<node name="Javac_canUseLambda">
<attribute name="enabled" value="true"/>
</node>
+ <node name="org.netbeans.modules.java.hints.AddOverrideAnnotation">
+ <attribute name="enabled" value="false"/>
+ </node>
</tool>
</configuration>
diff --git a/cmdline/tool/build.xml b/cmdline/tool/build.xml
index b57d509..2fca89f 100644
--- a/cmdline/tool/build.xml
+++ b/cmdline/tool/build.xml
@@ -31,7 +31,24 @@
skipexisting="true"/>
</target>
- <target name="build-init" depends="harness.build-init,-download-joptsimple" />
+ <target name="-download-diffparser">
+ <mkdir dir="build" />
+ <get src="https://repo1.maven.org/maven2/io/reflectoring/diffparser/diffparser/1.4/diffparser-1.4.jar"
+ dest="build/diffparser-1.4.jar"
+ skipexisting="true"/>
+ </target>
+
+ <target name="-download-slf4j">
+ <mkdir dir="build" />
+ <get src="https://repo1.maven.org/maven2/org/slf4j/slf4j-api/1.7.25/slf4j-api-1.7.25.jar"
+ dest="build/slf4j-api-1.7.25.jar"
+ skipexisting="true"/>
+ <get src="https://repo1.maven.org/maven2/org/slf4j/slf4j-nop/1.7.25/slf4j-nop-1.7.25.jar"
+ dest="build/slf4j-nop-1.7.25.jar"
+ skipexisting="true"/>
+ </target>
+
+ <target name="build-init" depends="harness.build-init,-download-joptsimple,-download-diffparser,-download-slf4j" />
<target name="create-standalone-tool" depends="init,netbeans">
<mkdir dir="${build.classes.dir}/../jackpot" />
diff --git a/cmdline/tool/nbproject/project.properties b/cmdline/tool/nbproject/project.properties
index 72ed17b..eaafa90 100644
--- a/cmdline/tool/nbproject/project.properties
+++ b/cmdline/tool/nbproject/project.properties
@@ -15,6 +15,6 @@
javac.source=1.8
javac.compilerargs=-Xlint -Xlint:-serial
-cp.extra=build/jopt-simple-3.2.jar:${tools.jar}
+cp.extra=build/jopt-simple-3.2.jar:build/diffparser-1.4.jar:build/slf4j-api-1.7.25.jar:build/slf4j-nop-1.7.25.jar:${tools.jar}
spec.version.base=1.16.0
test.timeout=6000000
diff --git a/cmdline/tool/scripts/LICENSE-bin-tool.txt b/cmdline/tool/scripts/LICENSE-bin-tool.txt
index 7b03741..5f3f417 100644
--- a/cmdline/tool/scripts/LICENSE-bin-tool.txt
+++ b/cmdline/tool/scripts/LICENSE-bin-tool.txt
@@ -804,3 +804,225 @@
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
+
+**********************************************************************
+
+This product includes diffparser with the following license:
+
+Apache License
+Version 2.0, January 2004
+http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+"License" shall mean the terms and conditions for use, reproduction, and
+distribution as defined by Sections 1 through 9 of this document.
+
+"Licensor" shall mean the copyright owner or entity authorized by the copyright
+owner that is granting the License.
+
+"Legal Entity" shall mean the union of the acting entity and all other entities
+that control, are controlled by, or are under common control with that entity.
+For the purposes of this definition, "control" means (i) the power, direct or
+indirect, to cause the direction or management of such entity, whether by
+contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
+outstanding shares, or (iii) beneficial ownership of such entity.
+
+"You" (or "Your") shall mean an individual or Legal Entity exercising
+permissions granted by this License.
+
+"Source" form shall mean the preferred form for making modifications, including
+but not limited to software source code, documentation source, and configuration
+files.
+
+"Object" form shall mean any form resulting from mechanical transformation or
+translation of a Source form, including but not limited to compiled object code,
+generated documentation, and conversions to other media types.
+
+"Work" shall mean the work of authorship, whether in Source or Object form, made
+available under the License, as indicated by a copyright notice that is included
+in or attached to the work (an example is provided in the Appendix below).
+
+"Derivative Works" shall mean any work, whether in Source or Object form, that
+is based on (or derived from) the Work and for which the editorial revisions,
+annotations, elaborations, or other modifications represent, as a whole, an
+original work of authorship. For the purposes of this License, Derivative Works
+shall not include works that remain separable from, or merely link (or bind by
+name) to the interfaces of, the Work and Derivative Works thereof.
+
+"Contribution" shall mean any work of authorship, including the original version
+of the Work and any modifications or additions to that Work or Derivative Works
+thereof, that is intentionally submitted to Licensor for inclusion in the Work
+by the copyright owner or by an individual or Legal Entity authorized to submit
+on behalf of the copyright owner. For the purposes of this definition,
+"submitted" means any form of electronic, verbal, or written communication sent
+to the Licensor or its representatives, including but not limited to
+communication on electronic mailing lists, source code control systems, and
+issue tracking systems that are managed by, or on behalf of, the Licensor for
+the purpose of discussing and improving the Work, but excluding communication
+that is conspicuously marked or otherwise designated in writing by the copyright
+owner as "Not a Contribution."
+
+"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
+of whom a Contribution has been received by Licensor and subsequently
+incorporated within the Work.
+
+2. Grant of Copyright License.
+
+Subject to the terms and conditions of this License, each Contributor hereby
+grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
+irrevocable copyright license to reproduce, prepare Derivative Works of,
+publicly display, publicly perform, sublicense, and distribute the Work and such
+Derivative Works in Source or Object form.
+
+3. Grant of Patent License.
+
+Subject to the terms and conditions of this License, each Contributor hereby
+grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
+irrevocable (except as stated in this section) patent license to make, have
+made, use, offer to sell, sell, import, and otherwise transfer the Work, where
+such license applies only to those patent claims licensable by such Contributor
+that are necessarily infringed by their Contribution(s) alone or by combination
+of their Contribution(s) with the Work to which such Contribution(s) was
+submitted. If You institute patent litigation against any entity (including a
+cross-claim or counterclaim in a lawsuit) alleging that the Work or a
+Contribution incorporated within the Work constitutes direct or contributory
+patent infringement, then any patent licenses granted to You under this License
+for that Work shall terminate as of the date such litigation is filed.
+
+4. Redistribution.
+
+You may reproduce and distribute copies of the Work or Derivative Works thereof
+in any medium, with or without modifications, and in Source or Object form,
+provided that You meet the following conditions:
+
+You must give any other recipients of the Work or Derivative Works a copy of
+this License; and
+You must cause any modified files to carry prominent notices stating that You
+changed the files; and
+You must retain, in the Source form of any Derivative Works that You distribute,
+all copyright, patent, trademark, and attribution notices from the Source form
+of the Work, excluding those notices that do not pertain to any part of the
+Derivative Works; and
+If the Work includes a "NOTICE" text file as part of its distribution, then any
+Derivative Works that You distribute must include a readable copy of the
+attribution notices contained within such NOTICE file, excluding those notices
+that do not pertain to any part of the Derivative Works, in at least one of the
+following places: within a NOTICE text file distributed as part of the
+Derivative Works; within the Source form or documentation, if provided along
+with the Derivative Works; or, within a display generated by the Derivative
+Works, if and wherever such third-party notices normally appear. The contents of
+the NOTICE file are for informational purposes only and do not modify the
+License. You may add Your own attribution notices within Derivative Works that
+You distribute, alongside or as an addendum to the NOTICE text from the Work,
+provided that such additional attribution notices cannot be construed as
+modifying the License.
+You may add Your own copyright statement to Your modifications and may provide
+additional or different license terms and conditions for use, reproduction, or
+distribution of Your modifications, or for any such Derivative Works as a whole,
+provided Your use, reproduction, and distribution of the Work otherwise complies
+with the conditions stated in this License.
+
+5. Submission of Contributions.
+
+Unless You explicitly state otherwise, any Contribution intentionally submitted
+for inclusion in the Work by You to the Licensor shall be under the terms and
+conditions of this License, without any additional terms or conditions.
+Notwithstanding the above, nothing herein shall supersede or modify the terms of
+any separate license agreement you may have executed with Licensor regarding
+such Contributions.
+
+6. Trademarks.
+
+This License does not grant permission to use the trade names, trademarks,
+service marks, or product names of the Licensor, except as required for
+reasonable and customary use in describing the origin of the Work and
+reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty.
+
+Unless required by applicable law or agreed to in writing, Licensor provides the
+Work (and each Contributor provides its Contributions) 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. You are
+solely responsible for determining the appropriateness of using or
+redistributing the Work and assume any risks associated with Your exercise of
+permissions under this License.
+
+8. Limitation of Liability.
+
+In no event and under no legal theory, whether in tort (including negligence),
+contract, or otherwise, unless required by applicable law (such as deliberate
+and grossly negligent acts) or agreed to in writing, shall any Contributor be
+liable to You for damages, including any direct, indirect, special, incidental,
+or consequential damages of any character arising as a result of this License or
+out of the use or inability to use the Work (including but not limited to
+damages for loss of goodwill, work stoppage, computer failure or malfunction, or
+any and all other commercial damages or losses), even if such Contributor has
+been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability.
+
+While redistributing the Work or Derivative Works thereof, You may choose to
+offer, and charge a fee for, acceptance of support, warranty, indemnity, or
+other liability obligations and/or rights consistent with this License. However,
+in accepting such obligations, You may act only on Your own behalf and on Your
+sole responsibility, not on behalf of any other Contributor, and only if You
+agree to indemnify, defend, and hold each Contributor harmless for any liability
+incurred by, or claims asserted against, such Contributor by reason of your
+accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Apache License to your work
+
+To apply the Apache License to your work, attach the following boilerplate
+notice, with the fields enclosed by brackets "[]" replaced with your own
+identifying information. (Don't include the brackets!) The text should be
+enclosed in the appropriate comment syntax for the file format. We also
+recommend that a file or class name and description of purpose be included on
+the same "printed page" as the copyright notice for easier identification within
+third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ 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.
+
+**********************************************************************
+
+This product includes SLF4J with the following license:
+
+ Copyright (c) 2004-2017 QOS.ch
+ All rights reserved.
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/cmdline/tool/scripts/NOTICE-bin-tool.txt b/cmdline/tool/scripts/NOTICE-bin-tool.txt
index 7e10be0..5435951 100644
--- a/cmdline/tool/scripts/NOTICE-bin-tool.txt
+++ b/cmdline/tool/scripts/NOTICE-bin-tool.txt
@@ -109,3 +109,5 @@
This product includes code (JaspellTernarySearchTrie) from Java Spelling Checking Package (jaspell): http://jaspell.sourceforge.net/
License: The BSD License (http://www.opensource.org/licenses/bsd-license.php)
+This product includes diffparser:
+Copyright 2013-2017 Tom Hombergs (tom.hombergs@gmail.com | http://reflectoring.io)
diff --git a/cmdline/tool/src/org/netbeans/modules/jackpot30/cmdline/Main.java b/cmdline/tool/src/org/netbeans/modules/jackpot30/cmdline/Main.java
index e97cc9f..62a64af 100644
--- a/cmdline/tool/src/org/netbeans/modules/jackpot30/cmdline/Main.java
+++ b/cmdline/tool/src/org/netbeans/modules/jackpot30/cmdline/Main.java
@@ -19,6 +19,11 @@
package org.netbeans.modules.jackpot30.cmdline;
+import io.reflectoring.diffparser.api.DiffParser;
+import io.reflectoring.diffparser.api.UnifiedDiffParser;
+import io.reflectoring.diffparser.api.model.Diff;
+import io.reflectoring.diffparser.api.model.Hunk;
+import io.reflectoring.diffparser.api.model.Line;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
@@ -29,6 +34,7 @@
import java.io.PrintStream;
import java.io.UncheckedIOException;
import java.io.Writer;
+import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
@@ -52,6 +58,7 @@
import java.util.prefs.Preferences;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
+import java.util.stream.StreamSupport;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeListener;
import joptsimple.ArgumentAcceptingOptionSpec;
@@ -71,6 +78,8 @@
import org.netbeans.modules.java.hints.declarative.test.TestPerformer.TestClassPathProvider;
import org.netbeans.modules.java.hints.jackpot.spi.PatternConvertor;
import org.netbeans.modules.java.hints.providers.spi.HintDescription;
+import org.netbeans.modules.java.hints.providers.spi.HintDescription.Worker;
+import org.netbeans.modules.java.hints.providers.spi.HintDescriptionFactory;
import org.netbeans.modules.java.hints.providers.spi.HintMetadata;
import org.netbeans.modules.java.hints.providers.spi.HintMetadata.Options;
import org.netbeans.modules.java.hints.spiimpl.MessageImpl;
@@ -78,6 +87,7 @@
import org.netbeans.modules.java.hints.spiimpl.batch.BatchSearch;
import org.netbeans.modules.java.hints.spiimpl.batch.BatchSearch.BatchResult;
import org.netbeans.modules.java.hints.spiimpl.batch.BatchSearch.Folder;
+import org.netbeans.modules.java.hints.spiimpl.batch.BatchSearch.IndexEnquirer;
import org.netbeans.modules.java.hints.spiimpl.batch.BatchSearch.Resource;
import org.netbeans.modules.java.hints.spiimpl.batch.BatchSearch.VerifiedSpansCallBack;
import org.netbeans.modules.java.hints.spiimpl.batch.BatchUtilities;
@@ -95,9 +105,12 @@
import org.netbeans.spi.java.classpath.ClassPathProvider;
import org.netbeans.spi.java.classpath.support.ClassPathSupport;
import org.netbeans.spi.java.hints.Hint.Kind;
+import org.netbeans.spi.java.hints.HintContext;
import org.netbeans.spi.java.queries.SourceLevelQueryImplementation2;
+import org.openide.cookies.EditorCookie;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
+import org.openide.text.PositionRef;
import org.openide.util.Exceptions;
import org.openide.util.Lookup;
import org.openide.util.Pair;
@@ -143,6 +156,7 @@
ArgumentAcceptingOptionSpec<String> config = parser.accepts("config", "configurations").withRequiredArg().ofType(String.class);
ArgumentAcceptingOptionSpec<File> hintFile = parser.accepts("hint-file", "file with rules that should be performed").withRequiredArg().ofType(File.class);
ArgumentAcceptingOptionSpec<String> group = parser.accepts("group", "specify roots to process alongside with their classpath").withRequiredArg().ofType(String.class);
+ ArgumentAcceptingOptionSpec<File> patchFile = parser.accepts("filter-patch", "patch file, which will be used to filter the output").withRequiredArg().ofType(File.class);
parser.accepts("list", "list all known hints");
parser.accepts("progress", "show progress");
@@ -317,7 +331,7 @@
GroupResult result = GroupResult.NOTHING_TO_DO;
try (Writer outS = parsed.has(out) ? new BufferedWriter(new OutputStreamWriter(new FileOutputStream(parsed.valueOf(out)))) : null) {
- GlobalConfiguration globalConfig = new GlobalConfiguration(hintSettingsPreferences, apply, runDeclarative, runDeclarativeTests, useDefaultEnabledSetting, parsed.valueOf(hint), parsed.valueOf(hintFile), outS, parsed.has(OPTION_FAIL_ON_WARNINGS));
+ GlobalConfiguration globalConfig = new GlobalConfiguration(hintSettingsPreferences, apply, runDeclarative, runDeclarativeTests, useDefaultEnabledSetting, parsed.valueOf(hint), parsed.valueOf(hintFile), parsed.valueOf(patchFile), outS, parsed.has(OPTION_FAIL_ON_WARNINGS));
for (RootConfiguration groupConfig : groups) {
result = result.join(handleGroup(groupConfig, progress, globalConfig, parsed.valuesOf(config)));
@@ -526,17 +540,36 @@
}
RootConfiguration prevConfig = currentRootConfiguration.get();
+ PatchDescription patch;
+
+ if (globalConfig.patchFile != null) {
+ patch = createPatchDescription(rootConfiguration, globalConfig.patchFile);
+
+ if (patch.file2AddedLines.isEmpty()) {
+ return GroupResult.SUCCESS;
+ }
+
+ hints = filterHints(hints, patch);
+ } else {
+ patch = null;
+ }
try {
currentRootConfiguration.set(rootConfiguration);
try {
+ ProgressHandleWrapper nestedProgress = progress.startNextPartWithEmbedding(1, 1);
+ BatchSearch.Scope scope = Scopes.specifiedFoldersScope(rootConfiguration.rootFolders.toArray(new Folder[0]));
+ BatchResult occurrences = BatchSearch.findOccurrences(hints, scope, nestedProgress, hintSettings);
+
+ occurrences = filterBatchResult(occurrences, patch);
+
if (globalConfig.apply) {
- apply(hints, rootConfiguration.rootFolders.toArray(new Folder[0]), progress, hintSettings, globalConfig.out);
+ apply(nestedProgress, occurrences, globalConfig.out);
return GroupResult.SUCCESS; //TODO: WarningsAndErrors?
} else {
- findOccurrences(hints, rootConfiguration.rootFolders.toArray(new Folder[0]), progress, hintSettings, wae);
+ findOccurrences(nestedProgress, occurrences, hints, wae);
if (wae.errors != 0 || (wae.warnings != 0 && globalConfig.failOnWarnings)) {
return GroupResult.FAILURE;
@@ -552,6 +585,95 @@
}
}
+ private static PatchDescription createPatchDescription(RootConfiguration rootConfiguration, File patchFile) throws IOException {
+ Map<FileObject, Set<Integer>> file2AddedLines = new HashMap<>();
+ DiffParser p = new UnifiedDiffParser();
+ List<Diff> diffs = p.parse(patchFile);
+
+ for (Diff diff : diffs) {
+ String fileName = diff.getToFileName();
+ FileObject resolvedTarget = null;
+ OUTER:
+ while (!fileName.isEmpty()) {
+ for (Folder f : rootConfiguration.rootFolders) {
+ resolvedTarget = f.getFileObject().getFileObject(fileName);
+ if (resolvedTarget != null) {
+ break OUTER;
+ }
+ }
+ int slash = fileName.indexOf("/");
+ if (slash == (-1)) break;
+ fileName = fileName.substring(slash + 1);
+ }
+ if (resolvedTarget == null) {
+ //TODO: warning?
+ continue;
+ }
+ Set<Integer> includedLines = new HashSet<>();
+ for (Hunk hunk : diff.getHunks()) {
+ int newLine = hunk.getToFileRange().getLineStart();
+ for (Line l : hunk.getLines()) {
+ switch (l.getLineType()) {
+ case FROM: break;
+ case NEUTRAL: newLine++; break;
+ case TO:
+ includedLines.add(newLine);
+ newLine++;
+ break;
+ }
+ }
+ }
+ file2AddedLines.put(resolvedTarget, includedLines);
+ }
+
+ return new PatchDescription(file2AddedLines);
+ }
+
+ private static Iterable<? extends HintDescription> filterHints(Iterable<? extends HintDescription> hints, PatchDescription patch) {
+ class FilteringWorker implements Worker {
+ private final PatchDescription patch;
+ private final Worker delegate;
+
+ public FilteringWorker(PatchDescription patch, Worker delegate) {
+ this.patch = patch;
+ this.delegate = delegate;
+ }
+
+ @Override
+ public Collection<? extends ErrorDescription> createErrors(HintContext ctx) {
+ Collection<? extends ErrorDescription> errors = delegate.createErrors(ctx);
+ return errors != null ? errors.stream().filter(ed -> patch.included(ed)).collect(Collectors.toList()) : null;
+ }
+
+ }
+
+ return StreamSupport.stream(hints.spliterator(), false)
+ .map(hd -> HintDescriptionFactory.create()
+ .setHintText(hd.getHintText())
+ .setMetadata(hd.getMetadata())
+ .setTrigger(hd.getTrigger())
+ .setAdditionalConstraints(hd.getAdditionalConstraints())
+ .setWorker(new FilteringWorker(patch, hd.getWorker()))
+ .produce())
+ .collect(Collectors.toList());
+ }
+
+ private static BatchResult filterBatchResult(BatchResult result, PatchDescription patch) {
+ try {
+ if (patch == null) return result;
+ Field f = result.getClass().getDeclaredField("projectId2Resources");
+ Map<? extends IndexEnquirer, ? extends Collection<? extends Resource>> projectId2Resources = (Map<? extends BatchSearch.IndexEnquirer, ? extends Collection<? extends Resource>>) f.get(result);
+ Map<IndexEnquirer, Collection<? extends Resource>> filteredProjectId2Resources = new HashMap<>();
+ for (Entry<? extends IndexEnquirer, ? extends Collection<? extends Resource>> e : projectId2Resources.entrySet()) {
+ filteredProjectId2Resources.put(e.getKey(), e.getValue().stream().filter(r -> patch.included(r.getResolvedFile())).collect(Collectors.toList()));
+ }
+ return new BatchResult(projectId2Resources, result.problems);
+ } catch (ReflectiveOperationException ex) {
+ Exceptions.printStackTrace(ex);
+ return result;
+ }
+ }
+
private static class MemoryPreferences extends AbstractPreferences {
private final Map<String, String> values = new HashMap<>();
@@ -698,13 +820,11 @@
System.setProperty("RepositoryUpdate.increasedLogLevel", "OFF");
}
- private static void findOccurrences(Iterable<? extends HintDescription> descs, Folder[] sourceRoot, ProgressHandleWrapper progress, HintsSettings settings, final WarningsAndErrors wae) throws IOException {
+ private static void findOccurrences(ProgressHandleWrapper progress, BatchResult rawOccurrences, Iterable<? extends HintDescription> descs, final WarningsAndErrors wae) throws IOException {
final Map<String, String> id2DisplayName = Utils.computeId2DisplayName(descs);
- ProgressHandleWrapper w = progress.startNextPartWithEmbedding(1, 1);
- BatchResult occurrences = BatchSearch.findOccurrences(descs, Scopes.specifiedFoldersScope(sourceRoot), w, settings);
List<MessageImpl> problems = new LinkedList<MessageImpl>();
- BatchSearch.getVerifiedSpans(occurrences, w, new VerifiedSpansCallBack() {
+ BatchSearch.getVerifiedSpans(rawOccurrences, progress, new VerifiedSpansCallBack() {
@Override public void groupStarted() {}
@Override public boolean spansVerified(CompilationController wc, Resource r, Collection<? extends ErrorDescription> hints) throws Exception {
hints = hints.stream()
@@ -752,12 +872,9 @@
System.out.println(b);
}
- private static void apply(Iterable<? extends HintDescription> descs, Folder[] sourceRoot, ProgressHandleWrapper progress, HintsSettings settings, Writer out) throws IOException {
- ProgressHandleWrapper w = progress.startNextPartWithEmbedding(1, 1);
- BatchResult occurrences = BatchSearch.findOccurrences(descs, Scopes.specifiedFoldersScope(sourceRoot), w, settings);
-
+ private static void apply(ProgressHandleWrapper progress, BatchResult rawOccurrences, Writer out) throws IOException {
List<MessageImpl> problems = new LinkedList<MessageImpl>();
- Collection<ModificationResult> diffs = BatchUtilities.applyFixes(occurrences, w, new AtomicBoolean(), new ArrayList<RefactoringElementImplementation>(), null, true, problems);
+ Collection<ModificationResult> diffs = BatchUtilities.applyFixes(rawOccurrences, progress, new AtomicBoolean(), new ArrayList<RefactoringElementImplementation>(), null, true, problems);
if (out != null) {
for (ModificationResult mr : diffs) {
@@ -904,10 +1021,11 @@
private final boolean useDefaultEnabledSetting;
private final String hint;
private final File hintFile;
+ private final File patchFile;
private final Writer out;
private final boolean failOnWarnings;
- public GlobalConfiguration(Preferences configurationPreferences, boolean apply, boolean runDeclarative, boolean runDeclarativeTests, boolean useDefaultEnabledSetting, String hint, File hintFile, Writer out, boolean failOnWarnings) {
+ public GlobalConfiguration(Preferences configurationPreferences, boolean apply, boolean runDeclarative, boolean runDeclarativeTests, boolean useDefaultEnabledSetting, String hint, File hintFile, File patchFile, Writer out, boolean failOnWarnings) {
this.configurationPreferences = configurationPreferences;
this.apply = apply;
this.runDeclarative = runDeclarative;
@@ -915,6 +1033,7 @@
this.useDefaultEnabledSetting = useDefaultEnabledSetting;
this.hint = hint;
this.hintFile = hintFile;
+ this.patchFile = patchFile;
this.out = out;
this.failOnWarnings = failOnWarnings;
}
@@ -1090,4 +1209,63 @@
}
}
+
+ private static class PatchDescription {
+ private final Map<FileObject, Set<Integer>> file2AddedLines;
+ private final Map<FileObject, int[]> file2LineStarts = new HashMap<>();
+
+ private PatchDescription(Map<FileObject, Set<Integer>> file2AddedLines) {
+ this.file2AddedLines = file2AddedLines;
+ }
+
+ public boolean included(FileObject file) {
+ return file2AddedLines.containsKey(file);
+ }
+
+ public boolean included(ErrorDescription error) {
+ int startLine = findLineForPos(file2LineStarts, error.getFile(), error.getRange().getBegin());
+ int endLine = findLineForPos(file2LineStarts, error.getFile(), error.getRange().getBegin());
+ Set<Integer> addedLines = file2AddedLines.get(error.getFile());
+
+ if (addedLines == null) {
+ return false;
+ }
+
+ for (int line = startLine; line <= endLine; line++) {
+ if (addedLines.contains(line)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ }
+
+ private static int findLineForPos(Map<FileObject, int[]> file2LineStartsCache, FileObject file, PositionRef pos) {
+ return findLineForPos(file2LineStartsCache, file, pos.getOffset());
+ }
+
+ static int findLineForPos(Map<FileObject, int[]> file2LineStartsCache, FileObject file, int offset) {
+ int[] lineStarts = file2LineStartsCache.computeIfAbsent(file, x -> lineStarts(file));
+ int line = Arrays.binarySearch(lineStarts, offset);
+ if (line < 0) return -line - 1;
+ else return line + 1;
+ }
+
+ private static int[] lineStarts(FileObject file) {
+ try {
+ List<Integer> lineStarts = new ArrayList<>();
+
+ lineStarts.add(0);
+
+ for (String line : file.asLines()) {
+ lineStarts.add(lineStarts.get(lineStarts.size() - 1) + line.length() + 1);
+ }
+
+ return lineStarts.stream().mapToInt(ls -> ls).toArray();
+ } catch (IOException ex) {
+ return new int[1];
+ }
+ }
}
diff --git a/cmdline/tool/test/unit/src/org/netbeans/modules/jackpot30/cmdline/CreateTool.java b/cmdline/tool/test/unit/src/org/netbeans/modules/jackpot30/cmdline/CreateTool.java
index 2b04b7b..4b9b021 100644
--- a/cmdline/tool/test/unit/src/org/netbeans/modules/jackpot30/cmdline/CreateTool.java
+++ b/cmdline/tool/test/unit/src/org/netbeans/modules/jackpot30/cmdline/CreateTool.java
@@ -45,7 +45,7 @@
@Override
protected Info computeInfo() {
- return new Info().addAdditionalRoots(Main.class.getName(), DeclarativeHintsTestBase.class.getName(), OpenProjectsTrampolineImpl.class.getName(), J2SEProject.class.getName(), DefaultJavaPlatformProvider.class.getName(), PatternConvertorImpl.class.getName(), ProcessorImpl.class.getName(), BCPFallBack.class.getName())
+ return new Info().addAdditionalRoots(Main.class.getName(), DeclarativeHintsTestBase.class.getName(), OpenProjectsTrampolineImpl.class.getName(), J2SEProject.class.getName(), DefaultJavaPlatformProvider.class.getName(), PatternConvertorImpl.class.getName(), ProcessorImpl.class.getName(), BCPFallBack.class.getName(), "org.slf4j.impl.StaticLoggerBinder")
.addAdditionalResources("org/netbeans/modules/java/hints/resources/Bundle.properties", "org/netbeans/modules/java/hints/declarative/resources/Bundle.properties", "org/netbeans/modules/jackpot30/cmdline/cfg_hints.xml")
.addAdditionalLayers("org/netbeans/modules/java/hints/resources/layer.xml", "org/netbeans/modules/java/hints/declarative/resources/layer.xml")
.addMetaInfRegistrations(new MetaInfRegistration(org.netbeans.modules.project.uiapi.OpenProjectsTrampoline.class, OpenProjectsTrampolineImpl.class))
diff --git a/cmdline/tool/test/unit/src/org/netbeans/modules/jackpot30/cmdline/MainTest.java b/cmdline/tool/test/unit/src/org/netbeans/modules/jackpot30/cmdline/MainTest.java
index 5be9315..7595365 100644
--- a/cmdline/tool/test/unit/src/org/netbeans/modules/jackpot30/cmdline/MainTest.java
+++ b/cmdline/tool/test/unit/src/org/netbeans/modules/jackpot30/cmdline/MainTest.java
@@ -22,13 +22,18 @@
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
import java.io.PrintStream;
+import java.io.Writer;
+import java.lang.annotation.RetentionPolicy;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
import java.util.Collections;
+import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
@@ -37,6 +42,8 @@
import javax.tools.ToolProvider;
import org.junit.runner.Result;
import org.netbeans.junit.NbTestCase;
+import org.openide.filesystems.FileObject;
+import org.openide.filesystems.FileUtil;
/**XXX: should also test error conditions
*
@@ -917,6 +924,118 @@
"@" + getWorkDirPath() + "/parameters.txt");
}
+ public void testPatchWarnings() throws Exception {
+ String golden =
+ "package test;\n" +
+ "public class Test {\n" +
+ " private void test(java.util.Collection c) {\n" +
+ " boolean b = c.size() == 0;\n" +
+ " boolean b2 = c.size() == 0;\n" +
+ "\n" +
+ " boolean b3 = c.size() == 0;\n" +
+ " }\n" +
+ "}\n";
+
+ doRunCompiler(golden,
+ "${workdir}/src/test/Test.java:5: warning: [Usage_of_size_equals_0] Usage of .size() == 0 can be replaced with .isEmpty()\n" +
+ " boolean b2 = c.size() == 0;\n" +
+ " ^\n" +
+ "${workdir}/src/test/Test.java:7: warning: [Usage_of_size_equals_0] Usage of .size() == 0 can be replaced with .isEmpty()\n" +
+ " boolean b3 = c.size() == 0;\n" +
+ " ^\n",
+ "",
+ "src/test/Test.java",
+ golden,
+ "patch.diff",
+ "diff --git a/src/test/Test.java b/src/test/Test.java\n" +
+ "index 100a838..cc6a6c0 100644\n" +
+ "--- a/src/test/Test.java\n" +
+ "+++ b/src/test/Test.java\n" +
+ "@@ -2,6 +2,8 @@ package test;\n" +
+ " public class Test {\n" +
+ " private void test(java.util.Collection c) {\n" +
+ " boolean b = c.size() == 0;\n" +
+ "- boolean b = c.size() == 0;\n" +
+ "+ boolean b2 = c.size() == 0;\n" +
+ "+\n" +
+ "+ boolean b3 = c.size() == 0;\n" +
+ " }\n" +
+ " }\n",
+ null,
+ "--source", "8",
+ "--sourcepath", "${workdir}/src",
+ "--hint", "Usage of .size() == 0",
+ "--filter-patch", getWorkDirPath() + "/patch.diff");
+ }
+
+ public void testPatchApply() throws Exception {
+ String golden =
+ "package test;\n" +
+ "public class Test {\n" +
+ " private void test(java.util.Collection c) {\n" +
+ " boolean b = c.size() == 0;\n" +
+ " boolean b2 = c.isEmpty();\n" +
+ "\n" +
+ " boolean b3 = c.isEmpty();\n" +
+ " }\n" +
+ "}\n";
+
+ doRunCompiler(golden,
+ null,
+ null,
+ "src/test/Test.java",
+ "package test;\n" +
+ "public class Test {\n" +
+ " private void test(java.util.Collection c) {\n" +
+ " boolean b = c.size() == 0;\n" +
+ " boolean b2 = c.size() == 0;\n" +
+ "\n" +
+ " boolean b3 = c.size() == 0;\n" +
+ " }\n" +
+ "}\n",
+ "patch.diff",
+ "diff --git a/src/test/Test.java b/src/test/Test.java\n" +
+ "index 100a838..cc6a6c0 100644\n" +
+ "--- a/src/test/Test.java\n" +
+ "+++ b/src/test/Test.java\n" +
+ "@@ -2,6 +2,8 @@ package test;\n" +
+ " public class Test {\n" +
+ " private void test(java.util.Collection c) {\n" +
+ " boolean b = c.size() == 0;\n" +
+ "- boolean b = c.size() == 0;\n" +
+ "+ boolean b2 = c.size() == 0;\n" +
+ "+\n" +
+ "+ boolean b3 = c.size() == 0;\n" +
+ " }\n" +
+ " }\n",
+ null,
+ "--apply",
+ "--source", "8",
+ "--sourcepath", "${workdir}/src",
+ "--hint", "Usage of .size() == 0",
+ "--filter-patch", getWorkDirPath() + "/patch.diff");
+ }
+
+ public void testLineNumber() throws Exception {
+ FileObject root = FileUtil.createMemoryFileSystem().getRoot();
+ FileObject test1 = root.createData("Test1.java");
+ try (OutputStream sout = test1.getOutputStream();
+ Writer out = new OutputStreamWriter(sout)) {
+ out.write("123456\n" +
+ "1234567\r\n" +
+ "12345");
+ }
+ assertEquals(1, Main.findLineForPos(new HashMap<FileObject, int[]>(), test1, 0));
+ assertEquals(1, Main.findLineForPos(new HashMap<FileObject, int[]>(), test1, 1));
+ assertEquals(1, Main.findLineForPos(new HashMap<FileObject, int[]>(), test1, 6));
+ assertEquals(2, Main.findLineForPos(new HashMap<FileObject, int[]>(), test1, 7));
+ assertEquals(2, Main.findLineForPos(new HashMap<FileObject, int[]>(), test1, 8));
+ assertEquals(2, Main.findLineForPos(new HashMap<FileObject, int[]>(), test1, 14));
+ assertEquals(3, Main.findLineForPos(new HashMap<FileObject, int[]>(), test1, 15));
+ assertEquals(3, Main.findLineForPos(new HashMap<FileObject, int[]>(), test1, 16));
+ assertEquals(3, Main.findLineForPos(new HashMap<FileObject, int[]>(), test1, 20));
+ }
+
private static final String DONT_APPEND_PATH = new String("DONT_APPEND_PATH");
private static final String IGNORE = new String("IGNORE");