text
stringlengths 1.38k
39.2k
|
---|
<s>[INST] <<SYS>> You are an assistant to create OpenRewrite recipes by providing the Java source code for an OpenRewrite recipe that implements the user's requirements. <</SYS>> Create an OpenRewrite recipes that fulfills the following requirement: Find source files with `ParseExceptionResult` markers [/INST] /*
* Copyright 2022 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite;
import lombok.EqualsAndHashCode;
import lombok.Value;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.marker.Markup;
import org.openrewrite.table.ParseFailures;
import java.util.Objects;
@Value
@EqualsAndHashCode(callSuper = false)
public class FindParseFailures extends Recipe {
@Option(displayName = "Max snippet length",
description = "When the failure occurs on a granular tree element, its source code will be included " +
"as a column in the data table up to this maximum snippet length.",
required = false)
@Nullable
Integer maxSnippetLength;
@Option(displayName = "Parser type",
description = "Only display failures from parsers with this fully qualified name.",
required = false,
example = "org.openrewrite.yaml.YamlParser")
@Nullable
String parserType;
@Option(displayName = "Stack trace",
description = "Only mark stack traces with a message containing this text.",
required = false)
@Nullable
String stackTrace;
transient ParseFailures failures = new ParseFailures(this);
@Override
public String getDisplayName() {
return "Find source files with `ParseExceptionResult` markers";
}
@Override
public String getDescription() {
return "This recipe explores parse failures after an LST is produced for classifying the types of " +
"failures that can occur and prioritizing fixes according to the most common problems.";
}
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return new TreeVisitor<Tree, ExecutionContext>() {
@Override
public Tree postVisit(Tree tree, ExecutionContext ctx) {
return tree.getMarkers().findFirst(ParseExceptionResult.class)
.map(exceptionResult -> {
if (parserType != null && !Objects.equals(exceptionResult.getParserType(), parserType)) {
return tree;
}
if (stackTrace != null && !exceptionResult.getMessage().contains(stackTrace)) {
return tree;
}
String snippet = tree instanceof SourceFile ? null : tree.printTrimmed(getCursor());
if (snippet != null && maxSnippetLength != null && snippet.length() > maxSnippetLength) {
snippet = snippet.substring(0, maxSnippetLength);
}
failures.insertRow(ctx, new ParseFailures.Row(
exceptionResult.getParserType(),
(tree instanceof SourceFile ? (SourceFile) tree : getCursor().firstEnclosingOrThrow(SourceFile.class))
.getSourcePath().toString(),
exceptionResult.getExceptionType(),
exceptionResult.getTreeType(),
snippet,
exceptionResult.getMessage()
));
return Markup.info(tree, exceptionResult.getMessage());
})
.orElse(tree);
}
};
}
} </s> |
<s>[INST] <<SYS>> You are an assistant to create OpenRewrite recipes by providing the Java source code for an OpenRewrite recipe that implements the user's requirements. <</SYS>> Create an OpenRewrite recipes that fulfills the following requirement: Is in repository [/INST] /*
* Copyright 2023 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite;
import lombok.EqualsAndHashCode;
import lombok.Value;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.marker.GitProvenance;
import org.openrewrite.marker.SearchResult;
import java.util.Optional;
import java.util.Set;
@Value
@EqualsAndHashCode(callSuper = false)
public class IsInRepository extends Recipe {
@Override
public String getDisplayName() {
return "Is in repository";
}
@Override
public String getDescription() {
return "A search recipe which marks files that are in a repository with one of the supplied names. " +
"Intended for use as a precondition for other recipes being run over many different repositories.";
}
@Option(displayName = "Allowed repositories",
description = "The names of the repositories that are allowed to be searched. " +
"Determines repository name according to git metadata recorded in the `GitProvenance` marker.",
example = "rewrite")
Set<String> allowedRepositories;
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return new TreeVisitor<Tree, ExecutionContext>() {
@Override
public @Nullable Tree visit(@Nullable Tree tree, ExecutionContext ctx) {
if (tree == null) {
return null;
}
Optional<GitProvenance> maybeGp = tree.getMarkers().findFirst(GitProvenance.class);
if (maybeGp.isPresent()) {
GitProvenance gp = maybeGp.get();
if (allowedRepositories.contains(gp.getRepositoryName())) {
return SearchResult.found(tree);
}
}
return tree;
}
};
}
} </s> |
<s>[INST] <<SYS>> You are an assistant to create OpenRewrite recipes by providing the Java source code for an OpenRewrite recipe that implements the user's requirements. <</SYS>> Create an OpenRewrite recipes that fulfills the following requirement: Experimental find text with multiselect [/INST] /*
* Copyright 2023 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite.text;
import lombok.EqualsAndHashCode;
import lombok.Value;
import org.openrewrite.*;
import org.openrewrite.binary.Binary;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.marker.Markers;
import org.openrewrite.marker.SearchResult;
import org.openrewrite.quark.Quark;
import org.openrewrite.remote.Remote;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toSet;
@Incubating(since = "8.2.0")
@Value
@EqualsAndHashCode(callSuper = false)
public class FindMultiselect extends Recipe {
@Override
public String getDisplayName() {
return "Experimental find text with multiselect";
}
@Override
public String getDescription() {
return "Search for text, treating all textual sources as plain text. " +
"This version of the recipe exists to experiment with multiselect recipe options.";
}
@Option(displayName = "Find",
description = "The text to find. This snippet can be multiline.",
example = "blacklist")
String find;
@Option(displayName = "Regex",
description = "If true, `find` will be interpreted as a Regular Expression. Default `false`.",
required = false)
@Nullable
Boolean regex;
@Option(displayName = "Regex options",
description = "Regex processing options. Multiple options may be specified. These options do nothing if `regex` mode is not enabled.\n" +
"* Case-sensitive - The search will be sensitive to letter case. " +
"* Multiline - Allows `^` and `$` to match the beginning and end of lines, respectively." +
"* Dot all - Allows `.` to match line terminators.",
valid = {"Case-sensitive", "Multiline", "Dot all"},
required = false)
@Nullable
Set<String> regexOptions;
@Option(displayName = "File pattern",
description = "A glob expression that can be used to constrain which directories or source files should be searched. " +
"Multiple patterns may be specified, separated by a semicolon `;`. " +
"If multiple patterns are supplied any of the patterns matching will be interpreted as a match. " +
"When not set, all source files are searched. ",
example = "**/*.java")
@Nullable
String filePattern;
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
Boolean caseSensitive;
Boolean multiline;
Boolean dotAll;
if (regexOptions != null) {
Set<String> lowerCaseOptions = regexOptions.stream()
.map(String::toLowerCase)
.collect(toSet());
caseSensitive = lowerCaseOptions.contains("Case-sensitive");
multiline = lowerCaseOptions.contains("Multiline");
dotAll = lowerCaseOptions.contains("Dot all");
} else {
caseSensitive = null;
multiline = null;
dotAll = null;
}
TreeVisitor<?, ExecutionContext> visitor = new TreeVisitor<Tree, ExecutionContext>() {
@Override
public Tree visit(@Nullable Tree tree, ExecutionContext ctx) {
SourceFile sourceFile = (SourceFile) requireNonNull(tree);
if (sourceFile instanceof Quark || sourceFile instanceof Remote || sourceFile instanceof Binary) {
return sourceFile;
}
PlainText plainText = PlainTextParser.convert(sourceFile);
String searchStr = find;
if (!Boolean.TRUE.equals(regex)) {
searchStr = Pattern.quote(searchStr);
}
int patternOptions = 0;
if (!Boolean.TRUE.equals(caseSensitive)) {
patternOptions |= Pattern.CASE_INSENSITIVE;
}
if (Boolean.TRUE.equals(multiline)) {
patternOptions |= Pattern.MULTILINE;
}
if (Boolean.TRUE.equals(dotAll)) {
patternOptions |= Pattern.DOTALL;
}
Pattern pattern = Pattern.compile(searchStr, patternOptions);
Matcher matcher = pattern.matcher(plainText.getText());
String rawText = plainText.getText();
if (!matcher.find()) {
return sourceFile;
}
matcher.reset();
List<PlainText.Snippet> snippets = new ArrayList<>();
int previousEnd = 0;
while (matcher.find()) {
int matchStart = matcher.start();
snippets.add(snippet(rawText.substring(previousEnd, matchStart)));
snippets.add(SearchResult.found(snippet(rawText.substring(matchStart, matcher.end()))));
previousEnd = matcher.end();
}
snippets.add(snippet(rawText.substring(previousEnd)));
return plainText.withText("").withSnippets(snippets);
}
};
//noinspection DuplicatedCode
if (filePattern != null) {
//noinspection unchecked
TreeVisitor<?, ExecutionContext> check = Preconditions.or(Arrays.stream(filePattern.split(";"))
.map(FindSourceFiles::new)
.map(Recipe::getVisitor)
.toArray(TreeVisitor[]::new));
visitor = Preconditions.check(check, visitor);
}
return visitor;
}
private static PlainText.Snippet snippet(String text) {
return new PlainText.Snippet(Tree.randomId(), Markers.EMPTY, text);
}
} </s> |
<s>[INST] <<SYS>> You are an assistant to create OpenRewrite recipes by providing the Java source code for an OpenRewrite recipe that implements the user's requirements. <</SYS>> Create an OpenRewrite recipes that fulfills the following requirement: Creates a new plain text file. [/INST] /*
* Copyright 2021 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite.text;
import lombok.EqualsAndHashCode;
import lombok.Value;
import org.openrewrite.*;
import org.openrewrite.internal.lang.Nullable;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import static java.util.Collections.emptyList;
import static java.util.Objects.requireNonNull;
@Value
@EqualsAndHashCode(callSuper = false)
public class CreateTextFile extends ScanningRecipe<AtomicBoolean> {
@Option(displayName = "File contents",
description = "Multiline text content for the file.",
example = "Some text.")
String fileContents;
@Option(displayName = "Relative file path",
description = "File path of new file.",
example = "foo/bar/baz.txt")
String relativeFileName;
@Option(displayName = "Overwrite existing file",
description = "If there is an existing file, should it be overwritten.",
required = false)
@Nullable
Boolean overwriteExisting;
@Override
public String getDisplayName() {
return "Create text file";
}
@Override
public String getDescription() {
return "Creates a new plain text file.";
}
@Override
public AtomicBoolean getInitialValue(ExecutionContext ctx) {
return new AtomicBoolean(true);
}
@Override
public TreeVisitor<?, ExecutionContext> getScanner(AtomicBoolean shouldCreate) {
return new CreateFileVisitor(Paths.get(relativeFileName), shouldCreate);
}
@Override
public Collection<SourceFile> generate(AtomicBoolean shouldCreate, ExecutionContext ctx) {
if (shouldCreate.get()) {
return PlainTextParser.builder().build().parse(fileContents)
.map(brandNewFile -> (SourceFile) brandNewFile.withSourcePath(Paths.get(relativeFileName)))
.collect(Collectors.toList());
}
return emptyList();
}
@Override
public TreeVisitor<?, ExecutionContext> getVisitor(AtomicBoolean created) {
Path path = Paths.get(relativeFileName);
return new TreeVisitor<SourceFile, ExecutionContext>() {
@Override
public SourceFile visit(@Nullable Tree tree, ExecutionContext ctx) {
SourceFile sourceFile = (SourceFile) requireNonNull(tree);
if ((created.get() || Boolean.TRUE.equals(overwriteExisting)) && path.equals(sourceFile.getSourcePath())) {
if (sourceFile instanceof PlainText) {
return ((PlainText) sourceFile).withText(fileContents);
}
PlainText plainText = PlainText.builder()
.id(sourceFile.getId())
.sourcePath(sourceFile.getSourcePath())
.fileAttributes(sourceFile.getFileAttributes())
.charsetBomMarked(sourceFile.isCharsetBomMarked())
.text(fileContents)
.build();
if (sourceFile.getCharset() != null) {
return plainText.withCharset(sourceFile.getCharset());
}
return plainText;
}
return sourceFile;
}
};
}
} </s> |
<s>[INST] <<SYS>> You are an assistant to create OpenRewrite recipes by providing the Java source code for an OpenRewrite recipe that implements the user's requirements. <</SYS>> Create an OpenRewrite recipes that fulfills the following requirement: Change text [/INST] /*
* Copyright 2020 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite.text;
import lombok.EqualsAndHashCode;
import lombok.Value;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Option;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import java.util.Collections;
import java.util.Set;
import static java.util.Collections.emptyList;
@Value
@EqualsAndHashCode(callSuper = false)
public class ChangeText extends Recipe {
@Option(displayName = "Text after change",
description = "The text file will have only this text after the change. The snippet provided here can be multiline.",
example = "Some text.")
String toText;
@Override
public Set<String> getTags() {
return Collections.singleton("plain text");
}
@Override
public String getDisplayName() {
return "Change text";
}
@Override
public String getInstanceNameSuffix() {
return "to `" + toText + "`";
}
@Override
public String getDescription() {
return "Completely replaces the contents of the text file with other text. " +
"Use together with a `FindSourceFiles` precondition to limit which files are changed.";
}
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return new PlainTextVisitor<ExecutionContext>() {
@Override
public PlainText visitText(PlainText text, ExecutionContext ctx) {
return text
.withSnippets(emptyList())
.withText(toText);
}
};
}
} </s> |
<s>[INST] <<SYS>> You are an assistant to create OpenRewrite recipes by providing the Java source code for an OpenRewrite recipe that implements the user's requirements. <</SYS>> Create an OpenRewrite recipes that fulfills the following requirement: Find and replace [/INST] /*
* Copyright 2022 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite.text;
import lombok.EqualsAndHashCode;
import lombok.Value;
import org.openrewrite.*;
import org.openrewrite.binary.Binary;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.marker.AlreadyReplaced;
import org.openrewrite.marker.Marker;
import org.openrewrite.quark.Quark;
import org.openrewrite.remote.Remote;
import java.util.Arrays;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.util.Objects.requireNonNull;
import static org.openrewrite.Tree.randomId;
@Value
@EqualsAndHashCode(callSuper = false)
public class FindAndReplace extends Recipe {
@Option(displayName = "Find",
description = "The text to find (and replace). This snippet can be multiline.",
example = "blacklist")
String find;
@Option(displayName = "Replace",
description = "The replacement text for `find`. This snippet can be multiline.",
example = "denylist",
required = false)
@Nullable
String replace;
@Option(displayName = "Regex",
description = "Default false. If true, `find` will be interpreted as a Regular Expression, and capture group contents will be available in `replace`.",
required = false)
@Nullable
Boolean regex;
@Option(displayName = "Case sensitive",
description = "If `true` the search will be sensitive to case. Default `false`.",
required = false)
@Nullable
Boolean caseSensitive;
@Option(displayName = "Regex multiline mode",
description = "When performing a regex search setting this to `true` allows \"^\" and \"$\" to match the beginning and end of lines, respectively. " +
"When performing a regex search when this is `false` \"^\" and \"$\" will match only the beginning and ending of the entire source file, respectively." +
"Has no effect when not performing a regex search. Default `false`.",
required = false)
@Nullable
Boolean multiline;
@Option(displayName = "Regex dot all",
description = "When performing a regex search setting this to `true` allows \".\" to match line terminators." +
"Has no effect when not performing a regex search. Default `false`.",
required = false)
@Nullable
Boolean dotAll;
@Option(displayName = "File pattern",
description = "A glob expression that can be used to constrain which directories or source files should be searched. " +
"Multiple patterns may be specified, separated by a semicolon `;`. " +
"If multiple patterns are supplied any of the patterns matching will be interpreted as a match. " +
"When not set, all source files are searched. ",
required = false,
example = "**/*.java")
@Nullable
String filePattern;
@Override
public String getDisplayName() {
return "Find and replace";
}
@Override
public String getDescription() {
return "Simple text find and replace. When the original source file is a language-specific Lossless Semantic " +
"Tree, this operation irreversibly converts the source file to a plain text file. Subsequent recipes " +
"will not be able to operate on language-specific type.";
}
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
TreeVisitor<?, ExecutionContext> visitor = new TreeVisitor<Tree, ExecutionContext>() {
@Override
public Tree visit(@Nullable Tree tree, ExecutionContext ctx) {
SourceFile sourceFile = (SourceFile) requireNonNull(tree);
if (sourceFile instanceof Quark || sourceFile instanceof Remote || sourceFile instanceof Binary) {
return sourceFile;
}
for (Marker marker : sourceFile.getMarkers().getMarkers()) {
if (marker instanceof AlreadyReplaced) {
AlreadyReplaced alreadyReplaced = (AlreadyReplaced) marker;
if (Objects.equals(find, alreadyReplaced.getFind()) && Objects.equals(replace, alreadyReplaced.getReplace())) {
return sourceFile;
}
}
}
String searchStr = find;
if (!Boolean.TRUE.equals(regex)) {
searchStr = Pattern.quote(searchStr);
}
int patternOptions = 0;
if (!Boolean.TRUE.equals(caseSensitive)) {
patternOptions |= Pattern.CASE_INSENSITIVE;
}
if (Boolean.TRUE.equals(multiline)) {
patternOptions |= Pattern.MULTILINE;
}
if (Boolean.TRUE.equals(dotAll)) {
patternOptions |= Pattern.DOTALL;
}
PlainText plainText = PlainTextParser.convert(sourceFile);
Pattern pattern = Pattern.compile(searchStr, patternOptions);
Matcher matcher = pattern.matcher(plainText.getText());
if (!matcher.find()) {
return sourceFile;
}
String replacement = replace == null ? "" : replace;
if (!Boolean.TRUE.equals(regex)) {
replacement = replacement.replace("$", "\\$");
}
String newText = matcher.replaceAll(replacement);
return plainText.withText(newText)
.withMarkers(sourceFile.getMarkers().add(new AlreadyReplaced(randomId(), find, replace)));
}
};
//noinspection DuplicatedCode
if (filePattern != null) {
//noinspection unchecked
TreeVisitor<?, ExecutionContext> check = Preconditions.or(Arrays.stream(filePattern.split(";"))
.map(FindSourceFiles::new)
.map(Recipe::getVisitor)
.toArray(TreeVisitor[]::new));
visitor = Preconditions.check(check, visitor);
}
return visitor;
}
} </s> |
<s>[INST] <<SYS>> You are an assistant to create OpenRewrite recipes by providing the Java source code for an OpenRewrite recipe that implements the user's requirements. <</SYS>> Create an OpenRewrite recipes that fulfills the following requirement: Appends or replaces content of an existing plain text file, or creates a new one if it doesn't already exist. [/INST] /*
* Copyright 2022 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite.text;
import lombok.EqualsAndHashCode;
import lombok.Value;
import org.openrewrite.*;
import org.openrewrite.internal.lang.Nullable;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.atomic.AtomicBoolean;
import static java.util.Objects.requireNonNull;
@Value
@EqualsAndHashCode(callSuper = false)
public class AppendToTextFile extends ScanningRecipe<AtomicBoolean> {
@Option(displayName = "Relative File Name",
description = "File name, using a relative path. If a non-plaintext file already exists at this location, then this recipe will do nothing.",
example = "foo/bar/baz.txt")
String relativeFileName;
@Option(displayName = "Content",
description = "Multiline text content to be appended to the file.",
example = "Some text.")
String content;
@Option(displayName = "Preamble",
description = "If a new file is created, this content will be included at the beginning.",
example = "# File generated by OpenRewrite #",
required = false)
@Nullable String preamble;
@Option(displayName = "Append newline",
description = "Print a newline automatically after the content (and preamble). Default true.",
required = false)
@Nullable Boolean appendNewline;
@Option(displayName = "Existing file strategy",
description = "Determines behavior if a file exists at this location prior to Rewrite execution.\n\n"
+ "- `Continue`: append new content to existing file contents. If existing file is not plaintext, recipe does nothing.\n"
+ "- `Replace`: remove existing content from file.\n"
+ "- `Leave`: *(default)* do nothing. Existing file is fully preserved.\n\n"
+ "Note: this only affects the first interaction with the specified file per Rewrite execution.\n"
+ "Subsequent instances of this recipe in the same Rewrite execution will always append.",
valid = {"Continue", "Replace", "Leave"},
required = false)
@Nullable Strategy existingFileStrategy;
public enum Strategy {Continue, Replace, Leave}
@Override
public String getDisplayName() {
return "Append to text file";
}
@Override
public String getDescription() {
return "Appends or replaces content of an existing plain text file, or creates a new one if it doesn't already exist.";
}
@Override
public int maxCycles() {
return 1;
}
@Override
public AtomicBoolean getInitialValue(ExecutionContext ctx) {
return new AtomicBoolean(false);
}
@Override
public TreeVisitor<?, ExecutionContext> getScanner(AtomicBoolean fileExists) {
return new TreeVisitor<Tree, ExecutionContext>() {
@Override
public Tree visit(@Nullable Tree tree, ExecutionContext ctx) {
SourceFile sourceFile = (SourceFile) requireNonNull(tree);
if (!fileExists.get() && sourceFile.getSourcePath().toString().equals(Paths.get(relativeFileName).toString())) {
fileExists.set(true);
}
return sourceFile;
}
};
}
@Override
public Collection<PlainText> generate(AtomicBoolean fileExists, Collection<SourceFile> generatedInThisCycle, ExecutionContext ctx) {
String maybeNewline = !Boolean.FALSE.equals(appendNewline) ? "\n" : "";
String content = this.content + maybeNewline;
String preamble = this.preamble != null ? this.preamble + maybeNewline : "";
boolean exists = fileExists.get();
Path path = Paths.get(relativeFileName);
if (!exists) {
for (SourceFile generated : generatedInThisCycle) {
if (generated.getSourcePath().toString().equals(path.toString())) {
exists = true;
break;
}
}
}
return exists ?
Collections.emptyList() :
Collections.singletonList(PlainText.builder()
.text(preamble + content)
.sourcePath(path)
.build());
}
@Override
public TreeVisitor<?, ExecutionContext> getVisitor(AtomicBoolean fileExists) {
return Preconditions.check(fileExists.get(), new TreeVisitor<Tree, ExecutionContext>() {
@Override
public Tree visit(@Nullable Tree tree, ExecutionContext ctx) {
SourceFile sourceFile = (SourceFile) requireNonNull(tree);
if (sourceFile.getSourcePath().toString().equals(Paths.get(relativeFileName).toString())) {
String maybeNewline = !Boolean.FALSE.equals(appendNewline) ? "\n" : "";
String content = AppendToTextFile.this.content + maybeNewline;
String preamble = AppendToTextFile.this.preamble != null ? AppendToTextFile.this.preamble + maybeNewline : "";
PlainText existingPlainText = (PlainText) sourceFile;
switch (existingFileStrategy != null ? existingFileStrategy : Strategy.Leave) {
case Continue:
if (!maybeNewline.isEmpty() && !existingPlainText.getText().endsWith(maybeNewline)) {
content = maybeNewline + content;
}
return existingPlainText.withText(existingPlainText.getText() + content);
case Replace:
return existingPlainText.withText(preamble + content);
}
}
return sourceFile;
}
});
}
} </s> |
<s>[INST] <<SYS>> You are an assistant to create OpenRewrite recipes by providing the Java source code for an OpenRewrite recipe that implements the user's requirements. <</SYS>> Create an OpenRewrite recipes that fulfills the following requirement: Search for text, treating all textual sources as plain text. [/INST] /*
* Copyright 2023 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite.text;
import lombok.EqualsAndHashCode;
import lombok.Value;
import org.openrewrite.*;
import org.openrewrite.binary.Binary;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.marker.Markers;
import org.openrewrite.marker.SearchResult;
import org.openrewrite.quark.Quark;
import org.openrewrite.remote.Remote;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.util.Objects.requireNonNull;
@Value
@EqualsAndHashCode(callSuper = false)
public class Find extends Recipe {
@Override
public String getDisplayName() {
return "Find text";
}
@Override
public String getDescription() {
return "Search for text, treating all textual sources as plain text.";
}
@Option(displayName = "Find",
description = "The text to find. This snippet can be multiline.",
example = "blacklist")
String find;
@Option(displayName = "Regex",
description = "If true, `find` will be interpreted as a Regular Expression. Default `false`.",
required = false)
@Nullable
Boolean regex;
@Option(displayName = "Case sensitive",
description = "If `true` the search will be sensitive to case. Default `false`.",
required = false)
@Nullable
Boolean caseSensitive;
@Option(displayName = "Regex multiline mode",
description = "When performing a regex search setting this to `true` allows \"^\" and \"$\" to match the beginning and end of lines, respectively. " +
"When performing a regex search when this is `false` \"^\" and \"$\" will match only the beginning and ending of the entire source file, respectively." +
"Has no effect when not performing a regex search. Default `false`.",
required = false)
@Nullable
Boolean multiline;
@Option(displayName = "Regex dot all",
description = "When performing a regex search setting this to `true` allows \".\" to match line terminators." +
"Has no effect when not performing a regex search. Default `false`.",
required = false)
@Nullable
Boolean dotAll;
@Option(displayName = "File pattern",
description = "A glob expression that can be used to constrain which directories or source files should be searched. " +
"Multiple patterns may be specified, separated by a semicolon `;`. " +
"If multiple patterns are supplied any of the patterns matching will be interpreted as a match. " +
"When not set, all source files are searched. ",
required = false,
example = "**/*.java")
@Nullable
String filePattern;
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
TreeVisitor<?, ExecutionContext> visitor = new TreeVisitor<Tree, ExecutionContext>() {
@Override
public Tree visit(@Nullable Tree tree, ExecutionContext ctx) {
SourceFile sourceFile = (SourceFile) requireNonNull(tree);
if (sourceFile instanceof Quark || sourceFile instanceof Remote || sourceFile instanceof Binary) {
return sourceFile;
}
PlainText plainText = PlainTextParser.convert(sourceFile);
String searchStr = find;
if (!Boolean.TRUE.equals(regex)) {
searchStr = Pattern.quote(searchStr);
}
int patternOptions = 0;
if (!Boolean.TRUE.equals(caseSensitive)) {
patternOptions |= Pattern.CASE_INSENSITIVE;
}
if (Boolean.TRUE.equals(multiline)) {
patternOptions |= Pattern.MULTILINE;
}
if (Boolean.TRUE.equals(dotAll)) {
patternOptions |= Pattern.DOTALL;
}
Pattern pattern = Pattern.compile(searchStr, patternOptions);
Matcher matcher = pattern.matcher(plainText.getText());
String rawText = plainText.getText();
if (!matcher.find()) {
return sourceFile;
}
matcher.reset();
List<PlainText.Snippet> snippets = new ArrayList<>();
int previousEnd = 0;
while (matcher.find()) {
int matchStart = matcher.start();
snippets.add(snippet(rawText.substring(previousEnd, matchStart)));
snippets.add(SearchResult.found(snippet(rawText.substring(matchStart, matcher.end()))));
previousEnd = matcher.end();
}
snippets.add(snippet(rawText.substring(previousEnd)));
return plainText.withText("").withSnippets(snippets);
}
};
//noinspection DuplicatedCode
if (filePattern != null) {
//noinspection unchecked
TreeVisitor<?, ExecutionContext> check = Preconditions.or(Arrays.stream(filePattern.split(";"))
.map(FindSourceFiles::new)
.map(Recipe::getVisitor)
.toArray(TreeVisitor[]::new));
visitor = Preconditions.check(check, visitor);
}
return visitor;
}
private static PlainText.Snippet snippet(String text) {
return new PlainText.Snippet(Tree.randomId(), Markers.EMPTY, text);
}
} </s> |
<s>[INST] <<SYS>> You are an assistant to create OpenRewrite recipes by providing the Java source code for an OpenRewrite recipe that implements the user's requirements. <</SYS>> Create an OpenRewrite recipes that fulfills the following requirement: End of Line @ End of File (EOL @ EOF) [/INST] /*
* Copyright 2023 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite.text;
import org.openrewrite.*;
import org.openrewrite.binary.Binary;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.quark.Quark;
import org.openrewrite.remote.Remote;
import static java.util.Objects.requireNonNull;
public class EndOfLineAtEndOfFile extends Recipe {
@Override
public String getDisplayName() {
return "End of Line @ End of File (EOL @ EOF)";
}
@Override
public String getDescription() {
return "Ensure that the file ends with the newline character.\n\n" +
"*Note*: If this recipe modifies a file, it converts the file into plain text. " +
"As such, this recipe should be run after any recipe that modifies the language-specific LST.";
}
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return new TreeVisitor<Tree, ExecutionContext>() {
@Override
public Tree visit(@Nullable Tree tree, ExecutionContext ctx) {
SourceFile sourceFile = (SourceFile) requireNonNull(tree);
if (sourceFile instanceof Quark || sourceFile instanceof Remote || sourceFile instanceof Binary) {
return sourceFile;
}
PlainText plainText = PlainTextParser.convert(sourceFile);
boolean whitespaceContainsCRLF = plainText.getText().contains("\r\n");
if (!plainText.getText().endsWith("\n")) {
if (whitespaceContainsCRLF) {
return plainText.withText(plainText.getText() + "\r\n");
} else {
return plainText.withText(plainText.getText() + '\n');
}
}
return sourceFile;
}
};
}
} </s> |
<s>[INST] <<SYS>> You are an assistant to create OpenRewrite recipes by providing the Java source code for an OpenRewrite recipe that implements the user's requirements. <</SYS>> Create an OpenRewrite recipes that fulfills the following requirement: Default no-op test, does nothing. [/INST] /*
* Copyright 2020 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import lombok.Setter;
import org.intellij.lang.annotations.Language;
import org.openrewrite.config.DataTableDescriptor;
import org.openrewrite.config.OptionDescriptor;
import org.openrewrite.config.RecipeDescriptor;
import org.openrewrite.config.RecipeExample;
import org.openrewrite.internal.ListUtils;
import org.openrewrite.internal.StringUtils;
import org.openrewrite.internal.lang.NullUtils;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.table.RecipeRunStats;
import org.openrewrite.table.SourcesFileErrors;
import org.openrewrite.table.SourcesFileResults;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.Duration;
import java.util.*;
import static java.util.Collections.emptyList;
import static org.openrewrite.internal.RecipeIntrospectionUtils.dataTableDescriptorFromDataTable;
/**
* Provides a formalized link list data structure of {@link Recipe recipes} and a {@link Recipe#run(LargeSourceSet, ExecutionContext)} method which will
* apply each recipes {@link TreeVisitor visitor} visit method to a list of {@link SourceFile sourceFiles}
* <p>
* Requires a name, {@link TreeVisitor visitor}.
* Optionally a subsequent Recipe can be linked via {@link #getRecipeList()}}
* <p>
* An {@link ExecutionContext} controls parallel execution and lifecycle while providing a message bus
* for sharing state between recipes and their visitors
* <p>
* returns a list of {@link Result results} for each modified {@link SourceFile}
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "@c")
@JsonPropertyOrder({"@c"}) // serialize type info first
public abstract class Recipe implements Cloneable {
public static final String PANIC = "__AHHH_PANIC!!!__";
private static final Logger logger = LoggerFactory.getLogger(Recipe.class);
@SuppressWarnings("unused")
@JsonProperty("@c")
public String getJacksonPolymorphicTypeTag() {
return getClass().getName();
}
private transient RecipeDescriptor descriptor;
@Nullable
private transient List<DataTableDescriptor> dataTables;
public static Recipe noop() {
return new Noop();
}
static class Noop extends Recipe {
@Override
public String getDisplayName() {
return "Do nothing";
}
@Override
public String getDescription() {
return "Default no-op test, does nothing.";
}
}
/**
* @return The maximum number of cycles this recipe is allowed to make changes in a recipe run.
*/
@Incubating(since = "8.0.0")
public int maxCycles() {
return Integer.MAX_VALUE;
}
/**
* A human-readable display name for the recipe, initial capped with no period.
* For example, "Find text". The display name can be assumed to be rendered in
* documentation and other places where markdown is understood, so it is possible
* to use stylistic markers like backticks to indicate types. For example,
* "Find uses of `java.util.List`".
*
* @return The display name.
*/
@Language("markdown")
public abstract String getDisplayName();
/**
* A human-readable display name for this recipe instance, including some descriptive
* text about the recipe options that are supplied, if any. The name must be
* initial capped with no period. For example, "Find text 'hello world'".
* <br/>
* For recipes with no options, by default this is equal to {@link #getDisplayName()}. For
* recipes with options, the default implementation does its best to summarize those options
* in a way that fits in a reasonable amount of characters.
* <br/>
* For consistency, when surrounding option descriptive text in quotes to visually differentiate
* it from the text before it, use single ``.
* <br/>
* Override to provide meaningful recipe instance names for recipes with complex sets of options.
*
* @return A name that describes this recipe instance.
*/
@Incubating(since = "8.12.0")
@Language("markdown")
public String getInstanceName() {
@Language("markdown")
String suffix = getInstanceNameSuffix();
if (!StringUtils.isBlank(suffix)) {
return getDisplayName() + " " + suffix;
}
List<OptionDescriptor> options = new ArrayList<>(getOptionDescriptors(getClass()));
options.removeIf(opt -> !opt.isRequired());
if (options.isEmpty()) {
return getDisplayName();
}
if (options.size() == 1) {
try {
OptionDescriptor option = options.get(0);
String name = option.getName();
Field optionField = getClass().getDeclaredField(name);
optionField.setAccessible(true);
Object optionValue = optionField.get(this);
if (optionValue != null &&
!Iterable.class.isAssignableFrom(optionValue.getClass()) &&
!optionValue.getClass().isArray()) {
return String.format("%s `%s`", getDisplayName(), optionValue);
}
} catch (NoSuchFieldException | IllegalAccessException ignore) {
// we tried...
}
}
return getDisplayName();
}
/**
* Since most instance names will be constructed with {@link #getDisplayName()} followed
* by some further descriptive text about the recipe's options, this method provides a convenient
* way to just specify the option descriptive text. When {@link #getInstanceName()} is overridden,
* this method has no effect. Generally either override this method or {@link #getInstanceName()}
* if you want to customize the instance name text.
*
* @return A suffix to append to the display name of a recipe.
*/
public String getInstanceNameSuffix() {
return "";
}
/**
* A human-readable description for the recipe, consisting of one or more full
* sentences ending with a period.
* <p>
* "Find methods by pattern." is an example. The description can be assumed to be rendered in
* documentation and other places where markdown is understood, so it is possible
* to use stylistic markers like backticks to indicate types. For example,
* "Find uses of `java.util.List`.".
*
* @return The display name.
*/
@Language("markdown")
public abstract String getDescription();
/**
* A set of strings used for categorizing related recipes. For example
* "testing", "junit", "spring". Any individual tag should consist of a
* single word, all lowercase.
*
* @return The tags.
*/
public Set<String> getTags() {
return Collections.emptySet();
}
/**
* @return An estimated effort were a developer to fix manually instead of using this recipe.
*/
@Nullable
public Duration getEstimatedEffortPerOccurrence() {
return Duration.ofMinutes(5);
}
public final RecipeDescriptor getDescriptor() {
if (descriptor == null) {
descriptor = createRecipeDescriptor();
}
return descriptor;
}
protected RecipeDescriptor createRecipeDescriptor() {
List<OptionDescriptor> options = getOptionDescriptors(this.getClass());
List<RecipeDescriptor> recipeList1 = new ArrayList<>();
for (Recipe next : getRecipeList()) {
recipeList1.add(next.getDescriptor());
}
URI recipeSource;
try {
recipeSource = getClass().getProtectionDomain().getCodeSource().getLocation().toURI();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
return new RecipeDescriptor(getName(), getDisplayName(), getDescription(), getTags(),
getEstimatedEffortPerOccurrence(), options, recipeList1, getDataTableDescriptors(),
getMaintainers(), getContributors(), getExamples(), recipeSource);
}
private List<OptionDescriptor> getOptionDescriptors(Class<?> recipeClass) {
List<OptionDescriptor> options = new ArrayList<>();
for (Field field : recipeClass.getDeclaredFields()) {
Object value;
try {
field.setAccessible(true);
value = field.get(this);
} catch (IllegalAccessException e) {
value = null;
}
Option option = field.getAnnotation(Option.class);
if (option != null) {
options.add(new OptionDescriptor(field.getName(),
field.getType().getSimpleName(),
option.displayName(),
option.description(),
option.example().isEmpty() ? null : option.example(),
option.valid().length == 1 && option.valid()[0].isEmpty() ? null : Arrays.asList(option.valid()),
option.required(),
value));
}
}
return options;
}
private static final List<DataTableDescriptor> GLOBAL_DATA_TABLES = Arrays.asList(
dataTableDescriptorFromDataTable(new SourcesFileResults(Recipe.noop())),
dataTableDescriptorFromDataTable(new SourcesFileErrors(Recipe.noop())),
dataTableDescriptorFromDataTable(new RecipeRunStats(Recipe.noop()))
);
public List<DataTableDescriptor> getDataTableDescriptors() {
return ListUtils.concatAll(dataTables == null ? emptyList() : dataTables, GLOBAL_DATA_TABLES);
}
/**
* @return a list of the organization(s) responsible for maintaining this recipe.
*/
public List<Maintainer> getMaintainers() {
return new ArrayList<>();
}
@Setter
protected List<Contributor> contributors;
public List<Contributor> getContributors() {
if (contributors == null) {
return new ArrayList<>();
}
return contributors;
}
@Setter
protected transient List<RecipeExample> examples;
public List<RecipeExample> getExamples() {
if (examples == null) {
return new ArrayList<>();
}
return examples;
}
/**
* @return Determines if another cycle is run when this recipe makes a change. In some cases, like changing method declaration names,
* a further cycle is needed to update method invocations of that declaration that were visited prior to the declaration change. But other
* visitors never need to cause another cycle, such as those that format whitespace or add search markers. Note that even when this is false,
* the recipe will still run on another cycle if any other recipe causes another cycle to run. But if every recipe reports no need to run
* another cycle (or if there are no changes made in a cycle), then another will not run.
*/
public boolean causesAnotherCycle() {
return false;
}
/**
* A list of recipes that run, source file by source file,
* after this recipe. This method is guaranteed to be called only once
* per cycle.
*
* @return The list of recipes to run.
*/
public List<Recipe> getRecipeList() {
return Collections.emptyList();
}
/**
* A recipe can optionally encapsulate a visitor that performs operations on a set of source files. Subclasses
* of the recipe may override this method to provide an instance of a visitor that will be used when the recipe
* is executed.
*
* @return A tree visitor that will perform operations associated with the recipe.
*/
public TreeVisitor<?, ExecutionContext> getVisitor() {
return TreeVisitor.noop();
}
public void addDataTable(DataTable<?> dataTable) {
if (dataTables == null) {
dataTables = new ArrayList<>();
}
dataTables.add(dataTableDescriptorFromDataTable(dataTable));
}
public final RecipeRun run(LargeSourceSet before, ExecutionContext ctx) {
return run(before, ctx, 3);
}
public final RecipeRun run(LargeSourceSet before, ExecutionContext ctx, int maxCycles) {
return run(before, ctx, maxCycles, 1);
}
public final RecipeRun run(LargeSourceSet before, ExecutionContext ctx, int maxCycles, int minCycles) {
return new RecipeScheduler().scheduleRun(this, before, ctx, maxCycles, minCycles);
}
@SuppressWarnings("unused")
public Validated<Object> validate(ExecutionContext ctx) {
Validated<Object> validated = validate();
for (Recipe recipe : getRecipeList()) {
validated = validated.and(recipe.validate(ctx));
}
return validated;
}
/**
* The default implementation of validate on the recipe will look for package and field level annotations that
* indicate a field is not-null. The annotations must have run-time retention and the simple name of the annotation
* must match one of the common names defined in {@link NullUtils}
*
* @return A validated instance based using non-null/nullable annotations to determine which fields of the recipe are required.
*/
public Validated<Object> validate() {
Validated<Object> validated = Validated.none();
Class<? extends Recipe> clazz = this.getClass();
List<Field> requiredFields = NullUtils.findNonNullFields(clazz);
for (Field field : requiredFields) {
try {
validated = validated.and(Validated.required(clazz.getSimpleName() + '.' + field.getName(), field.get(this)));
} catch (IllegalAccessException e) {
logger.warn("Unable to validate the field [{}] on the class [{}]", field.getName(), clazz.getName());
}
}
for (Recipe recipe : getRecipeList()) {
validated = validated.and(recipe.validate());
}
return validated;
}
public final Collection<Validated<Object>> validateAll() {
return validateAll(new InMemoryExecutionContext(), new ArrayList<>());
}
public Collection<Validated<Object>> validateAll(ExecutionContext ctx, Collection<Validated<Object>> acc) {
acc.add(validate(ctx));
for (Recipe recipe : getRecipeList()) {
recipe.validateAll(ctx, acc);
}
return acc;
}
public String getName() {
return getClass().getName();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Recipe recipe = (Recipe) o;
return getName().equals(recipe.getName());
}
@Override
public int hashCode() {
return Objects.hash(getName());
}
@Override
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
} </s> |
<s>[INST] <<SYS>> You are an assistant to create OpenRewrite recipes by providing the Java source code for an OpenRewrite recipe that implements the user's requirements. <</SYS>> Create an OpenRewrite recipes that fulfills the following requirement: Set a file's read, write and executable permission attributes. [/INST] /*
* Copyright 2022 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite;
import lombok.EqualsAndHashCode;
import lombok.Value;
import org.openrewrite.internal.lang.Nullable;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
@Value
@EqualsAndHashCode(callSuper = false)
public class SetFilePermissions extends Recipe {
@Option(displayName = "File matcher",
description = "Permissions will be applied to matching files. This is a glob expression.",
example = "**/gradlew.bat")
String fileMatcher;
@Option(displayName = "Readable",
description = "File read permission.")
Boolean isReadable;
@Option(displayName = "Writable",
description = "File write permission.")
Boolean isWritable;
@Option(displayName = "Executable",
description = "Files executable permission.")
Boolean isExecutable;
@Override
public String getDisplayName() {
return "Set file permission attributes";
}
@Override
public String getDescription() {
return "Set a file's read, write and executable permission attributes.";
}
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return new TreeVisitor<Tree, ExecutionContext>() {
@Nullable
@Override
public Tree visit(@Nullable Tree tree, ExecutionContext ctx) {
if (tree instanceof SourceFile) {
SourceFile sourceFile = (SourceFile) tree;
Path sourcePath = sourceFile.getSourcePath();
PathMatcher pathMatcher = sourcePath.getFileSystem().getPathMatcher("glob:" + fileMatcher);
if(pathMatcher.matches(sourcePath)) {
if (sourceFile.getFileAttributes() == null) {
sourceFile = sourceFile.withFileAttributes(new FileAttributes(null, null, null, isReadable, isWritable, isExecutable, 0));
} else {
FileAttributes fileAttributes = sourceFile.getFileAttributes();
sourceFile = sourceFile.withFileAttributes(fileAttributes.withReadable(isReadable).withWritable(isWritable).withExecutable(isExecutable));
}
return sourceFile;
}
}
return super.visit(tree, ctx);
}
};
}
} </s> |
<s>[INST] <<SYS>> You are an assistant to create OpenRewrite recipes by providing the Java source code for an OpenRewrite recipe that implements the user's requirements. <</SYS>> Create an OpenRewrite recipes that fulfills the following requirement: Show Git source control metadata [/INST] /*
* Copyright 2022 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.marker.GitProvenance;
import org.openrewrite.table.DistinctGitProvenance;
import java.util.*;
import static java.util.Objects.requireNonNull;
public class FindGitProvenance extends ScanningRecipe<Set<GitProvenance>> {
// we are looking for substantive differences, not just ID differences
private static final UUID DONT_CONSIDER_ID_IN_HASH_CODE = UUID.randomUUID();
private final DistinctGitProvenance distinct = new DistinctGitProvenance(this);
@Override
public String getDisplayName() {
return "Show Git source control metadata";
}
@Override
public String getDescription() {
return "List out the contents of each unique `GitProvenance` marker in the set of source files. " +
"When everything is working correctly, exactly one such marker should be printed as all source files are " +
"expected to come from the same repository / branch / commit hash.";
}
@Override
public Set<GitProvenance> getInitialValue(ExecutionContext ctx) {
return new HashSet<>();
}
@Override
public TreeVisitor<?, ExecutionContext> getScanner(Set<GitProvenance> provenances) {
return new TreeVisitor<Tree, ExecutionContext>() {
@Override
public Tree visit(@Nullable Tree tree, ExecutionContext ctx) {
SourceFile sourceFile = (SourceFile) requireNonNull(tree);
sourceFile.getMarkers().findFirst(GitProvenance.class).ifPresent(provenance ->
provenances.add(provenance.withId(DONT_CONSIDER_ID_IN_HASH_CODE)));
return sourceFile;
}
};
}
@Override
public Collection<SourceFile> generate(Set<GitProvenance> provenances, ExecutionContext ctx) {
for (GitProvenance provenance : provenances) {
distinct.insertRow(ctx, new DistinctGitProvenance.Row(
provenance.getOrigin(),
provenance.getBranch(),
provenance.getChange(),
provenance.getAutocrlf(),
provenance.getEol())
);
}
return Collections.emptyList();
}
} </s> |
<s>[INST] <<SYS>> You are an assistant to create OpenRewrite recipes by providing the Java source code for an OpenRewrite recipe that implements the user's requirements. <</SYS>> Create an OpenRewrite recipes that fulfills the following requirement: Find colliding source files [/INST] /*
* Copyright 2023 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite;
import lombok.EqualsAndHashCode;
import lombok.Value;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.marker.SearchResult;
import org.openrewrite.table.CollidingSourceFiles;
import java.nio.file.Path;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;
@Value
@EqualsAndHashCode(callSuper = false)
public class FindCollidingSourceFiles extends ScanningRecipe<FindCollidingSourceFiles.Accumulator> {
transient CollidingSourceFiles collidingSourceFiles = new CollidingSourceFiles(this);
@Override
public String getDisplayName() {
return "Find colliding source files";
}
@Override
public String getDescription() {
return "Finds source files which share a path with another source file. " +
"There should always be exactly one source file per path within a repository. " +
"This is a diagnostic for finding problems in OpenRewrite parsers/build plugins.";
}
@Override
public Accumulator getInitialValue(ExecutionContext ctx) {
return new Accumulator();
}
@Override
public TreeVisitor<?, ExecutionContext> getScanner(Accumulator acc) {
return new TreeVisitor<Tree, ExecutionContext>() {
@Override
public Tree visit(@Nullable Tree tree, ExecutionContext ctx) {
assert tree instanceof SourceFile;
Path p = ((SourceFile) tree).getSourcePath();
if (!acc.getSourcePaths().add(p)) {
acc.getDuplicates().add(p);
}
return tree;
}
};
}
@Override
public Collection<? extends SourceFile> generate(Accumulator acc, ExecutionContext ctx) {
acc.getSourcePaths().clear(); // we don't need this anymore, might as well free the memory sooner
return super.generate(acc, ctx);
}
@Override
public TreeVisitor<?, ExecutionContext> getVisitor(Accumulator acc) {
return new TreeVisitor<Tree, ExecutionContext>() {
@Override
public @Nullable Tree visit(@Nullable Tree tree, ExecutionContext ctx) {
if (tree instanceof SourceFile) {
Path p = ((SourceFile) tree).getSourcePath();
if (acc.getDuplicates().contains(p)) {
collidingSourceFiles.insertRow(ctx, new CollidingSourceFiles.Row(
p.toString(),
tree.getClass().toString()
));
return SearchResult.found(tree, "Duplicate source file " + p);
}
}
return tree;
}
};
}
@Value
static class Accumulator {
Set<Path> sourcePaths = new LinkedHashSet<>();
Set<Path> duplicates = new LinkedHashSet<>();
}
} </s> |
<s>[INST] <<SYS>> You are an assistant to create OpenRewrite recipes by providing the Java source code for an OpenRewrite recipe that implements the user's requirements. <</SYS>> Create an OpenRewrite recipes that fulfills the following requirement: Produces a data table showing what versions of OpenRewrite/Moderne tooling was used to produce a given LST. [/INST] /*
* Copyright 2023 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite;
import lombok.EqualsAndHashCode;
import lombok.Value;
import org.openrewrite.marker.LstProvenance;
import org.openrewrite.table.LstProvenanceTable;
import static java.time.ZoneOffset.UTC;
@Value
@EqualsAndHashCode(callSuper = false)
public class FindLstProvenance extends ScanningRecipe<FindLstProvenance.Accumulator> {
@Override
public String getDisplayName() {
return "Find LST provenance";
}
@Override
public String getDescription() {
return "Produces a data table showing what versions of OpenRewrite/Moderne tooling was used to produce a given LST.";
}
transient LstProvenanceTable provenanceTable = new LstProvenanceTable(this);
public static class Accumulator {
// There will only ever be one LstProvenance per repository, so after we have seen one we don't need to see more
boolean foundLstProvenance;
}
@Override
public Accumulator getInitialValue(ExecutionContext ctx) {
return new Accumulator();
}
@Override
public TreeVisitor<?, ExecutionContext> getScanner(Accumulator acc) {
return new TreeVisitor<Tree, ExecutionContext>() {
@Override
public Tree preVisit(Tree tree, ExecutionContext ctx) {
stopAfterPreVisit();
if(acc.foundLstProvenance) {
return tree;
}
LstProvenance lstProvenance = tree.getMarkers().findFirst(LstProvenance.class).orElse(null);
if (lstProvenance == null) {
return tree;
}
provenanceTable.insertRow(ctx, new LstProvenanceTable.Row(lstProvenance.getBuildToolType(),
lstProvenance.getBuildToolVersion(), lstProvenance.getLstSerializerVersion(),
lstProvenance.getTimestampUtc() == null ? null : lstProvenance.getTimestampUtc().toEpochMilli(),
lstProvenance.getTimestampUtc() == null ? null : lstProvenance.getTimestampUtc().atZone(UTC).toString()));
acc.foundLstProvenance = true;
return tree;
}
};
}
} </s> |
<s>[INST] <<SYS>> You are an assistant to create OpenRewrite recipes by providing the Java source code for an OpenRewrite recipe that implements the user's requirements. <</SYS>> Create an OpenRewrite recipes that fulfills the following requirement: Produces a data table collecting all deserialization errors of serialized LSTs. [/INST] /*
* Copyright 2024 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite;
import lombok.EqualsAndHashCode;
import lombok.Value;
import org.openrewrite.marker.DeserializationError;
import org.openrewrite.marker.LstProvenance;
import org.openrewrite.marker.Markup;
import org.openrewrite.marker.OutdatedSerializer;
import org.openrewrite.table.DeserializationErrorTable;
import java.time.Instant;
import java.time.ZonedDateTime;
import java.util.Optional;
import static java.time.ZoneOffset.UTC;
@Value
@EqualsAndHashCode(callSuper = false)
public class FindDeserializationErrors extends Recipe {
@Override
public String getDisplayName() {
return "Find deserialization errors";
}
@Override
public String getDescription() {
return "Produces a data table collecting all deserialization errors of serialized LSTs.";
}
transient DeserializationErrorTable dataTable = new DeserializationErrorTable(this);
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return new TreeVisitor<Tree, ExecutionContext>() {
@Override
public Tree preVisit(Tree tree, ExecutionContext ctx) {
stopAfterPreVisit();
return tree.getMarkers().findFirst(DeserializationError.class)
.map(error -> {
Optional<OutdatedSerializer> outdatedSerializer = tree.getMarkers().findFirst(OutdatedSerializer.class);
Optional<LstProvenance> lstProvenance = tree.getMarkers().findFirst(LstProvenance.class);
dataTable.insertRow(ctx, new DeserializationErrorTable.Row(
tree instanceof SourceFile ? ((SourceFile) tree).getSourcePath().toString() : null,
error.getMessage(),
error.getDetail(),
outdatedSerializer.map(OutdatedSerializer::getLanguage).orElse(null),
outdatedSerializer.map(OutdatedSerializer::getMinimumVersion).orElse(null),
outdatedSerializer.map(OutdatedSerializer::getActualVersion)
.orElseGet(() -> lstProvenance.map(LstProvenance::getBuildToolVersion).orElse(null)),
lstProvenance.map(LstProvenance::getTimestampUtc).map(Instant::toEpochMilli).orElse(null),
lstProvenance.map(LstProvenance::getTimestampUtc).map(ts -> ts.atZone(UTC)).map(ZonedDateTime::toString).orElse(null)
));
return Markup.info(tree, error.getMessage());
})
.orElse(tree);
}
};
}
} </s> |
<s>[INST] <<SYS>> You are an assistant to create OpenRewrite recipes by providing the Java source code for an OpenRewrite recipe that implements the user's requirements. <</SYS>> Create an OpenRewrite recipes that fulfills the following requirement: `Quark` source files are pointers to the existence of a file without capturing any of the contents of the file. [/INST] /*
* Copyright 2022 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite;
import lombok.EqualsAndHashCode;
import lombok.Value;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.marker.SearchResult;
import org.openrewrite.quark.Quark;
import static java.util.Objects.requireNonNull;
@Value
@EqualsAndHashCode(callSuper = false)
public class FindQuarks extends Recipe {
@Override
public String getDisplayName() {
return "Find instances of type `Quark`";
}
@Override
public String getDescription() {
return "`Quark` source files are pointers to the existence of a file without capturing any of the contents of the file.";
}
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return new TreeVisitor<Tree, ExecutionContext>() {
@Override
public Tree visit(@Nullable Tree tree, ExecutionContext ctx) {
SourceFile sourceFile = (SourceFile) requireNonNull(tree);
if (sourceFile instanceof Quark) {
return SearchResult.found(sourceFile);
}
return sourceFile;
}
};
}
} </s> |
<s>[INST] <<SYS>> You are an assistant to create OpenRewrite recipes by providing the Java source code for an OpenRewrite recipe that implements the user's requirements. <</SYS>> Create an OpenRewrite recipes that fulfills the following requirement: Find files by source path. [/INST] /*
* Copyright 2021 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite;
import lombok.EqualsAndHashCode;
import lombok.Value;
import org.openrewrite.internal.StringUtils;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.marker.SearchResult;
import org.openrewrite.table.SourcesFiles;
import java.nio.file.Path;
@Value
@EqualsAndHashCode(callSuper = false)
public class FindSourceFiles extends Recipe {
transient SourcesFiles results = new SourcesFiles(this);
@Option(displayName = "File pattern",
description = "A glob expression representing a file path to search for (relative to the project root). Blank/null matches all.",
required = false,
example = ".github/workflows/*.yml")
@Nullable
String filePattern;
@Override
public String getDisplayName() {
return "Find files";
}
@Override
public String getDescription() {
return "Find files by source path.";
}
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return new TreeVisitor<Tree, ExecutionContext>() {
@Nullable
@Override
public Tree visit(@Nullable Tree tree, ExecutionContext ctx) {
if (tree instanceof SourceFile) {
SourceFile sourceFile = (SourceFile) tree;
Path sourcePath = sourceFile.getSourcePath();
if (StringUtils.isBlank(filePattern) || PathUtils.matchesGlob(sourcePath, normalize(filePattern))) {
results.insertRow(ctx, new SourcesFiles.Row(sourcePath.toString(),
tree.getClass().getSimpleName()));
return SearchResult.found(sourceFile);
}
}
return tree;
}
};
}
private static String normalize(String filePattern) {
if (filePattern.startsWith("./") || filePattern.startsWith(".\\")) {
return filePattern.substring(2);
} else if (filePattern.startsWith("/") || filePattern.startsWith("\\")) {
return filePattern.substring(1);
}
return filePattern;
}
} </s> |
<s>[INST] <<SYS>> You are an assistant to create OpenRewrite recipes by providing the Java source code for an OpenRewrite recipe that implements the user's requirements. <</SYS>> Create an OpenRewrite recipes that fulfills the following requirement: Find parse to print inequality [/INST] /*
* Copyright 2023 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite.search;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Recipe;
import org.openrewrite.Tree;
import org.openrewrite.TreeVisitor;
import org.openrewrite.internal.InMemoryDiffEntry;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.marker.SearchResult;
import org.openrewrite.table.ParseToPrintInequalities;
import org.openrewrite.tree.ParseError;
import java.util.Collections;
public class FindParseToPrintInequality extends Recipe {
transient ParseToPrintInequalities inequalities = new ParseToPrintInequalities(this);
@Override
public String getDisplayName() {
return "Find parse to print inequality";
}
@Override
public String getDescription() {
return "OpenRewrite `Parser` implementations should produce `SourceFile` objects whose `printAll()` " +
"method should be byte-for-byte equivalent with the original source file. When this isn't true, " +
"recipes can still run on the `SourceFile` and even produce diffs, but the diffs would fail to " +
"apply as a patch to the original source file. Most `Parser` use `Parser#requirePrintEqualsInput` " +
"to produce a `ParseError` when they fail to produce a `SourceFile` that is print idempotent.";
}
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return new TreeVisitor<Tree, ExecutionContext>() {
@Override
public Tree visit(@Nullable Tree tree, ExecutionContext ctx) {
if (tree instanceof ParseError) {
ParseError parseError = (ParseError) tree;
if (parseError.getErroneous() != null) {
try (InMemoryDiffEntry diffEntry = new InMemoryDiffEntry(
parseError.getSourcePath(),
parseError.getSourcePath(),
null,
parseError.getText(),
parseError.getErroneous().printAll(),
Collections.emptySet()
)) {
inequalities.insertRow(ctx, new ParseToPrintInequalities.Row(
parseError.getSourcePath().toString(),
diffEntry.getDiff(false)
));
}
return SearchResult.found(parseError);
}
}
return super.visit(tree, ctx);
}
};
}
} </s> |
<s>[INST] <<SYS>> You are an assistant to create OpenRewrite recipes by providing the Java source code for an OpenRewrite recipe that implements the user's requirements. <</SYS>> Create an OpenRewrite recipes that fulfills the following requirement: List the committers on a repository. [/INST] /*
* Copyright 2023 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite.search;
import lombok.EqualsAndHashCode;
import lombok.Value;
import org.openrewrite.*;
import org.openrewrite.internal.StringUtils;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.marker.GitProvenance;
import org.openrewrite.table.CommitsByDay;
import org.openrewrite.table.DistinctCommitters;
import java.time.LocalDate;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.atomic.AtomicReference;
import static java.util.Objects.requireNonNull;
@Value
@EqualsAndHashCode(callSuper = false)
public class FindCommitters extends ScanningRecipe<AtomicReference<GitProvenance>> {
transient DistinctCommitters committers = new DistinctCommitters(this);
transient CommitsByDay commitsByDay = new CommitsByDay(this);
@Option(displayName = "From date",
required = false,
description = "Optional. Take into account only commits since this date (inclusive). Default will be the entire history.",
example = "2023-01-01")
@Nullable
String fromDate;
@Override
public String getDisplayName() {
return "Find committers on repositories";
}
@Override
public String getDescription() {
return "List the committers on a repository.";
}
@Override
public int maxCycles() {
// This recipe does not modify the LSTs and only requires the `GitProvenance` marker
return 1;
}
@Override
public AtomicReference<GitProvenance> getInitialValue(ExecutionContext ctx) {
return new AtomicReference<>();
}
@Override
public TreeVisitor<?, ExecutionContext> getScanner(AtomicReference<GitProvenance> acc) {
return Preconditions.check(acc.get() == null, new TreeVisitor<Tree, ExecutionContext>() {
@Override
public @Nullable Tree visit(@Nullable Tree tree, ExecutionContext ctx) {
if (tree instanceof SourceFile) {
SourceFile sourceFile = (SourceFile) tree;
sourceFile.getMarkers().findFirst(GitProvenance.class).ifPresent(provenance -> {
if (provenance.getCommitters() != null) {
acc.set(provenance);
}
});
}
return tree;
}
});
}
@Override
public Collection<? extends SourceFile> generate(AtomicReference<GitProvenance> acc, ExecutionContext ctx) {
GitProvenance gitProvenance = acc.get();
if (gitProvenance != null) {
LocalDate from = StringUtils.isBlank(fromDate) ? null : LocalDate.parse(fromDate).minusDays(1);
for (GitProvenance.Committer committer : requireNonNull(gitProvenance.getCommitters())) {
if (from == null || committer.getCommitsByDay().keySet().stream().anyMatch(day -> day.isAfter(from))) {
committers.insertRow(ctx, new DistinctCommitters.Row(
committer.getName(),
committer.getEmail(),
committer.getCommitsByDay().lastKey(),
committer.getCommitsByDay().values().stream().mapToInt(Integer::intValue).sum()
));
committer.getCommitsByDay().forEach((day, commits) -> commitsByDay.insertRow(ctx, new CommitsByDay.Row(
committer.getName(),
committer.getEmail(),
day,
commits
)));
}
}
}
return Collections.emptyList();
}
} </s> |
<s>[INST] <<SYS>> You are an assistant to create OpenRewrite recipes by providing the Java source code for an OpenRewrite recipe that implements the user's requirements. <</SYS>> Create an OpenRewrite recipes that fulfills the following requirement: Find source files with matching build metadata. [/INST] /*
* Copyright 2023 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite.search;
import lombok.EqualsAndHashCode;
import lombok.Value;
import org.openrewrite.*;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.marker.BuildMetadata;
import org.openrewrite.marker.SearchResult;
@Value
@EqualsAndHashCode(callSuper = false)
public class FindBuildMetadata extends Recipe {
@Option(displayName = "Build metadata key",
description = "The key to search for in the build metadata.",
example = "lstFormatVersion")
String key;
@Option(displayName = "Build metadata value",
description = "The value to search for in the build metadata.",
example = "2")
String value;
@Override
public String getDisplayName() {
return "Find build metadata";
}
@Override
public String getDescription() {
return "Find source files with matching build metadata.";
}
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return new TreeVisitor<Tree, ExecutionContext>() {
@Override
public Tree visit(@Nullable Tree tree, ExecutionContext ctx) {
if (tree instanceof SourceFile) {
for (BuildMetadata buildMetadata : tree.getMarkers().findAll(BuildMetadata.class)) {
if (buildMetadata.getMetadata().containsKey(key)) {
if (buildMetadata.getMetadata().get(key).equals(value)) {
return SearchResult.found(tree, "Found build metadata");
}
}
}
}
return tree;
}
};
}
} </s> |
<s>[INST] <<SYS>> You are an assistant to create OpenRewrite recipes by providing the Java source code for an OpenRewrite recipe that implements the user's requirements. <</SYS>> Create an OpenRewrite recipes that fulfills the following requirement: Delete files by source path. [/INST] /*
* Copyright 2021 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite;
import lombok.EqualsAndHashCode;
import lombok.Value;
import org.openrewrite.internal.lang.Nullable;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
@Value
@EqualsAndHashCode(callSuper = false)
public class DeleteSourceFiles extends Recipe {
@Option(displayName = "File pattern",
description = "A glob expression representing a file path to delete (relative to the project root).",
example = ".github/workflows/*.yml")
String filePattern;
@Override
public String getDisplayName() {
return "Delete files";
}
@Override
public String getDescription() {
return "Delete files by source path.";
}
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return new TreeVisitor<Tree, ExecutionContext>() {
@Nullable
@Override
public Tree visit(@Nullable Tree tree, ExecutionContext ctx) {
if (tree instanceof SourceFile) {
SourceFile sourceFile = (SourceFile) tree;
Path sourcePath = sourceFile.getSourcePath();
PathMatcher pathMatcher = sourcePath.getFileSystem().getPathMatcher("glob:" + filePattern);
if (pathMatcher.matches(sourcePath)) {
return null;
}
}
return tree;
}
};
}
} </s> |
<s>[INST] <<SYS>> You are an assistant to create OpenRewrite recipes by providing the Java source code for an OpenRewrite recipe that implements the user's requirements. <</SYS>> Create an OpenRewrite recipes that fulfills the following requirement: Rename a file while keeping it in the same directory. [/INST] /*
* Copyright 2021 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite;
import lombok.EqualsAndHashCode;
import lombok.Value;
import org.openrewrite.internal.lang.Nullable;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
@Value
@EqualsAndHashCode(callSuper = false)
public class RenameFile extends Recipe {
@Option(displayName = "File matcher",
description = "Matching files will be renamed. This is a glob expression.",
example = "**/application-*.yml")
String fileMatcher;
@Option(displayName = "The renamed file name",
description = "Just the file name without the folder path that precedes it.",
example = "application.yml")
String fileName;
@Override
public String getDisplayName() {
return "Rename a file";
}
@Override
public String getDescription() {
return "Rename a file while keeping it in the same directory.";
}
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return new TreeVisitor<Tree, ExecutionContext>() {
@Nullable
@Override
public Tree visit(@Nullable Tree tree, ExecutionContext ctx) {
if (tree instanceof SourceFile) {
SourceFile sourceFile = (SourceFile) tree;
Path sourcePath = sourceFile.getSourcePath();
PathMatcher pathMatcher = sourcePath.getFileSystem().getPathMatcher("glob:" + fileMatcher);
if(pathMatcher.matches(sourcePath)) {
return ((SourceFile) tree).withSourcePath(sourcePath.resolveSibling(fileName).normalize());
}
}
return super.visit(tree, ctx);
}
};
}
} </s> |
<s>[INST] <<SYS>> You are an assistant to create OpenRewrite recipes by providing the Java source code for an OpenRewrite recipe that implements the user's requirements. <</SYS>> Create an OpenRewrite recipes that fulfills the following requirement: A diagnostic utility which emits the runtime classpath to a data table. [/INST] /*
* Copyright 2023 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite;
import io.github.classgraph.ClassGraph;
import io.github.classgraph.Resource;
import io.github.classgraph.ResourceList;
import io.github.classgraph.ScanResult;
import org.openrewrite.table.ClasspathReport;
import java.net.URI;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ListRuntimeClasspath extends ScanningRecipe<Void> {
transient ClasspathReport report = new ClasspathReport(this);
@Override
public String getDisplayName() {
return "List runtime classpath";
}
@Override
public String getDescription() {
return "A diagnostic utility which emits the runtime classpath to a data table.";
}
@Override
public Void getInitialValue(ExecutionContext ctx) {
return null;
}
@Override
public TreeVisitor<?, ExecutionContext> getScanner(Void acc) {
return TreeVisitor.noop();
}
@Override
public Collection<? extends SourceFile> generate(Void acc, ExecutionContext ctx) {
try (ScanResult result = new ClassGraph().scan()) {
ResourceList resources = result.getResourcesWithExtension(".jar");
Map<String, List<Resource>> classpathEntriesWithJarResources = resources.stream()
.collect(Collectors.groupingBy(it -> it.getClasspathElementURI().toString()));
for (URI classPathUri : result.getClasspathURIs()) {
List<Resource> jarResources = classpathEntriesWithJarResources.get(classPathUri.toString());
if (jarResources == null || jarResources.isEmpty()) {
report.insertRow(ctx, new ClasspathReport.Row(classPathUri.toString(), ""));
} else {
for (Resource r : jarResources) {
report.insertRow(ctx, new ClasspathReport.Row(classPathUri.toString(), r.getPath()));
}
}
}
}
return Collections.emptyList();
}
} </s> |
<s>[INST] <<SYS>> You are an assistant to create OpenRewrite recipes by providing the Java source code for an OpenRewrite recipe that implements the user's requirements. <</SYS>> Create an OpenRewrite recipes that fulfills the following requirement: Change the group of a specified Gradle dependency. [/INST] /*
* Copyright 2021 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite.gradle;
import lombok.EqualsAndHashCode;
import lombok.Value;
import org.openrewrite.*;
import org.openrewrite.gradle.util.ChangeStringLiteral;
import org.openrewrite.gradle.util.Dependency;
import org.openrewrite.gradle.util.DependencyStringNotationConverter;
import org.openrewrite.groovy.GroovyVisitor;
import org.openrewrite.groovy.tree.G;
import org.openrewrite.internal.ListUtils;
import org.openrewrite.internal.StringUtils;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.J;
import org.openrewrite.semver.DependencyMatcher;
import java.util.List;
import static java.util.Objects.requireNonNull;
@EqualsAndHashCode(callSuper = false)
@Value
public class ChangeDependencyGroupId extends Recipe {
@Option(displayName = "Group",
description = "The first part of a dependency coordinate `com.google.guava:guava:VERSION`. This can be a glob expression.",
example = "com.fasterxml.jackson*")
String groupId;
@Option(displayName = "Artifact",
description = "The second part of a dependency coordinate `com.google.guava:guava:VERSION`. This can be a glob expression.",
example = "jackson-module*")
String artifactId;
@Option(displayName = "New groupId",
description = "The new groupId to use.",
example = "corp.internal.jackson")
String newGroupId;
@Option(displayName = "Dependency configuration",
description = "The dependency configuration to search for dependencies in.",
example = "api",
required = false)
@Nullable
String configuration;
@Override
public String getDisplayName() {
return "Change Gradle dependency group";
}
@Override
public String getInstanceNameSuffix() {
return String.format("`%s:%s`", groupId, artifactId);
}
@Override
public String getDescription() {
return "Change the group of a specified Gradle dependency.";
}
@Override
public Validated<Object> validate() {
return super.validate().and(DependencyMatcher.build(groupId + ":" + artifactId));
}
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return Preconditions.check(new IsBuildGradle<>(), new GroovyVisitor<ExecutionContext>() {
final DependencyMatcher depMatcher = requireNonNull(DependencyMatcher.build(groupId + ":" + artifactId).getValue());
final MethodMatcher dependencyDsl = new MethodMatcher("DependencyHandlerSpec *(..)");
@Override
public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
J.MethodInvocation m = (J.MethodInvocation) super.visitMethodInvocation(method, ctx);
if (!dependencyDsl.matches(m) || !(StringUtils.isBlank(configuration) || m.getSimpleName().equals(configuration))) {
return m;
}
List<Expression> depArgs = m.getArguments();
if (depArgs.get(0) instanceof J.Literal || depArgs.get(0) instanceof G.GString || depArgs.get(0) instanceof G.MapEntry) {
m = updateDependency(m);
} else if (depArgs.get(0) instanceof J.MethodInvocation &&
(((J.MethodInvocation) depArgs.get(0)).getSimpleName().equals("platform") ||
((J.MethodInvocation) depArgs.get(0)).getSimpleName().equals("enforcedPlatform"))) {
m = m.withArguments(ListUtils.mapFirst(depArgs, platform -> updateDependency((J.MethodInvocation) platform)));
}
return m;
}
private J.MethodInvocation updateDependency(J.MethodInvocation m) {
List<Expression> depArgs = m.getArguments();
if (depArgs.get(0) instanceof J.Literal) {
String gav = (String) ((J.Literal) depArgs.get(0)).getValue();
if (gav != null) {
Dependency dependency = DependencyStringNotationConverter.parse(gav);
if (!newGroupId.equals(dependency.getGroupId()) &&
((dependency.getVersion() == null && depMatcher.matches(dependency.getGroupId(), dependency.getArtifactId())) ||
(dependency.getVersion() != null && depMatcher.matches(dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion())))) {
Dependency newDependency = dependency.withGroupId(newGroupId);
m = m.withArguments(ListUtils.mapFirst(m.getArguments(), arg -> ChangeStringLiteral.withStringValue((J.Literal) arg, newDependency.toStringNotation())));
}
}
} else if (depArgs.get(0) instanceof G.GString) {
List<J> strings = ((G.GString) depArgs.get(0)).getStrings();
if (strings.size() >= 2 &&
strings.get(0) instanceof J.Literal) {
Dependency dependency = DependencyStringNotationConverter.parse((String) ((J.Literal) strings.get(0)).getValue());
if (!newGroupId.equals(dependency.getGroupId())
&& depMatcher.matches(dependency.getGroupId(), dependency.getArtifactId())) {
dependency = dependency.withGroupId(newGroupId);
String replacement = dependency.toStringNotation();
m = m.withArguments(ListUtils.mapFirst(depArgs, arg -> {
G.GString gString = (G.GString) arg;
return gString.withStrings(ListUtils.mapFirst(gString.getStrings(), l -> ((J.Literal) l).withValue(replacement).withValueSource(replacement)));
}));
}
}
} else if (depArgs.get(0) instanceof G.MapEntry) {
G.MapEntry groupEntry = null;
String groupId = null;
String artifactId = null;
String version = null;
String versionStringDelimiter = "'";
for (Expression e : depArgs) {
if (!(e instanceof G.MapEntry)) {
continue;
}
G.MapEntry arg = (G.MapEntry) e;
if (!(arg.getKey() instanceof J.Literal) || !(arg.getValue() instanceof J.Literal)) {
continue;
}
J.Literal key = (J.Literal) arg.getKey();
J.Literal value = (J.Literal) arg.getValue();
if (!(key.getValue() instanceof String) || !(value.getValue() instanceof String)) {
continue;
}
String keyValue = (String) key.getValue();
String valueValue = (String) value.getValue();
if ("group".equals(keyValue) && !newGroupId.equals(valueValue)) {
if (value.getValueSource() != null) {
versionStringDelimiter = value.getValueSource().substring(0, value.getValueSource().indexOf(valueValue));
}
groupEntry = arg;
groupId = valueValue;
} else if ("name".equals(keyValue)) {
artifactId = valueValue;
} else if ("version".equals(keyValue)) {
version = valueValue;
}
}
if (groupId == null || artifactId == null
|| (version == null && !depMatcher.matches(groupId, artifactId))
|| (version != null && !depMatcher.matches(groupId, artifactId, version))) {
return m;
}
String delimiter = versionStringDelimiter;
G.MapEntry finalGroup = groupEntry;
m = m.withArguments(ListUtils.map(m.getArguments(), arg -> {
if (arg == finalGroup) {
return finalGroup.withValue(((J.Literal) finalGroup.getValue())
.withValue(newGroupId)
.withValueSource(delimiter + newGroupId + delimiter));
}
return arg;
}));
}
return m;
}
});
}
} </s> |
<s>[INST] <<SYS>> You are an assistant to create OpenRewrite recipes by providing the Java source code for an OpenRewrite recipe that implements the user's requirements. <</SYS>> Create an OpenRewrite recipes that fulfills the following requirement: Use `Map` notation for Gradle dependency declarations [/INST] /*
* Copyright 2021 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite.gradle;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Preconditions;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.gradle.util.Dependency;
import org.openrewrite.gradle.util.DependencyStringNotationConverter;
import org.openrewrite.groovy.GroovyVisitor;
import org.openrewrite.groovy.tree.G;
import org.openrewrite.internal.ListUtils;
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.tree.*;
import org.openrewrite.marker.Markers;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.openrewrite.Tree.randomId;
public class DependencyUseMapNotation extends Recipe {
@Override
public String getDisplayName() {
return "Use `Map` notation for Gradle dependency declarations";
}
@Override
public String getDescription() {
return "In Gradle, dependencies can be expressed as a `String` like `\"groupId:artifactId:version\"`, " +
"or equivalently as a `Map` like `group: 'groupId', name: 'artifactId', version: 'version'`. " +
"This recipe replaces dependencies represented as `Strings` with an equivalent dependency represented as a `Map`.";
}
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
final MethodMatcher dependencyDsl = new MethodMatcher("DependencyHandlerSpec *(..)");
return Preconditions.check(new IsBuildGradle<>(), new GroovyVisitor<ExecutionContext>() {
@Override
public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
J.MethodInvocation m = (J.MethodInvocation) super.visitMethodInvocation(method, ctx);
if (!dependencyDsl.matches(m)) {
return m;
}
m = forBasicString(m);
m = forGString(m);
return m;
}
private J.MethodInvocation forBasicString(J.MethodInvocation m) {
Expression e = m.getArguments().get(0);
if (!(e instanceof J.Literal)) {
return m;
}
J.Literal arg = (J.Literal) e;
if (arg.getType() != JavaType.Primitive.String) {
return m;
}
String dependencyString = (String) arg.getValue();
if (dependencyString == null) {
return m;
}
Dependency dependency = DependencyStringNotationConverter.parse(dependencyString);
List<Expression> arguments = new ArrayList<>();
arguments.add(mapEntry("group", dependency.getGroupId())
.withMarkers(arg.getMarkers())
.withPrefix(arg.getPrefix()));
arguments.add(mapEntry("name", dependency.getArtifactId())
.withMarkers(arg.getMarkers()));
if (dependency.getVersion() != null) {
arguments.add(mapEntry("version", dependency.getVersion())
.withMarkers(arg.getMarkers()));
}
if (dependency.getClassifier() != null) {
arguments.add(mapEntry("classifier", dependency.getClassifier())
.withMarkers(arg.getMarkers()));
}
if (dependency.getExt() != null) {
arguments.add(mapEntry("ext", dependency.getExt())
.withMarkers(arg.getMarkers()));
}
Expression lastArg = m.getArguments().get(m.getArguments().size() - 1);
if (lastArg instanceof J.Lambda) {
m = m.withArguments(ListUtils.concat(arguments, lastArg));
} else {
m = m.withArguments(arguments);
}
return updateTypeForMapArgument(m);
}
private J.MethodInvocation forGString(J.MethodInvocation m) {
Expression e = m.getArguments().get(0);
if (!(e instanceof G.GString)) {
return m;
}
G.GString g = (G.GString)e;
// Supporting all possible GString interpolations is impossible
// Supporting all probable GString interpolations is difficult
// This focuses on the most common case: When only the version number is interpolated
if (g.getStrings().size() != 2 || !(g.getStrings().get(0) instanceof J.Literal)
|| !(g.getStrings().get(1) instanceof G.GString.Value)) {
return m;
}
J.Literal arg1 = (J.Literal)g.getStrings().get(0);
if (arg1.getType() != JavaType.Primitive.String || arg1.getValue() == null) {
return m;
}
String[] ga = ((String) arg1.getValue()).split(":");
if (ga.length != 2) {
return m;
}
G.GString.Value arg2 = (G.GString.Value)g.getStrings().get(1);
if (!(arg2.getTree() instanceof Expression)) {
return m;
}
G.MapEntry groupEntry = mapEntry("group", ga[0])
.withMarkers(e.getMarkers())
.withPrefix(e.getPrefix());
G.MapEntry artifactEntry = mapEntry("name", ga[1])
.withMarkers(e.getMarkers());
G.MapEntry versionEntry = mapEntry("version", (Expression) arg2.getTree().withPrefix(Space.format(" ")))
.withMarkers(e.getMarkers());
Expression lastArg = m.getArguments().get(m.getArguments().size() - 1);
if (lastArg instanceof J.Lambda) {
m = m.withArguments(Arrays.asList(groupEntry, artifactEntry, versionEntry, lastArg));
} else {
m = m.withArguments(Arrays.asList(groupEntry, artifactEntry, versionEntry));
}
return updateTypeForMapArgument(m);
}
private J.MethodInvocation updateTypeForMapArgument(J.MethodInvocation m) {
JavaType.Method mtype = m.getMethodType();
if (mtype == null) {
return m;
}
mtype = mtype.withParameterTypes(singletonList(JavaType.ShallowClass.build("java.util.Map")));
if (m.getName().getType() != null) {
m = m.withName(m.getName().withType(mtype));
}
return m.withMethodType(mtype);
}
});
}
private static G.MapEntry mapEntry(String key, String value) {
return mapEntry(key,
new J.Literal(randomId(), Space.build(" ", emptyList()), Markers.EMPTY, value, "'" + value + "'", null, JavaType.Primitive.String));
}
private static G.MapEntry mapEntry(String key, Expression e) {
return new G.MapEntry(
randomId(),
Space.format(" "),
Markers.EMPTY,
JRightPadded.build(new J.Identifier(randomId(), Space.EMPTY, Markers.EMPTY, emptyList(), key, null, null)),
e,
null
);
}
} </s> |
<s>[INST] <<SYS>> You are an assistant to create OpenRewrite recipes by providing the Java source code for an OpenRewrite recipe that implements the user's requirements. <</SYS>> Create an OpenRewrite recipes that fulfills the following requirement: Change the artifact of a specified Gradle dependency. [/INST] /*
* Copyright 2021 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite.gradle;
import lombok.EqualsAndHashCode;
import lombok.Value;
import org.openrewrite.*;
import org.openrewrite.gradle.util.ChangeStringLiteral;
import org.openrewrite.gradle.util.Dependency;
import org.openrewrite.gradle.util.DependencyStringNotationConverter;
import org.openrewrite.groovy.GroovyVisitor;
import org.openrewrite.groovy.tree.G;
import org.openrewrite.internal.ListUtils;
import org.openrewrite.internal.StringUtils;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.J;
import org.openrewrite.semver.DependencyMatcher;
import java.util.List;
import static java.util.Objects.requireNonNull;
@EqualsAndHashCode(callSuper = false)
@Value
public class ChangeDependencyArtifactId extends Recipe {
@Option(displayName = "Group",
description = "The first part of a dependency coordinate `com.google.guava:guava:VERSION`. This can be a glob expression.",
example = "com.fasterxml.jackson*")
String groupId;
@Option(displayName = "Artifact",
description = "The second part of a dependency coordinate `com.google.guava:guava:VERSION`. This can be a glob expression.",
example = "jackson-module*")
String artifactId;
@Option(displayName = "New artifactId",
description = "The new artifactId to use.",
example = "jackson-custom")
String newArtifactId;
@Option(displayName = "Dependency configuration",
description = "The dependency configuration to search for dependencies in.",
example = "api",
required = false)
@Nullable
String configuration;
@Override
public String getDisplayName() {
return "Change Gradle dependency artifact";
}
@Override
public String getInstanceNameSuffix() {
return String.format("`%s:%s`", groupId, artifactId);
}
@Override
public String getDescription() {
return "Change the artifact of a specified Gradle dependency.";
}
@Override
public Validated<Object> validate() {
return super.validate().and(DependencyMatcher.build(groupId + ":" + artifactId));
}
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return Preconditions.check(new IsBuildGradle<>(), new GroovyVisitor<ExecutionContext>() {
final DependencyMatcher depMatcher = requireNonNull(DependencyMatcher.build(groupId + ":" + artifactId).getValue());
final MethodMatcher dependencyDsl = new MethodMatcher("DependencyHandlerSpec *(..)");
@Override
public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
J.MethodInvocation m = (J.MethodInvocation) super.visitMethodInvocation(method, ctx);
if (!dependencyDsl.matches(m) || !(StringUtils.isBlank(configuration) || m.getSimpleName().equals(configuration))) {
return m;
}
List<Expression> depArgs = m.getArguments();
if (depArgs.get(0) instanceof J.Literal || depArgs.get(0) instanceof G.GString || depArgs.get(0) instanceof G.MapEntry) {
m = updateDependency(m);
} else if (depArgs.get(0) instanceof J.MethodInvocation &&
(((J.MethodInvocation) depArgs.get(0)).getSimpleName().equals("platform") ||
((J.MethodInvocation) depArgs.get(0)).getSimpleName().equals("enforcedPlatform"))) {
m = m.withArguments(ListUtils.map(depArgs, platform -> updateDependency((J.MethodInvocation) platform)));
}
return m;
}
private J.MethodInvocation updateDependency(J.MethodInvocation m) {
List<Expression> depArgs = m.getArguments();
if (depArgs.get(0) instanceof J.Literal) {
String gav = (String) ((J.Literal) depArgs.get(0)).getValue();
if (gav != null) {
Dependency dependency = DependencyStringNotationConverter.parse(gav);
if (!newArtifactId.equals(dependency.getArtifactId()) &&
((dependency.getVersion() == null && depMatcher.matches(dependency.getGroupId(), dependency.getArtifactId())) ||
(dependency.getVersion() != null && depMatcher.matches(dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion())))) {
Dependency newDependency = dependency.withArtifactId(newArtifactId);
m = m.withArguments(ListUtils.mapFirst(m.getArguments(), arg -> ChangeStringLiteral.withStringValue((J.Literal) arg, newDependency.toStringNotation())));
}
}
} else if (depArgs.get(0) instanceof G.GString) {
List<J> strings = ((G.GString) depArgs.get(0)).getStrings();
if (strings.size() >= 2 &&
strings.get(0) instanceof J.Literal) {
Dependency dependency = DependencyStringNotationConverter.parse((String) ((J.Literal) strings.get(0)).getValue());
if (!newArtifactId.equals(dependency.getArtifactId())
&& depMatcher.matches(dependency.getGroupId(), dependency.getArtifactId())) {
dependency = dependency.withArtifactId(newArtifactId);
String replacement = dependency.toStringNotation();
m = m.withArguments(ListUtils.mapFirst(depArgs, arg -> {
G.GString gString = (G.GString) arg;
return gString.withStrings(ListUtils.mapFirst(gString.getStrings(), l -> ((J.Literal) l).withValue(replacement).withValueSource(replacement)));
}));
}
}
} else if (depArgs.get(0) instanceof G.MapEntry) {
G.MapEntry artifactEntry = null;
String groupId = null;
String artifactId = null;
String version = null;
String versionStringDelimiter = "'";
for (Expression e : depArgs) {
if (!(e instanceof G.MapEntry)) {
continue;
}
G.MapEntry arg = (G.MapEntry) e;
if (!(arg.getKey() instanceof J.Literal) || !(arg.getValue() instanceof J.Literal)) {
continue;
}
J.Literal key = (J.Literal) arg.getKey();
J.Literal value = (J.Literal) arg.getValue();
if (!(key.getValue() instanceof String) || !(value.getValue() instanceof String)) {
continue;
}
String keyValue = (String) key.getValue();
String valueValue = (String) value.getValue();
if ("group".equals(keyValue)) {
groupId = valueValue;
} else if ("name".equals(keyValue) && !newArtifactId.equals(valueValue)) {
if (value.getValueSource() != null) {
versionStringDelimiter = value.getValueSource().substring(0, value.getValueSource().indexOf(valueValue));
}
artifactEntry = arg;
artifactId = valueValue;
} else if ("version".equals(keyValue)) {
version = valueValue;
}
}
if (groupId == null || artifactId == null
|| (version == null && !depMatcher.matches(groupId, artifactId))
|| (version != null && !depMatcher.matches(groupId, artifactId, version))) {
return m;
}
String delimiter = versionStringDelimiter;
G.MapEntry finalArtifact = artifactEntry;
m = m.withArguments(ListUtils.map(m.getArguments(), arg -> {
if (arg == finalArtifact) {
return finalArtifact.withValue(((J.Literal) finalArtifact.getValue())
.withValue(newArtifactId)
.withValueSource(delimiter + newArtifactId + delimiter));
}
return arg;
}));
}
return m;
}
});
}
} </s> |
<s>[INST] <<SYS>> You are an assistant to create OpenRewrite recipes by providing the Java source code for an OpenRewrite recipe that implements the user's requirements. <</SYS>> Create an OpenRewrite recipes that fulfills the following requirement: Change a Gradle dependency coordinates. The `newGroupId` or `newArtifactId` **MUST** be different from before. [/INST] /*
* Copyright 2023 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite.gradle;
import com.fasterxml.jackson.annotation.JsonCreator;
import lombok.EqualsAndHashCode;
import lombok.Value;
import org.openrewrite.*;
import org.openrewrite.gradle.marker.GradleDependencyConfiguration;
import org.openrewrite.gradle.marker.GradleProject;
import org.openrewrite.gradle.search.FindGradleProject;
import org.openrewrite.gradle.util.ChangeStringLiteral;
import org.openrewrite.gradle.util.Dependency;
import org.openrewrite.gradle.util.DependencyStringNotationConverter;
import org.openrewrite.groovy.GroovyIsoVisitor;
import org.openrewrite.groovy.tree.G;
import org.openrewrite.internal.ListUtils;
import org.openrewrite.internal.StringUtils;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.J;
import org.openrewrite.maven.MavenDownloadingException;
import org.openrewrite.maven.tree.GroupArtifact;
import org.openrewrite.maven.tree.GroupArtifactVersion;
import org.openrewrite.maven.tree.ResolvedGroupArtifactVersion;
import org.openrewrite.semver.DependencyMatcher;
import org.openrewrite.semver.Semver;
import java.util.*;
import static java.util.Objects.requireNonNull;
@Value
@EqualsAndHashCode(callSuper = false)
public class ChangeDependency extends Recipe {
@Option(displayName = "Old groupId",
description = "The old groupId to replace. The groupId is the first part of a dependency coordinate 'com.google.guava:guava:VERSION'. Supports glob expressions.",
example = "org.openrewrite.recipe")
String oldGroupId;
@Option(displayName = "Old artifactId",
description = "The old artifactId to replace. The artifactId is the second part of a dependency coordinate 'com.google.guava:guava:VERSION'. Supports glob expressions.",
example = "rewrite-testing-frameworks")
String oldArtifactId;
@Option(displayName = "New groupId",
description = "The new groupId to use. Defaults to the existing group id.",
example = "corp.internal.openrewrite.recipe",
required = false)
@Nullable
String newGroupId;
@Option(displayName = "New artifactId",
description = "The new artifactId to use. Defaults to the existing artifact id.",
example = "rewrite-testing-frameworks",
required = false)
@Nullable
String newArtifactId;
@Option(displayName = "New version",
description = "An exact version number or node-style semver selector used to select the version number. " +
"You can also use `latest.release` for the latest available version and `latest.patch` if " +
"the current version is a valid semantic version. For more details, you can look at the documentation " +
"page of [version selectors](https://docs.openrewrite.org/reference/dependency-version-selectors).",
example = "29.X",
required = false)
@Nullable
String newVersion;
@Option(displayName = "Version pattern",
description = "Allows version selection to be extended beyond the original Node Semver semantics. So for example," +
"Setting 'version' to \"25-29\" can be paired with a metadata pattern of \"-jre\" to select Guava 29.0-jre",
example = "-jre",
required = false)
@Nullable
String versionPattern;
@Option(displayName = "Override managed version",
description = "If the old dependency has a managed version, this flag can be used to explicitly set the version on the new dependency. " +
"WARNING: No check is done on the NEW dependency to verify if it is managed, it relies on whether the OLD dependency had a managed version. " +
"The default for this flag is `false`.",
required = false)
@Nullable
Boolean overrideManagedVersion;
/**
* Keeping this constructor just for compatibility purposes
*
* @deprecated Use {@link ChangeDependency#ChangeDependency(String, String, String, String, String, String, Boolean)}
*/
@Deprecated
public ChangeDependency(String oldGroupId, String oldArtifactId, @Nullable String newGroupId, @Nullable String newArtifactId, @Nullable String newVersion, @Nullable String versionPattern) {
this(oldGroupId, oldArtifactId, newGroupId, newArtifactId, newVersion, versionPattern, null);
}
@JsonCreator
public ChangeDependency(String oldGroupId, String oldArtifactId, @Nullable String newGroupId, @Nullable String newArtifactId, @Nullable String newVersion, @Nullable String versionPattern, @Nullable Boolean overrideManagedVersion) {
this.oldGroupId = oldGroupId;
this.oldArtifactId = oldArtifactId;
this.newGroupId = newGroupId;
this.newArtifactId = newArtifactId;
this.newVersion = newVersion;
this.versionPattern = versionPattern;
this.overrideManagedVersion = overrideManagedVersion;
}
@Override
public String getDisplayName() {
return "Change Gradle dependency";
}
@Override
public String getInstanceNameSuffix() {
return String.format("`%s:%s`", oldGroupId, oldArtifactId);
}
@Override
public String getDescription() {
return "Change a Gradle dependency coordinates. The `newGroupId` or `newArtifactId` **MUST** be different from before.";
}
@Override
public Validated<Object> validate() {
Validated<Object> validated = super.validate();
if (newVersion != null) {
validated = validated.and(Semver.validate(newVersion, versionPattern));
}
validated = validated.and(Validated.required("newGroupId", newGroupId).or(Validated.required("newArtifactId", newArtifactId)));
validated = validated.and(Validated.test(
"coordinates",
"newGroupId OR newArtifactId must be different from before",
this,
r -> {
boolean sameGroupId = StringUtils.isBlank(r.newGroupId) || Objects.equals(r.oldGroupId, r.newGroupId);
boolean sameArtifactId = StringUtils.isBlank(r.newArtifactId) || Objects.equals(r.oldArtifactId, r.newArtifactId);
return !(sameGroupId && sameArtifactId);
}
));
return validated;
}
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return Preconditions.check(new FindGradleProject(FindGradleProject.SearchCriteria.Marker).getVisitor(), new GroovyIsoVisitor<ExecutionContext>() {
final DependencyMatcher depMatcher = requireNonNull(DependencyMatcher.build(oldGroupId + ":" + oldArtifactId).getValue());
final MethodMatcher dependencyDsl = new MethodMatcher("DependencyHandlerSpec *(..)");
GradleProject gradleProject;
@Override
public G.CompilationUnit visitCompilationUnit(G.CompilationUnit cu, ExecutionContext ctx) {
Optional<GradleProject> maybeGp = cu.getMarkers().findFirst(GradleProject.class);
if (!maybeGp.isPresent()) {
return cu;
}
gradleProject = maybeGp.get();
G.CompilationUnit g = super.visitCompilationUnit(cu, ctx);
if (g != cu) {
g = g.withMarkers(g.getMarkers().setByType(updateGradleModel(gradleProject)));
}
return g;
}
@Override
public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
J.MethodInvocation m = super.visitMethodInvocation(method, ctx);
if (!dependencyDsl.matches(m)) {
return m;
}
List<Expression> depArgs = m.getArguments();
if (depArgs.get(0) instanceof J.Literal || depArgs.get(0) instanceof G.GString || depArgs.get(0) instanceof G.MapEntry) {
m = updateDependency(m, ctx);
} else if (depArgs.get(0) instanceof J.MethodInvocation &&
(((J.MethodInvocation) depArgs.get(0)).getSimpleName().equals("platform") ||
((J.MethodInvocation) depArgs.get(0)).getSimpleName().equals("enforcedPlatform"))) {
m = m.withArguments(ListUtils.mapFirst(depArgs, platform -> updateDependency((J.MethodInvocation) platform, ctx)));
}
return m;
}
private J.MethodInvocation updateDependency(J.MethodInvocation m, ExecutionContext ctx) {
List<Expression> depArgs = m.getArguments();
if (depArgs.get(0) instanceof J.Literal) {
String gav = (String) ((J.Literal) depArgs.get(0)).getValue();
if (gav != null) {
Dependency original = DependencyStringNotationConverter.parse(gav);
if (depMatcher.matches(original.getGroupId(), original.getArtifactId())) {
Dependency updated = original;
if (!StringUtils.isBlank(newGroupId) && !updated.getGroupId().equals(newGroupId)) {
updated = updated.withGroupId(newGroupId);
}
if (!StringUtils.isBlank(newArtifactId) && !updated.getArtifactId().equals(newArtifactId)) {
updated = updated.withArtifactId(newArtifactId);
}
if (!StringUtils.isBlank(newVersion) && (!StringUtils.isBlank(original.getVersion()) || Boolean.TRUE.equals(overrideManagedVersion))) {
String resolvedVersion;
try {
resolvedVersion = new DependencyVersionSelector(null, gradleProject)
.select(new GroupArtifact(updated.getGroupId(), updated.getArtifactId()), m.getSimpleName(), newVersion, versionPattern, ctx);
} catch (MavenDownloadingException e) {
return e.warn(m);
}
if (resolvedVersion != null && !resolvedVersion.equals(updated.getVersion())) {
updated = updated.withVersion(resolvedVersion);
}
}
if (original != updated) {
String replacement = updated.toStringNotation();
m = m.withArguments(ListUtils.mapFirst(m.getArguments(), arg -> ChangeStringLiteral.withStringValue((J.Literal) arg, replacement)));
}
}
}
} else if (m.getArguments().get(0) instanceof G.GString) {
G.GString gstring = (G.GString) depArgs.get(0);
List<J> strings = gstring.getStrings();
if (strings.size() >= 2 && strings.get(0) instanceof J.Literal &&
((J.Literal) strings.get(0)).getValue() != null) {
J.Literal literal = (J.Literal) strings.get(0);
Dependency original = DependencyStringNotationConverter.parse((String) requireNonNull(literal.getValue()));
if (depMatcher.matches(original.getGroupId(), original.getArtifactId())) {
Dependency updated = original;
if (!StringUtils.isBlank(newGroupId) && !updated.getGroupId().equals(newGroupId)) {
updated = updated.withGroupId(newGroupId);
}
if (!StringUtils.isBlank(newArtifactId) && !updated.getArtifactId().equals(newArtifactId)) {
updated = updated.withArtifactId(newArtifactId);
}
if (!StringUtils.isBlank(newVersion)) {
String resolvedVersion;
try {
resolvedVersion = new DependencyVersionSelector(null, gradleProject)
.select(new GroupArtifact(updated.getGroupId(), updated.getArtifactId()), m.getSimpleName(), newVersion, versionPattern, ctx);
} catch (MavenDownloadingException e) {
return e.warn(m);
}
if (resolvedVersion != null && !resolvedVersion.equals(updated.getVersion())) {
updated = updated.withVersion(resolvedVersion);
}
}
if (original != updated) {
String replacement = updated.toStringNotation();
J.Literal newLiteral = literal.withValue(replacement)
.withValueSource(gstring.getDelimiter() + replacement + gstring.getDelimiter());
m = m.withArguments(Collections.singletonList(newLiteral));
}
}
}
} else if (m.getArguments().get(0) instanceof G.MapEntry) {
G.MapEntry groupEntry = null;
G.MapEntry artifactEntry = null;
G.MapEntry versionEntry = null;
String groupId = null;
String artifactId = null;
String version = null;
for (Expression e : depArgs) {
if (!(e instanceof G.MapEntry)) {
continue;
}
G.MapEntry arg = (G.MapEntry) e;
if (!(arg.getKey() instanceof J.Literal) || !(arg.getValue() instanceof J.Literal)) {
continue;
}
J.Literal key = (J.Literal) arg.getKey();
J.Literal value = (J.Literal) arg.getValue();
if (!(key.getValue() instanceof String) || !(value.getValue() instanceof String)) {
continue;
}
String keyValue = (String) key.getValue();
String valueValue = (String) value.getValue();
switch (keyValue) {
case "group":
groupEntry = arg;
groupId = valueValue;
break;
case "name":
artifactEntry = arg;
artifactId = valueValue;
break;
case "version":
versionEntry = arg;
version = valueValue;
break;
}
}
if (groupId == null || artifactId == null) {
return m;
}
if (!depMatcher.matches(groupId, artifactId)) {
return m;
}
String updatedGroupId = groupId;
if (!StringUtils.isBlank(newGroupId) && !updatedGroupId.equals(newGroupId)) {
updatedGroupId = newGroupId;
}
String updatedArtifactId = artifactId;
if (!StringUtils.isBlank(newArtifactId) && !updatedArtifactId.equals(newArtifactId)) {
updatedArtifactId = newArtifactId;
}
String updatedVersion = version;
if (!StringUtils.isBlank(newVersion) && (!StringUtils.isBlank(version) || Boolean.TRUE.equals(overrideManagedVersion))) {
String resolvedVersion;
try {
resolvedVersion = new DependencyVersionSelector(null, gradleProject)
.select(new GroupArtifact(updatedGroupId, updatedArtifactId), m.getSimpleName(), newVersion, versionPattern, ctx);
} catch (MavenDownloadingException e) {
return e.warn(m);
}
if (resolvedVersion != null && !resolvedVersion.equals(updatedVersion)) {
updatedVersion = resolvedVersion;
}
}
if (!updatedGroupId.equals(groupId) || !updatedArtifactId.equals(artifactId) || updatedVersion != null && !updatedVersion.equals(version)) {
G.MapEntry finalGroup = groupEntry;
String finalGroupIdValue = updatedGroupId;
G.MapEntry finalArtifact = artifactEntry;
String finalArtifactIdValue = updatedArtifactId;
G.MapEntry finalVersion = versionEntry;
String finalVersionValue = updatedVersion;
m = m.withArguments(ListUtils.map(m.getArguments(), arg -> {
if (arg == finalGroup) {
return finalGroup.withValue(ChangeStringLiteral.withStringValue((J.Literal) finalGroup.getValue(), finalGroupIdValue));
}
if (arg == finalArtifact) {
return finalArtifact.withValue(ChangeStringLiteral.withStringValue((J.Literal) finalArtifact.getValue(), finalArtifactIdValue));
}
if (arg == finalVersion) {
return finalVersion.withValue(ChangeStringLiteral.withStringValue((J.Literal) finalVersion.getValue(), finalVersionValue));
}
return arg;
}));
}
}
return m;
}
private GradleProject updateGradleModel(GradleProject gp) {
Map<String, GradleDependencyConfiguration> nameToConfiguration = gp.getNameToConfiguration();
Map<String, GradleDependencyConfiguration> newNameToConfiguration = new HashMap<>(nameToConfiguration.size());
boolean anyChanged = false;
for (GradleDependencyConfiguration gdc : nameToConfiguration.values()) {
GradleDependencyConfiguration newGdc = gdc;
newGdc = newGdc.withRequested(ListUtils.map(gdc.getRequested(), requested -> {
if (depMatcher.matches(requested.getGroupId(), requested.getArtifactId())) {
GroupArtifactVersion gav = requested.getGav();
if (newGroupId != null) {
gav = gav.withGroupId(newGroupId);
}
if (newArtifactId != null) {
gav = gav.withArtifactId(newArtifactId);
}
if (gav != requested.getGav()) {
return requested.withGav(gav);
}
}
return requested;
}));
newGdc = newGdc.withDirectResolved(ListUtils.map(gdc.getDirectResolved(), resolved -> {
if (depMatcher.matches(resolved.getGroupId(), resolved.getArtifactId())) {
ResolvedGroupArtifactVersion gav = resolved.getGav();
if (newGroupId != null) {
gav = gav.withGroupId(newGroupId);
}
if (newArtifactId != null) {
gav = gav.withArtifactId(newArtifactId);
}
if (gav != resolved.getGav()) {
return resolved.withGav(gav);
}
}
return resolved;
}));
anyChanged |= newGdc != gdc;
newNameToConfiguration.put(newGdc.getName(), newGdc);
}
if (anyChanged) {
gp = gp.withNameToConfiguration(newNameToConfiguration);
}
return gp;
}
});
}
} </s> |
<s>[INST] <<SYS>> You are an assistant to create OpenRewrite recipes by providing the Java source code for an OpenRewrite recipe that implements the user's requirements. <</SYS>> Create an OpenRewrite recipes that fulfills the following requirement: Update Gradle wrapper [/INST] /*
* Copyright 2022 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite.gradle;
import lombok.AccessLevel;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import lombok.experimental.NonFinal;
import org.openrewrite.*;
import org.openrewrite.gradle.util.GradleWrapper;
import org.openrewrite.internal.ListUtils;
import org.openrewrite.internal.StringUtils;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.marker.BuildTool;
import org.openrewrite.marker.Markers;
import org.openrewrite.properties.PropertiesParser;
import org.openrewrite.properties.PropertiesVisitor;
import org.openrewrite.properties.search.FindProperties;
import org.openrewrite.properties.tree.Properties;
import org.openrewrite.quark.Quark;
import org.openrewrite.remote.Remote;
import org.openrewrite.semver.Semver;
import org.openrewrite.semver.VersionComparator;
import org.openrewrite.text.PlainText;
import java.time.ZonedDateTime;
import java.util.*;
import static java.util.Objects.requireNonNull;
import static org.openrewrite.PathUtils.equalIgnoringSeparators;
import static org.openrewrite.gradle.util.GradleWrapper.*;
import static org.openrewrite.internal.StringUtils.formatUriForPropertiesFile;
import static org.openrewrite.internal.StringUtils.isBlank;
@RequiredArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
@EqualsAndHashCode(callSuper = false)
public class UpdateGradleWrapper extends ScanningRecipe<UpdateGradleWrapper.GradleWrapperState> {
@Override
public String getDisplayName() {
return "Update Gradle wrapper";
}
@Override
public String getDescription() {
return "Update the version of Gradle used in an existing Gradle wrapper. " +
"Queries services.gradle.org to determine the available releases, but prefers the artifact repository URL " +
"which already exists within the wrapper properties file. " +
"If your artifact repository does not contain the same Gradle distributions as services.gradle.org, " +
"then the recipe may suggest a version which is not available in your artifact repository.";
}
@Getter
@Option(displayName = "New version",
description = "An exact version number or node-style semver selector used to select the version number. " +
"Defaults to the latest release available from services.gradle.org if not specified.",
example = "7.x",
required = false)
@Nullable
final String version;
@Getter
@Option(displayName = "Distribution type",
description = "The distribution of Gradle to use. \"bin\" includes Gradle binaries. " +
"\"all\" includes Gradle binaries, source code, and documentation. " +
"Defaults to \"bin\".",
valid = {"bin", "all"},
required = false
)
@Nullable
final String distribution;
@Getter
@Option(displayName = "Add if missing",
description = "Add a Gradle wrapper, if it's missing. Defaults to `true`.",
required = false)
@Nullable
final Boolean addIfMissing;
@Getter
@Option(displayName = "Wrapper URI",
description = "The URI of the Gradle wrapper distribution. " +
"Lookup of available versions still requires access to https://services.gradle.org " +
"When this is specified the exact literal values supplied for `version` and `distribution` " +
"will be interpolated into this string wherever `${version}` and `${distribution}` appear respectively. " +
"Defaults to https://services.gradle.org/distributions/gradle-${version}-${distribution}.zip.",
required = false)
@Nullable
final String wrapperUri;
@Override
public Validated<Object> validate() {
Validated<Object> validated = super.validate();
if (version != null) {
validated = validated.and(Semver.validate(version, null));
}
return validated;
}
@NonFinal
transient GradleWrapper gradleWrapper;
private GradleWrapper getGradleWrapper(ExecutionContext ctx) {
if (gradleWrapper == null) {
gradleWrapper = GradleWrapper.create(distribution, version, null, ctx);
}
return gradleWrapper;
}
public static class GradleWrapperState {
boolean needsWrapperUpdate = false;
BuildTool updatedMarker;
boolean addGradleWrapperProperties = true;
boolean addGradleWrapperJar = true;
boolean addGradleShellScript = true;
boolean addGradleBatchScript = true;
}
@Override
public GradleWrapperState getInitialValue(ExecutionContext ctx) {
return new GradleWrapperState();
}
@Override
public TreeVisitor<?, ExecutionContext> getScanner(GradleWrapperState acc) {
return Preconditions.or(
new PropertiesVisitor<ExecutionContext>() {
@Override
public boolean isAcceptable(SourceFile sourceFile, ExecutionContext ctx) {
if (!super.isAcceptable(sourceFile, ctx)) {
return false;
}
if (equalIgnoringSeparators(sourceFile.getSourcePath(), WRAPPER_PROPERTIES_LOCATION)) {
acc.addGradleWrapperProperties = false;
} else if (!PathUtils.matchesGlob(sourceFile.getSourcePath(), "**/" + WRAPPER_PROPERTIES_LOCATION_RELATIVE_PATH)) {
return false;
}
Optional<BuildTool> maybeBuildTool = sourceFile.getMarkers().findFirst(BuildTool.class);
if (!maybeBuildTool.isPresent()) {
return false;
}
BuildTool buildTool = maybeBuildTool.get();
if (buildTool.getType() != BuildTool.Type.Gradle) {
return false;
}
GradleWrapper gradleWrapper = getGradleWrapper(ctx);
VersionComparator versionComparator = requireNonNull(Semver.validate(isBlank(version) ? "latest.release" : version, null).getValue());
int compare = versionComparator.compare(null, buildTool.getVersion(), gradleWrapper.getVersion());
// maybe we want to update the distribution type or url
if (compare < 0) {
acc.needsWrapperUpdate = true;
acc.updatedMarker = buildTool.withVersion(gradleWrapper.getVersion());
return true;
} else return compare == 0;
}
@Override
public Properties visitEntry(Properties.Entry entry, ExecutionContext ctx) {
if (!"distributionUrl".equals(entry.getKey())) {
return entry;
}
GradleWrapper gradleWrapper = getGradleWrapper(ctx);
// Typical example: https://services.gradle.org/distributions/gradle-7.4-all.zip
String currentDistributionUrl = entry.getValue().getText();
if (!gradleWrapper.getPropertiesFormattedUrl().equals(currentDistributionUrl)) {
acc.needsWrapperUpdate = true;
}
return entry;
}
},
new TreeVisitor<Tree, ExecutionContext>() {
@Override
public boolean isAcceptable(SourceFile sourceFile, ExecutionContext ctx) {
if (!super.isAcceptable(sourceFile, ctx)) {
return false;
}
if ((sourceFile instanceof Quark || sourceFile instanceof Remote) &&
equalIgnoringSeparators(sourceFile.getSourcePath(), WRAPPER_JAR_LOCATION)) {
acc.addGradleWrapperJar = false;
return true;
}
if (sourceFile instanceof PlainText) {
if (equalIgnoringSeparators(sourceFile.getSourcePath(), WRAPPER_BATCH_LOCATION)) {
acc.addGradleBatchScript = false;
return true;
} else if (equalIgnoringSeparators(sourceFile.getSourcePath(), WRAPPER_SCRIPT_LOCATION)) {
acc.addGradleShellScript = false;
return true;
}
}
return false;
}
}
);
}
@Override
public Collection<SourceFile> generate(GradleWrapperState acc, ExecutionContext ctx) {
if (Boolean.FALSE.equals(addIfMissing)) {
return Collections.emptyList();
}
if (!(acc.addGradleWrapperJar || acc.addGradleWrapperProperties || acc.addGradleBatchScript || acc.addGradleShellScript)) {
return Collections.emptyList();
}
List<SourceFile> gradleWrapperFiles = new ArrayList<>();
ZonedDateTime now = ZonedDateTime.now();
GradleWrapper gradleWrapper = getGradleWrapper(ctx);
if (acc.addGradleWrapperProperties) {
//noinspection UnusedProperty
Properties.File gradleWrapperProperties = new PropertiesParser().parse(
"distributionBase=GRADLE_USER_HOME\n" +
"distributionPath=wrapper/dists\n" +
"distributionUrl=" + gradleWrapper.getPropertiesFormattedUrl() + "\n" +
"distributionSha256Sum=" + gradleWrapper.getDistributionChecksum().getHexValue() + "\n" +
"zipStoreBase=GRADLE_USER_HOME\n" +
"zipStorePath=wrapper/dists")
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("Could not parse as properties"))
.withSourcePath(WRAPPER_PROPERTIES_LOCATION);
gradleWrapperFiles.add(gradleWrapperProperties);
}
FileAttributes wrapperScriptAttributes = new FileAttributes(now, now, now, true, true, true, 1L);
if (acc.addGradleShellScript) {
String gradlewText = unixScript(gradleWrapper, ctx);
PlainText gradlew = PlainText.builder()
.text(gradlewText)
.sourcePath(WRAPPER_SCRIPT_LOCATION)
.fileAttributes(wrapperScriptAttributes)
.build();
gradleWrapperFiles.add(gradlew);
}
if (acc.addGradleBatchScript) {
String gradlewBatText = batchScript(gradleWrapper, ctx);
PlainText gradlewBat = PlainText.builder()
.text(gradlewBatText)
.sourcePath(WRAPPER_BATCH_LOCATION)
.fileAttributes(wrapperScriptAttributes)
.build();
gradleWrapperFiles.add(gradlewBat);
}
if (acc.addGradleWrapperJar) {
gradleWrapperFiles.add(gradleWrapper.wrapperJar());
}
return gradleWrapperFiles;
}
@Override
public TreeVisitor<?, ExecutionContext> getVisitor(GradleWrapperState acc) {
if (!acc.needsWrapperUpdate) {
return TreeVisitor.noop();
}
return new TreeVisitor<Tree, ExecutionContext>() {
@Override
public Tree visit(@Nullable Tree tree, ExecutionContext ctx) {
if (!(tree instanceof SourceFile)) {
return tree;
}
SourceFile sourceFile = (SourceFile) tree;
if (acc.updatedMarker != null) {
Optional<BuildTool> maybeCurrentMarker = sourceFile.getMarkers().findFirst(BuildTool.class);
if (maybeCurrentMarker.isPresent()) {
BuildTool currentMarker = maybeCurrentMarker.get();
if (currentMarker.getType() != BuildTool.Type.Gradle) {
return sourceFile;
}
VersionComparator versionComparator = requireNonNull(Semver.validate(isBlank(version) ? "latest.release" : version, null).getValue());
int compare = versionComparator.compare(null, currentMarker.getVersion(), acc.updatedMarker.getVersion());
if (compare < 0) {
sourceFile = sourceFile.withMarkers(sourceFile.getMarkers().setByType(acc.updatedMarker));
} else {
return sourceFile;
}
}
}
if (sourceFile instanceof PlainText && PathUtils.matchesGlob(sourceFile.getSourcePath(), "**/" + WRAPPER_SCRIPT_LOCATION_RELATIVE_PATH)) {
String gradlewText = unixScript(gradleWrapper, ctx);
PlainText gradlew = (PlainText) setExecutable(sourceFile);
if (!gradlewText.equals(gradlew.getText())) {
gradlew = gradlew.withText(gradlewText);
}
return gradlew;
}
if (sourceFile instanceof PlainText && PathUtils.matchesGlob(sourceFile.getSourcePath(), "**/" + WRAPPER_BATCH_LOCATION_RELATIVE_PATH)) {
String gradlewBatText = batchScript(gradleWrapper, ctx);
PlainText gradlewBat = (PlainText) setExecutable(sourceFile);
if (!gradlewBatText.equals(gradlewBat.getText())) {
gradlewBat = gradlewBat.withText(gradlewBatText);
}
return gradlewBat;
}
if (sourceFile instanceof Properties.File && PathUtils.matchesGlob(sourceFile.getSourcePath(), "**/" + WRAPPER_PROPERTIES_LOCATION_RELATIVE_PATH)) {
return new WrapperPropertiesVisitor(gradleWrapper).visitNonNull(sourceFile, ctx);
}
if ((sourceFile instanceof Quark || sourceFile instanceof Remote) && PathUtils.matchesGlob(sourceFile.getSourcePath(), "**/" + WRAPPER_JAR_LOCATION_RELATIVE_PATH)) {
return gradleWrapper.wrapperJar(sourceFile);
}
return sourceFile;
}
};
}
private static <T extends SourceFile> T setExecutable(T sourceFile) {
FileAttributes attributes = sourceFile.getFileAttributes();
if (attributes == null) {
ZonedDateTime now = ZonedDateTime.now();
return sourceFile.withFileAttributes(new FileAttributes(now, now, now, true, true, true, 1));
} else if (!attributes.isExecutable()) {
return sourceFile.withFileAttributes(attributes.withExecutable(true));
}
return sourceFile;
}
private String unixScript(GradleWrapper gradleWrapper, ExecutionContext ctx) {
Map<String, String> binding = new HashMap<>();
String defaultJvmOpts = defaultJvmOpts(gradleWrapper);
binding.put("defaultJvmOpts", StringUtils.isNotEmpty(defaultJvmOpts) ? "'" + defaultJvmOpts + "'" : "");
binding.put("classpath", "$APP_HOME/gradle/wrapper/gradle-wrapper.jar");
String gradlewTemplate = StringUtils.readFully(gradleWrapper.gradlew().getInputStream(ctx));
return renderTemplate(gradlewTemplate, binding, "\n");
}
private String batchScript(GradleWrapper gradleWrapper, ExecutionContext ctx) {
Map<String, String> binding = new HashMap<>();
binding.put("defaultJvmOpts", defaultJvmOpts(gradleWrapper));
binding.put("classpath", "%APP_HOME%\\gradle\\wrapper\\gradle-wrapper.jar");
String gradlewBatTemplate = StringUtils.readFully(gradleWrapper.gradlewBat().getInputStream(ctx));
return renderTemplate(gradlewBatTemplate, binding, "\r\n");
}
private String defaultJvmOpts(GradleWrapper gradleWrapper) {
VersionComparator gradle53VersionComparator = requireNonNull(Semver.validate("[5.3,)", null).getValue());
VersionComparator gradle50VersionComparator = requireNonNull(Semver.validate("[5.0,)", null).getValue());
if (gradle53VersionComparator.isValid(null, gradleWrapper.getVersion())) {
return "\"-Xmx64m\" \"-Xms64m\"";
} else if (gradle50VersionComparator.isValid(null, gradleWrapper.getVersion())) {
return "\"-Xmx64m\"";
}
return "";
}
private String renderTemplate(String source, Map<String, String> parameters, String lineSeparator) {
Map<String, String> binding = new HashMap<>(parameters);
binding.put("applicationName", "Gradle");
binding.put("optsEnvironmentVar", "GRADLE_OPTS");
binding.put("exitEnvironmentVar", "GRADLE_EXIT_CONSOLE");
binding.put("mainClassName", "org.gradle.wrapper.GradleWrapperMain");
binding.put("appNameSystemProperty", "org.gradle.appname");
binding.put("appHomeRelativePath", "");
binding.put("modulePath", "");
String script = source;
for (Map.Entry<String, String> variable : binding.entrySet()) {
script = script.replace("${" + variable.getKey() + "}", variable.getValue())
.replace("$" + variable.getKey(), variable.getValue());
}
script = script.replaceAll("(?sm)<% /\\*.*?\\*/ %>", "");
script = script.replaceAll("(?sm)<% if \\( mainClassName\\.startsWith\\('--module '\\) \\) \\{.*?} %>", "");
script = script.replaceAll("(?sm)<% if \\( appNameSystemProperty \\) \\{.*?%>(.*?)<% } %>", "$1");
script = script.replace("\\$", "$");
script = script.replaceAll("DIRNAME=\\.\\\\[\r\n]", "DIRNAME=.");
script = script.replace("\\\\", "\\");
script = script.replaceAll("\r\n|\r|\n", lineSeparator);
return script;
}
private class WrapperPropertiesVisitor extends PropertiesVisitor<ExecutionContext> {
private static final String DISTRIBUTION_SHA_256_SUM_KEY = "distributionSha256Sum";
private final GradleWrapper gradleWrapper;
public WrapperPropertiesVisitor(GradleWrapper gradleWrapper) {
this.gradleWrapper = gradleWrapper;
}
@Override
public Properties visitFile(Properties.File file, ExecutionContext ctx) {
Properties p = super.visitFile(file, ctx);
Set<Properties.Entry> checksumKey = FindProperties.find(p, DISTRIBUTION_SHA_256_SUM_KEY, false);
if (checksumKey.isEmpty()) {
Properties.Value propertyValue = new Properties.Value(Tree.randomId(), "", Markers.EMPTY, gradleWrapper.getDistributionChecksum().getHexValue());
Properties.Entry entry = new Properties.Entry(Tree.randomId(), "\n", Markers.EMPTY, DISTRIBUTION_SHA_256_SUM_KEY, "", Properties.Entry.Delimiter.EQUALS, propertyValue);
List<Properties.Content> contentList = ListUtils.concat(((Properties.File) p).getContent(), entry);
p = ((Properties.File) p).withContent(contentList);
}
return p;
}
@Override
public Properties visitEntry(Properties.Entry entry, ExecutionContext ctx) {
if ("distributionUrl".equals(entry.getKey())) {
Properties.Value value = entry.getValue();
String currentUrl = value.getText();
// Prefer wrapperUri specified directly in the recipe over other options
// If that isn't set, prefer the existing artifact repository URL over changing to services.gradle.org
if(wrapperUri != null) {
String effectiveWrapperUri = formatUriForPropertiesFile(wrapperUri
.replace("${version}", gradleWrapper.getVersion())
.replace("${distribution}", distribution == null ? "bin" : distribution));
return entry.withValue(value.withText(effectiveWrapperUri));
} else if(currentUrl.startsWith("https\\://services.gradle.org/distributions/")) {
return entry.withValue(value.withText(gradleWrapper.getPropertiesFormattedUrl()));
} else {
String gradleServicesDistributionUrl = gradleWrapper.getDistributionUrl();
String newDistributionFile = gradleServicesDistributionUrl.substring(gradleServicesDistributionUrl.lastIndexOf('/') + 1);
String repositoryUrlPrefix = currentUrl.substring(0, currentUrl.lastIndexOf('/'));
return entry.withValue(value.withText(repositoryUrlPrefix + "/" + newDistributionFile));
}
}
if (DISTRIBUTION_SHA_256_SUM_KEY.equals(entry.getKey())) {
return entry.withValue(entry.getValue().withText(gradleWrapper.getDistributionChecksum().getHexValue()));
}
return entry;
}
}
} </s> |
<s>[INST] <<SYS>> You are an assistant to create OpenRewrite recipes by providing the Java source code for an OpenRewrite recipe that implements the user's requirements. <</SYS>> Create an OpenRewrite recipes that fulfills the following requirement: Use `String` notation for Gradle dependency declarations [/INST] /*
* Copyright 2021 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite.gradle;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Preconditions;
import org.openrewrite.Recipe;
import org.openrewrite.TreeVisitor;
import org.openrewrite.groovy.GroovyVisitor;
import org.openrewrite.groovy.tree.G;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.java.MethodMatcher;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.java.tree.Space;
import org.openrewrite.marker.Markers;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.openrewrite.Tree.randomId;
public class DependencyUseStringNotation extends Recipe {
@Override
public String getDisplayName() {
return "Use `String` notation for Gradle dependency declarations";
}
@Override
public String getDescription() {
return "In Gradle, dependencies can be expressed as a `String` like `\"groupId:artifactId:version\"`, " +
"or equivalently as a `Map` like `group: 'groupId', name: 'artifactId', version: 'version'`. " +
"This recipe replaces dependencies represented as `Maps` with an equivalent dependency represented as a `String`.";
}
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
final MethodMatcher dependencyDsl = new MethodMatcher("DependencyHandlerSpec *(..)");
return Preconditions.check(new IsBuildGradle<>(), new GroovyVisitor<ExecutionContext>() {
@Override
public J visitMethodInvocation(J.MethodInvocation method, ExecutionContext ctx) {
J.MethodInvocation m = (J.MethodInvocation) super.visitMethodInvocation(method, ctx);
if (!dependencyDsl.matches(m)) {
return m;
}
if (m.getArguments().isEmpty()) {
return m;
}
Map<String, Expression> mapNotation = new HashMap<>();
if (m.getArguments().get(0) instanceof G.MapLiteral) {
G.MapLiteral arg = (G.MapLiteral) m.getArguments().get(0);
for (G.MapEntry entry : arg.getElements()) {
if (entry.getKey() instanceof J.Literal) {
J.Literal key = (J.Literal) entry.getKey();
if (key.getType() == JavaType.Primitive.String) {
mapNotation.put((String) key.getValue(), entry.getValue());
}
}
}
J.Literal stringNotation = toLiteral(arg.getPrefix(), arg.getMarkers(), mapNotation);
if (stringNotation == null) {
return m;
}
Expression lastArg = m.getArguments().get(m.getArguments().size() - 1);
if (lastArg instanceof J.Lambda) {
m = m.withArguments(Arrays.asList(stringNotation, lastArg));
} else {
m = m.withArguments(Collections.singletonList(stringNotation));
}
} else if (m.getArguments().get(0) instanceof G.MapEntry) {
G.MapEntry firstEntry = (G.MapEntry) m.getArguments().get(0);
Space prefix = firstEntry.getPrefix();
Markers markers = firstEntry.getMarkers();
for (Expression e : m.getArguments()) {
if (e instanceof G.MapEntry) {
G.MapEntry entry = (G.MapEntry) e;
if (entry.getKey() instanceof J.Literal) {
J.Literal key = (J.Literal) entry.getKey();
if (key.getType() == JavaType.Primitive.String) {
mapNotation.put((String) key.getValue(), entry.getValue());
}
}
}
}
J.Literal stringNotation = toLiteral(prefix, markers, mapNotation);
if (stringNotation == null) {
return m;
}
Expression lastArg = m.getArguments().get(m.getArguments().size() - 1);
if (lastArg instanceof J.Lambda) {
m = m.withArguments(Arrays.asList(stringNotation, lastArg));
} else {
m = m.withArguments(Collections.singletonList(stringNotation));
}
}
return m;
}
@Nullable
private J.Literal toLiteral(Space prefix, Markers markers, Map<String, Expression> mapNotation) {
if (mapNotation.containsKey("group") && mapNotation.containsKey("name")) {
String stringNotation = "";
String group = coerceToStringNotation(mapNotation.get("group"));
if (group != null) {
stringNotation += group;
}
String name = coerceToStringNotation(mapNotation.get("name"));
if (name != null) {
stringNotation += ":" + name;
}
String version = coerceToStringNotation(mapNotation.get("version"));
if (version != null) {
stringNotation += ":" + version;
}
return new J.Literal(randomId(), prefix, markers, stringNotation, "\"" + stringNotation + "\"", Collections.emptyList(), JavaType.Primitive.String);
}
return null;
}
@Nullable
private String coerceToStringNotation(Expression expression) {
if (expression instanceof J.Literal) {
return (String) ((J.Literal) expression).getValue();
} else if (expression instanceof J.Identifier) {
return "$" + ((J.Identifier) expression).getSimpleName();
} else if (expression instanceof G.GString) {
List<J> str = ((G.GString) expression).getStrings();
StringBuilder sb = new StringBuilder();
for (J valuePart : str) {
if (valuePart instanceof Expression) {
sb.append(coerceToStringNotation((Expression) valuePart));
} else if (valuePart instanceof G.GString.Value) {
J tree = ((G.GString.Value) valuePart).getTree();
if (tree instanceof Expression) {
sb.append(coerceToStringNotation((Expression) tree));
}
//Can it be something else? If so, what?
}
}
return sb.toString();
}
return null;
}
});
}
} </s> |
<s>[INST] <<SYS>> You are an assistant to create OpenRewrite recipes by providing the Java source code for an OpenRewrite recipe that implements the user's requirements. <</SYS>> Create an OpenRewrite recipes that fulfills the following requirement: Add a property to the `gradle.properties` file. [/INST] /*
* Copyright 2022 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite.gradle;
import lombok.EqualsAndHashCode;
import lombok.Value;
import org.openrewrite.*;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.properties.ChangePropertyValue;
import org.openrewrite.properties.PropertiesParser;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.Collections;
import java.util.stream.Collectors;
import static java.util.Collections.singletonList;
import static java.util.Objects.requireNonNull;
@Value
@EqualsAndHashCode(callSuper = false)
public class AddProperty extends ScanningRecipe<AddProperty.NeedsProperty> {
@Option(displayName = "Property name",
description = "The name of the property to add.",
example = "org.gradle.caching")
String key;
@Option(displayName = "Property value",
description = "The value of the property to add.")
String value;
@Option(displayName = "Overwrite if exists",
description = "If a property with the same key exists, overwrite.",
example = "Enable the Gradle build cache")
@Nullable
Boolean overwrite;
@Option(displayName = "File pattern",
description = "A glob expression that can be used to constrain which directories or source files should be searched. " +
"When not set, all source files are searched.",
example = "**/*.properties")
@Nullable
String filePattern;
@Override
public String getDisplayName() {
return "Add Gradle property";
}
@Override
public String getInstanceNameSuffix() {
return String.format("`%s=%s`", key, value);
}
@Override
public String getDescription() {
return "Add a property to the `gradle.properties` file.";
}
public static class NeedsProperty {
boolean isGradleProject;
boolean hasGradleProperties;
}
@Override
public NeedsProperty getInitialValue(ExecutionContext ctx) {
return new NeedsProperty();
}
@Override
public TreeVisitor<?, ExecutionContext> getScanner(NeedsProperty acc) {
return new TreeVisitor<Tree, ExecutionContext>() {
@Override
public Tree visit(@Nullable Tree tree, ExecutionContext ctx) {
SourceFile sourceFile = (SourceFile) requireNonNull(tree);
if (filePattern != null) {
if (new FindSourceFiles(filePattern).getVisitor().visitNonNull(tree, ctx) != tree &&
sourceFile.getSourcePath().endsWith("gradle.properties")) {
acc.hasGradleProperties = true;
}
} else if (sourceFile.getSourcePath().endsWith("gradle.properties")) {
acc.hasGradleProperties = true;
}
if (IsBuildGradle.matches(sourceFile.getSourcePath())) {
acc.isGradleProject = true;
}
return tree;
}
};
}
@Override
public Collection<? extends SourceFile> generate(NeedsProperty acc, ExecutionContext ctx) {
if (!acc.hasGradleProperties) {
return PropertiesParser.builder().build()
.parseInputs(singletonList(Parser.Input.fromString(Paths.get("gradle.properties"),
key + "=" + value)), null, ctx)
.collect(Collectors.toList());
}
return Collections.emptyList();
}
@Override
public TreeVisitor<?, ExecutionContext> getVisitor(NeedsProperty acc) {
return Preconditions.check(acc.isGradleProject && acc.hasGradleProperties, new TreeVisitor<Tree, ExecutionContext>() {
@Override
public Tree visit(@Nullable Tree tree, ExecutionContext ctx) {
SourceFile sourceFile = (SourceFile) requireNonNull(tree);
if (filePattern != null) {
if (new FindSourceFiles(filePattern).getVisitor().visitNonNull(sourceFile, ctx) != sourceFile &&
sourceFile.getSourcePath().endsWith("gradle.properties")) {
Tree t = !Boolean.TRUE.equals(overwrite) ?
sourceFile :
new ChangePropertyValue(key, value, null, false, null)
.getVisitor().visitNonNull(sourceFile, ctx);
return new org.openrewrite.properties.AddProperty(key, value, null, null)
.getVisitor()
.visitNonNull(t, ctx);
}
} else if (sourceFile.getSourcePath().endsWith("gradle.properties")) {
Tree t = !Boolean.TRUE.equals(overwrite) ?
sourceFile :
new ChangePropertyValue(key, value, null, false, null)
.getVisitor().visitNonNull(sourceFile, ctx);
return new org.openrewrite.properties.AddProperty(key, value, null, null)
.getVisitor()
.visitNonNull(t, ctx);
}
return sourceFile;
}
});
}
} </s> |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
Use the Edit dataset card button to edit it.
- Downloads last month
- 0