-
Notifications
You must be signed in to change notification settings - Fork 25.2k
converting ForbiddenPatternsTask to .java #36194
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
alpar-t
merged 15 commits into
elastic:master
from
cdschneider:replace-groovy-forbidden-task
Dec 11, 2018
Merged
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
dad2baf
converting ForbiddenPatternsTask w java impl & unit tests
2a1db23
Merge commit 'd036e0ca89924b24860ca0b4fd9b442a4356f398' into replace-…
alpar-t 3972bec
taking approach of excluding non-UTF-8 files in server project
5bc17f4
not needing to use temp folder for ProjectBuilder
8810227
consolidating redundant test/assertions in ForbiddenPatternsTaskTest,…
cc65469
adding writeSourceFile helper, per suggestion
5c9f93a
removing need for class-level var for outputMarker, also updating tes…
c665e4a
patterns no longer static
0240e22
adding @Input-annotated getter for patterns var
fdc3d72
Merge remote-tracking branch 'origin/master' into replace-groovy-forb…
alpar-t c42b799
unused TemporaryFolder
d1c3582
unmodifiable map
57da91c
adding rolling-upgrade exclusion for system_key file
da85751
adding full-cluster-restart exclusion for system_key file
4af0c06
Improove exception for non UTF8 files
alpar-t File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
130 changes: 0 additions & 130 deletions
130
buildSrc/src/main/groovy/org/elasticsearch/gradle/precommit/ForbiddenPatternsTask.groovy
This file was deleted.
Oops, something went wrong.
161 changes: 161 additions & 0 deletions
161
buildSrc/src/main/java/org/elasticsearch/gradle/precommit/ForbiddenPatternsTask.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,161 @@ | ||
/* | ||
* Licensed to Elasticsearch under one or more contributor | ||
* license agreements. See the NOTICE file distributed with | ||
* this work for additional information regarding copyright | ||
* ownership. Elasticsearch licenses this file to you 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 org.elasticsearch.gradle.precommit; | ||
|
||
import org.gradle.api.DefaultTask; | ||
import org.gradle.api.GradleException; | ||
import org.gradle.api.InvalidUserDataException; | ||
import org.gradle.api.file.FileCollection; | ||
import org.gradle.api.file.FileTree; | ||
import org.gradle.api.plugins.JavaPluginConvention; | ||
import org.gradle.api.tasks.Input; | ||
import org.gradle.api.tasks.InputFiles; | ||
import org.gradle.api.tasks.OutputFile; | ||
import org.gradle.api.tasks.SkipWhenEmpty; | ||
import org.gradle.api.tasks.TaskAction; | ||
import org.gradle.api.tasks.util.PatternFilterable; | ||
import org.gradle.api.tasks.util.PatternSet; | ||
|
||
import java.io.File; | ||
import java.io.IOException; | ||
import java.io.UncheckedIOException; | ||
import java.nio.charset.StandardCharsets; | ||
import java.nio.file.Files; | ||
import java.util.AbstractMap; | ||
import java.util.ArrayList; | ||
import java.util.Collections; | ||
import java.util.HashMap; | ||
import java.util.List; | ||
import java.util.Map; | ||
import java.util.regex.Pattern; | ||
import java.util.stream.Collectors; | ||
import java.util.stream.IntStream; | ||
import java.util.stream.Stream; | ||
|
||
/** | ||
* Checks for patterns in source files for the project which are forbidden. | ||
*/ | ||
public class ForbiddenPatternsTask extends DefaultTask { | ||
|
||
/* | ||
* A pattern set of which files should be checked. | ||
*/ | ||
private final PatternFilterable filesFilter = new PatternSet() | ||
// we always include all source files, and exclude what should not be checked | ||
.include("**") | ||
// exclude known binary extensions | ||
.exclude("**/*.gz") | ||
.exclude("**/*.ico") | ||
.exclude("**/*.jar") | ||
.exclude("**/*.zip") | ||
.exclude("**/*.jks") | ||
.exclude("**/*.crt") | ||
.exclude("**/*.png"); | ||
|
||
/* | ||
* The rules: a map from the rule name, to a rule regex pattern. | ||
*/ | ||
private final Map<String, String> patterns = new HashMap<>(); | ||
|
||
public ForbiddenPatternsTask() { | ||
setDescription("Checks source files for invalid patterns like nocommits or tabs"); | ||
getInputs().property("excludes", filesFilter.getExcludes()); | ||
getInputs().property("rules", patterns); | ||
|
||
// add mandatory rules | ||
patterns.put("nocommit", "nocommit|NOCOMMIT"); | ||
patterns.put("nocommit should be all lowercase or all uppercase", "((?i)nocommit)(?<!(nocommit|NOCOMMIT))"); | ||
patterns.put("tab", "\t"); | ||
} | ||
|
||
@InputFiles | ||
@SkipWhenEmpty | ||
public FileCollection files() { | ||
return getProject().getConvention().getPlugin(JavaPluginConvention.class).getSourceSets() | ||
.stream() | ||
.map(sourceSet -> sourceSet.getAllSource().matching(filesFilter)) | ||
.reduce(FileTree::plus) | ||
.orElse(getProject().files().getAsFileTree()); | ||
} | ||
|
||
@TaskAction | ||
public void checkInvalidPatterns() throws IOException { | ||
Pattern allPatterns = Pattern.compile("(" + String.join(")|(", getPatterns().values()) + ")"); | ||
List<String> failures = new ArrayList<>(); | ||
for (File f : files()) { | ||
List<String> lines; | ||
try(Stream<String> stream = Files.lines(f.toPath(), StandardCharsets.UTF_8)) { | ||
lines = stream.collect(Collectors.toList()); | ||
} catch (UncheckedIOException e) { | ||
throw new IllegalArgumentException("Failed to read " + f + " as UTF_8", e); | ||
} | ||
List<Integer> invalidLines = IntStream.range(0, lines.size()) | ||
.filter(i -> allPatterns.matcher(lines.get(i)).find()) | ||
.boxed() | ||
.collect(Collectors.toList()); | ||
|
||
String path = getProject().getRootProject().getProjectDir().toURI().relativize(f.toURI()).toString(); | ||
failures = invalidLines.stream() | ||
.map(l -> new AbstractMap.SimpleEntry<>(l+1, lines.get(l))) | ||
.flatMap(kv -> patterns.entrySet().stream() | ||
.filter(p -> Pattern.compile(p.getValue()).matcher(kv.getValue()).find()) | ||
.map(p -> "- " + p.getKey() + " on line " + kv.getKey() + " of " + path) | ||
) | ||
.collect(Collectors.toList()); | ||
} | ||
if (failures.isEmpty() == false) { | ||
throw new GradleException("Found invalid patterns:\n" + String.join("\n", failures)); | ||
} | ||
|
||
File outputMarker = getOutputMarker(); | ||
outputMarker.getParentFile().mkdirs(); | ||
Files.write(outputMarker.toPath(), "done".getBytes(StandardCharsets.UTF_8)); | ||
} | ||
|
||
@OutputFile | ||
public File getOutputMarker() { | ||
return new File(getProject().getBuildDir(), "markers/" + getName()); | ||
} | ||
|
||
@Input | ||
public Map<String, String> getPatterns() { | ||
return Collections.unmodifiableMap(patterns); | ||
} | ||
|
||
public void exclude(String... excludes) { | ||
filesFilter.exclude(excludes); | ||
} | ||
|
||
public void rule(Map<String,String> props) { | ||
String name = props.remove("name"); | ||
if (name == null) { | ||
throw new InvalidUserDataException("Missing [name] for invalid pattern rule"); | ||
} | ||
String pattern = props.remove("pattern"); | ||
if (pattern == null) { | ||
throw new InvalidUserDataException("Missing [pattern] for invalid pattern rule"); | ||
} | ||
if (props.isEmpty() == false) { | ||
throw new InvalidUserDataException("Unknown arguments for ForbiddenPatterns rule mapping: " | ||
+ props.keySet().toString()); | ||
} | ||
// TODO: fail if pattern contains a newline, it won't work (currently) | ||
patterns.put(name, pattern); | ||
alpar-t marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
getProject().files()
returns a file collection, no need forgetAsFileTree
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Because the result of
reduce()
is anOptional<FileTree>
, doesn't the result of the.orElse()
statement also need be of typeFileTree
?