Skip to content

Commit

Permalink
Allow a custom init script to be provided for operation within enviro…
Browse files Browse the repository at this point in the history
…nments where the default repositories are inaccessible.
  • Loading branch information
sambsnyd committed Apr 24, 2024
1 parent 455288d commit 945f6d5
Show file tree
Hide file tree
Showing 4 changed files with 115 additions and 14 deletions.
Expand Up @@ -47,7 +47,16 @@ public static UncheckedConsumer<List<SourceFile>> withToolingApi(URI distributio
return withToolingApi(GradleWrapper.create(distributionUrl, new InMemoryExecutionContext()));
}

@SuppressWarnings("unused")
public static UncheckedConsumer<List<SourceFile>> withToolingApi(URI distributionUrl, String initScriptContents) {
return withToolingApi(GradleWrapper.create(distributionUrl, new InMemoryExecutionContext()), initScriptContents);
}

public static UncheckedConsumer<List<SourceFile>> withToolingApi(@Nullable GradleWrapper gradleWrapper) {
return withToolingApi(gradleWrapper, null);
}

public static UncheckedConsumer<List<SourceFile>> withToolingApi(@Nullable GradleWrapper gradleWrapper, @Nullable String initScriptContents) {
return sourceFiles -> {
try {
Path tempDirectory = Files.createTempDirectory("project");
Expand Down Expand Up @@ -103,14 +112,14 @@ public static UncheckedConsumer<List<SourceFile>> withToolingApi(@Nullable Gradl
SourceFile sourceFile = sourceFiles.get(i);
if (sourceFile.getSourcePath().toString().endsWith(".gradle")) {
if (sourceFile.getSourcePath().endsWith("settings.gradle")) {
OpenRewriteModel model = OpenRewriteModelBuilder.forProjectDirectory(tempDirectory.resolve(sourceFile.getSourcePath()).getParent().toFile(), null);
OpenRewriteModel model = OpenRewriteModelBuilder.forProjectDirectory(tempDirectory.resolve(sourceFile.getSourcePath()).getParent().toFile(), null, initScriptContents);
org.openrewrite.gradle.toolingapi.GradleSettings rawSettings = model.gradleSettings();
if (rawSettings != null) {
GradleSettings gradleSettings = org.openrewrite.gradle.toolingapi.GradleSettings. toMarker(rawSettings);
sourceFiles.set(i, sourceFile.withMarkers(sourceFile.getMarkers().add(gradleSettings)));
}
} else {
OpenRewriteModel model = OpenRewriteModelBuilder.forProjectDirectory(projectDir.toFile(), tempDirectory.resolve(sourceFile.getSourcePath()).toFile());
OpenRewriteModel model = OpenRewriteModelBuilder.forProjectDirectory(projectDir.toFile(), tempDirectory.resolve(sourceFile.getSourcePath()).toFile(), initScriptContents);
GradleProject gradleProject = org.openrewrite.gradle.toolingapi.GradleProject.toMarker(model.gradleProject());
sourceFiles.set(i, sourceFile.withMarkers(sourceFile.getMarkers().add(gradleProject)));
}
Expand Down Expand Up @@ -139,7 +148,7 @@ public static UncheckedConsumer<List<SourceFile>> withToolingApi(String version)
}

public static UncheckedConsumer<List<SourceFile>> withToolingApi() {
return withToolingApi(null, null);
return withToolingApi((GradleWrapper) null, null);
}

private static void deleteDirectory(File directoryToBeDeleted) {
Expand Down
Expand Up @@ -27,12 +27,53 @@
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;

@SuppressWarnings("JavadocLinkAsPlainText")
public class OpenRewriteModelBuilder {

/**
* Build an OpenRewriteModel for a project directory, using the default Gradle init script bundled within this jar.
* The included init script accesses public artifact repositories (Maven Central, Nexus Snapshots) to be able to
* download rewrite dependencies, so public repositories must be accessible for this to work.
*/
public static OpenRewriteModel forProjectDirectory(File projectDir, @Nullable File buildFile) {
return forProjectDirectory(projectDir, buildFile, null);
}

/**
* Build an OpenRewriteModel for a project directory, using the init script contents passed to this function.
* When Maven Central / Nexus Snapshots are inaccessible this overload can be used with an alternate Groovy init script
* which applies the ToolingApiOpenRewriteModelPlugin to all projects.
* Example init script:
* <pre>
* initscript {
* repositories {
* mavenLocal()
* maven{ url = uri("https://oss.sonatype.org/content/repositories/snapshots") }
* mavenCentral()
* }
*
* configurations.all {
* resolutionStrategy{
* cacheChangingModulesFor 0, 'seconds'
* cacheDynamicVersionsFor 0, 'seconds'
* }
* }
*
* dependencies {
* classpath 'org.openrewrite.gradle.tooling:plugin:latest.integration'
* classpath 'org.openrewrite:rewrite-maven:latest.integration'
* }
* }
*
* allprojects {
* apply plugin: org.openrewrite.gradle.toolingapi.ToolingApiOpenRewriteModelPlugin
* }
* </pre>
*/
public static OpenRewriteModel forProjectDirectory(File projectDir, @Nullable File buildFile, @Nullable String initScript) {
DefaultGradleConnector connector = (DefaultGradleConnector)GradleConnector.newConnector();
if (Files.exists(projectDir.toPath().resolve("gradle/wrapper/gradle-wrapper.properties"))) {
connector.useBuildDistribution();
Expand All @@ -50,11 +91,17 @@ public static OpenRewriteModel forProjectDirectory(File projectDir, @Nullable Fi
arguments.add(init.toString());
try (ProjectConnection connection = connector.connect()) {
ModelBuilder<OpenRewriteModel> customModelBuilder = connection.model(OpenRewriteModel.class);
try (InputStream is = OpenRewriteModel.class.getResourceAsStream("/init.gradle")) {
if (is == null) {
throw new IllegalStateException("Expected to find init.gradle on the classpath");
try {
if(initScript == null) {
try (InputStream is = OpenRewriteModel.class.getResourceAsStream("/init.gradle")) {
if (is == null) {
throw new IllegalStateException("Expected to find init.gradle on the classpath");
}
Files.copy(is, init);
}
} else {
Files.write(init, initScript.getBytes());
}
Files.copy(is, init, StandardCopyOption.REPLACE_EXISTING);
customModelBuilder.withArguments(arguments);
return customModelBuilder.get();
} catch (IOException e) {
Expand Down
12 changes: 6 additions & 6 deletions model/src/main/resources/init.gradle
Expand Up @@ -13,26 +13,26 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
initscript{
repositories{
initscript {
repositories {
mavenLocal()
maven{ url = uri("https://oss.sonatype.org/content/repositories/snapshots") }
mavenCentral()
}

configurations.all{
resolutionStrategy{
configurations.all {
resolutionStrategy {
cacheChangingModulesFor 0, 'seconds'
cacheDynamicVersionsFor 0, 'seconds'
}
}

dependencies{
dependencies {
classpath 'org.openrewrite.gradle.tooling:plugin:latest.integration'
classpath 'org.openrewrite:rewrite-maven:latest.integration'
}
}

allprojects{
allprojects {
apply plugin: org.openrewrite.gradle.toolingapi.ToolingApiOpenRewriteModelPlugin
}
Expand Up @@ -17,6 +17,7 @@

import org.junit.jupiter.api.Test;
import org.openrewrite.gradle.marker.GradleProject;
import org.openrewrite.gradle.util.GradleWrapper;
import org.openrewrite.test.RewriteTest;

import java.net.URI;
Expand Down Expand Up @@ -57,4 +58,48 @@ void withCustomDistributionUri() {
)
);
}

@Test
void customInitScript() {
//language=groovy
String alternateInit = """
initscript{
repositories{
mavenLocal()
maven{ url = uri("https://oss.sonatype.org/content/repositories/snapshots") }
mavenCentral()
}
configurations.all{
resolutionStrategy{
cacheChangingModulesFor 0, 'seconds'
cacheDynamicVersionsFor 0, 'seconds'
}
}
dependencies{
classpath 'org.openrewrite.gradle.tooling:plugin:latest.integration'
classpath 'org.openrewrite:rewrite-maven:latest.integration'
}
}
allprojects{
apply plugin: org.openrewrite.gradle.toolingapi.ToolingApiOpenRewriteModelPlugin
}
""";
GradleWrapper gradleWrapper = GradleWrapper.create(URI.create("https://services.gradle.org/distributions/gradle-8.6-bin.zip"), null);
rewriteRun(
spec -> spec.beforeRecipe(Assertions.withToolingApi(gradleWrapper, alternateInit)),
//language=groovy
buildGradle(
"""
plugins {
id 'java'
}
""",
spec -> spec.afterRecipe(cu -> assertThat(cu.getMarkers().findFirst(GradleProject.class)).isPresent())
)
);
}
}

0 comments on commit 945f6d5

Please sign in to comment.