Skip to content

Commit

Permalink
Extract Gradle Enterprise configuration (#291)
Browse files Browse the repository at this point in the history
This commit extracts the Gradle Enterprise configuration into
its own plugin, so that it can be applied on projects which
only need support for Gradle Enterprise, but not publishing.

The plugin id is `io.micronaut.build.internal.gradle-enterprise`
  • Loading branch information
melix authored Mar 16, 2022
1 parent 90eefa0 commit 564c279
Show file tree
Hide file tree
Showing 5 changed files with 200 additions and 106 deletions.
4 changes: 4 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,10 @@ gradlePlugin {
id = 'io.micronaut.build.internal.docs'
implementationClass = 'io.micronaut.build.MicronautDocsPlugin'
}
gradleEnterprise {
id = 'io.micronaut.build.internal.gradle-enterprise'
implementationClass = 'io.micronaut.build.MicronautGradleEnterprisePlugin'
}
sharedSettings {
id = 'io.micronaut.build.shared.settings'
implementationClass = 'io.micronaut.build.MicronautSharedSettingsPlugin'
Expand Down
31 changes: 31 additions & 0 deletions src/main/java/io/micronaut/build/MicronautBuildSettingsPlugin.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
* Copyright 2003-2021 the original author or authors.
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.micronaut.build;

import org.gradle.api.Plugin;
import org.gradle.api.initialization.Settings;

/**
* This plugin declares the Micronaut Build Settings extension.
*/
public class MicronautBuildSettingsPlugin implements Plugin<Settings> {

@Override
public void apply(Settings settings) {
settings.getExtensions().create("micronautBuild", MicronautBuildSettingsExtension.class);
}

}
122 changes: 122 additions & 0 deletions src/main/java/io/micronaut/build/MicronautGradleEnterprisePlugin.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
/*
* Copyright 2003-2021 the original author or authors.
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.micronaut.build;

import com.gradle.CommonCustomUserDataGradlePlugin;
import com.gradle.enterprise.gradleplugin.GradleEnterpriseExtension;
import com.gradle.enterprise.gradleplugin.GradleEnterprisePlugin;
import com.gradle.scan.plugin.BuildScanExtension;
import org.gradle.api.Plugin;
import org.gradle.api.initialization.Settings;
import org.gradle.api.invocation.Gradle;
import org.gradle.api.plugins.PluginManager;
import org.gradle.api.provider.Provider;
import org.gradle.api.provider.ProviderFactory;
import org.gradle.caching.configuration.BuildCacheConfiguration;
import org.gradle.caching.http.HttpBuildCache;
import org.nosphere.gradle.github.ActionsPlugin;

import java.lang.reflect.InvocationTargetException;

import static io.micronaut.build.ProviderUtils.envOrSystemProperty;

public class MicronautGradleEnterprisePlugin implements Plugin<Settings> {
@Override
public void apply(Settings settings) {
PluginManager pluginManager = settings.getPluginManager();
pluginManager.apply(MicronautBuildSettingsPlugin.class);
pluginManager.apply(GradleEnterprisePlugin.class);
pluginManager.apply(CommonCustomUserDataGradlePlugin.class);
GradleEnterpriseExtension ge = settings.getExtensions().getByType(GradleEnterpriseExtension.class);
MicronautBuildSettingsExtension micronautBuildSettingsExtension = settings.getExtensions().getByType(MicronautBuildSettingsExtension.class);
configureGradleEnterprise(settings, ge, micronautBuildSettingsExtension);
}

private void configureGradleEnterprise(Settings settings,
GradleEnterpriseExtension ge,
MicronautBuildSettingsExtension micronautBuildSettingsExtension) {
ProviderFactory providers = settings.getProviders();
Provider<Boolean> publishScanOnDemand = providers.gradleProperty("publishScanOnDemand")
.map(Boolean::parseBoolean)
.orElse(false);
boolean isCI = ProviderUtils.guessCI(providers);
configureBuildScansPublishing(ge, isCI, publishScanOnDemand);
settings.getGradle().projectsLoaded(MicronautGradleEnterprisePlugin::applyGitHubActionsPlugin);
if (providers.gradleProperty("org.gradle.caching").map(Boolean::parseBoolean).orElse(true).get()) {
settings.getGradle().settingsEvaluated(lateSettings -> {
BuildCacheConfiguration buildCache = settings.getBuildCache();
boolean localEnabled = micronautBuildSettingsExtension.getUseLocalCache().get();
boolean remoteEnabled = micronautBuildSettingsExtension.getUseRemoteCache().get();
boolean push = MicronautBuildSettingsExtension.booleanProvider(providers, "cachePush", isCI).get();
if (isCI) {
System.out.println("Build cache enabled push");
System.out.println(" Local " + (localEnabled ? " Y " : " N ") + " N/A");
System.out.println(" Remote " + (remoteEnabled ? " Y " : " N ") + " " + (push ? " Y" : " N"));
}
buildCache.getLocal().setEnabled(localEnabled);
if (remoteEnabled) {
buildCache.remote(HttpBuildCache.class, remote -> {
remote.setUrl("https://ge.micronaut.io/cache/");
remote.setEnabled(true);
if (push) {
String username = envOrSystemProperty(providers, "GRADLE_ENTERPRISE_CACHE_USERNAME", "gradleEnterpriseCacheUsername", "");
String password = envOrSystemProperty(providers, "GRADLE_ENTERPRISE_CACHE_PASSWORD", "gradleEnterpriseCachePassword", "");
if (!username.isEmpty() && !password.isEmpty()) {
remote.setPush(true);
remote.credentials(creds -> {
creds.setUsername(username);
creds.setPassword(password);
});
} else {
System.err.println("WARNING: No credentials for remote build cache, cannot configure push!");
}
}
});
}
});
}
}

private void configureBuildScansPublishing(GradleEnterpriseExtension ge, boolean isCI, Provider<Boolean> publishScanOnDemand) {
ge.setServer("https://ge.micronaut.io");
ge.buildScan(buildScan -> {
if (!publishScanOnDemand.get()) {
buildScan.publishAlways();
}
if (isCI) {
buildScan.setUploadInBackground(false);
} else {
publishIfAuthenticated(buildScan);
}
buildScan.capture(c ->
c.setTaskInputFiles(true)
);
});
}

private static void applyGitHubActionsPlugin(Gradle gradle) {
gradle.getRootProject().getPluginManager().apply(ActionsPlugin.class);
}

private static void publishIfAuthenticated(BuildScanExtension ext) {
try {
ext.getClass().getMethod("publishIfAuthenticated").invoke(ext);
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
System.err.println("Unable to set publish if authenticated on build scan extension");
}
}

}
111 changes: 5 additions & 106 deletions src/main/java/io/micronaut/build/MicronautSharedSettingsPlugin.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,6 @@
*/
package io.micronaut.build;

import com.gradle.CommonCustomUserDataGradlePlugin;
import com.gradle.enterprise.gradleplugin.GradleEnterpriseExtension;
import com.gradle.enterprise.gradleplugin.GradleEnterprisePlugin;
import com.gradle.scan.plugin.BuildScanExtension;
import io.github.gradlenexus.publishplugin.NexusPublishExtension;
import org.gradle.api.InvalidUserCodeException;
import org.gradle.api.Plugin;
Expand All @@ -28,27 +24,22 @@
import org.gradle.api.plugins.PluginManager;
import org.gradle.api.provider.Provider;
import org.gradle.api.provider.ProviderFactory;
import org.gradle.caching.configuration.BuildCacheConfiguration;
import org.gradle.caching.http.HttpBuildCache;
import org.nosphere.gradle.github.ActionsPlugin;

import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

import static io.micronaut.build.ProviderUtils.envOrSystemProperty;

public class MicronautSharedSettingsPlugin implements Plugin<Settings> {
public static final String NEXUS_STAGING_PROFILE_ID = "11bd7bc41716aa";

@Override
public void apply(Settings settings) {
PluginManager pluginManager = settings.getPluginManager();
pluginManager.apply(GradleEnterprisePlugin.class);
pluginManager.apply(CommonCustomUserDataGradlePlugin.class);
GradleEnterpriseExtension ge = settings.getExtensions().getByType(GradleEnterpriseExtension.class);
MicronautBuildSettingsExtension micronautBuildSettingsExtension = settings.getExtensions().create("micronautBuild", MicronautBuildSettingsExtension.class);
configureGradleEnterprise(settings, ge, micronautBuildSettingsExtension);
pluginManager.apply(MicronautBuildSettingsPlugin.class);
pluginManager.apply(MicronautGradleEnterprisePlugin.class);
applyPublishingPlugin(settings);
assertUniqueProjectNames(settings);
}
Expand Down Expand Up @@ -96,7 +87,7 @@ private void configureNexusPublishing(Gradle gradle, String ossUser, String ossP
nexusPublish.getRepositoryDescription().set("" + rootProject.getGroup() + ":" + rootProject.getName() + ":" + version);
nexusPublish.getUseStaging().convention(!version.endsWith("-SNAPSHOT"));
nexusPublish.repositories(repos -> repos.create("sonatype", repo -> {
repo.getAllowInsecureProtocol().convention(rootProject.getProviders().systemProperty("allowInsecurePublishing").forUseAtConfigurationTime().map(Boolean::parseBoolean).orElse(false));
repo.getAllowInsecureProtocol().convention(rootProject.getProviders().systemProperty("allowInsecurePublishing").map(Boolean::parseBoolean).orElse(false));
repo.getUsername().set(ossUser);
repo.getPassword().set(ossPass);
repo.getNexusUrl().set(uri(envOrSystemProperty(rootProject.getProviders(), "SONATYPE_REPO_URI", "sonatypeRepoUri", "https://s01.oss.sonatype.org/service/local/")));
Expand All @@ -113,98 +104,6 @@ private static URI uri(String uri) {
}
}

private static String envOrSystemProperty(ProviderFactory providers, String envName, String propertyName, String defaultValue) {
return providers.environmentVariable(envName)
.forUseAtConfigurationTime()
.orElse(providers.gradleProperty(propertyName).forUseAtConfigurationTime())
.getOrElse(defaultValue);
}

private void configureGradleEnterprise(Settings settings,
GradleEnterpriseExtension ge,
MicronautBuildSettingsExtension micronautBuildSettingsExtension) {
ProviderFactory providers = settings.getProviders();
Provider<Boolean> publishScanOnDemand = providers.gradleProperty("publishScanOnDemand")
.forUseAtConfigurationTime()
.map(Boolean::parseBoolean)
.orElse(false);
boolean isCI = guessCI(providers);
configureBuildScansPublishing(ge, isCI, publishScanOnDemand);
settings.getGradle().projectsLoaded(MicronautSharedSettingsPlugin::applyGitHubActionsPlugin);
if (providers.gradleProperty("org.gradle.caching").forUseAtConfigurationTime().map(Boolean::parseBoolean).orElse(true).get()) {
settings.getGradle().settingsEvaluated(lateSettings -> {
BuildCacheConfiguration buildCache = settings.getBuildCache();
boolean localEnabled = micronautBuildSettingsExtension.getUseLocalCache().get();
boolean remoteEnabled = micronautBuildSettingsExtension.getUseRemoteCache().get();
boolean push = MicronautBuildSettingsExtension.booleanProvider(providers, "cachePush", isCI).get();
if (isCI) {
System.out.println("Build cache enabled push");
System.out.println(" Local " + (localEnabled ? " Y " : " N ") + " N/A");
System.out.println(" Remote " + (remoteEnabled ? " Y " : " N ") + " " + (push ? " Y" : " N"));
}
buildCache.getLocal().setEnabled(localEnabled);
if (remoteEnabled) {
buildCache.remote(HttpBuildCache.class, remote -> {
remote.setUrl("https://ge.micronaut.io/cache/");
remote.setEnabled(true);
if (push) {
String username = envOrSystemProperty(providers, "GRADLE_ENTERPRISE_CACHE_USERNAME", "gradleEnterpriseCacheUsername", "");
String password = envOrSystemProperty(providers, "GRADLE_ENTERPRISE_CACHE_PASSWORD", "gradleEnterpriseCachePassword", "");
if (!username.isEmpty() && !password.isEmpty()) {
remote.setPush(true);
remote.credentials(creds -> {
creds.setUsername(username);
creds.setPassword(password);
});
} else {
System.err.println("WARNING: No credentials for remote build cache, cannot configure push!");
}
}
});
}
});
}
}

private void configureBuildScansPublishing(GradleEnterpriseExtension ge, boolean isCI, Provider<Boolean> publishScanOnDemand) {
ge.setServer("https://ge.micronaut.io");
ge.buildScan(buildScan -> {
if (!publishScanOnDemand.get()) {
buildScan.publishAlways();
}
if (isCI) {
buildScan.setUploadInBackground(false);
} else {
publishIfAuthenticated(buildScan);
}
buildScan.capture(c ->
c.setTaskInputFiles(true)
);
});
}

private static void applyGitHubActionsPlugin(Gradle gradle) {
gradle.getRootProject().getPluginManager().apply(ActionsPlugin.class);
}

private static void publishIfAuthenticated(BuildScanExtension ext) {
try {
ext.getClass().getMethod("publishIfAuthenticated").invoke(ext);
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
System.err.println("Unable to set publish if authenticated on build scan extension");
}
}

private static boolean guessCI(ProviderFactory providers) {
return providers
.environmentVariable("CI").forUseAtConfigurationTime()
.flatMap(s -> // Not all workflows may have the enterprise key set
providers.environmentVariable("GRADLE_ENTERPRISE_ACCESS_KEY")
.forUseAtConfigurationTime()
.map(env -> true)
.orElse(false)
)
.orElse(false)
.get();
}
}
38 changes: 38 additions & 0 deletions src/main/java/io/micronaut/build/ProviderUtils.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
* Copyright 2003-2021 the original author or authors.
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.micronaut.build;

import org.gradle.api.provider.ProviderFactory;

class ProviderUtils {
static boolean guessCI(ProviderFactory providers) {
return providers
.environmentVariable("CI")
.flatMap(s -> // Not all workflows may have the enterprise key set
providers.environmentVariable("GRADLE_ENTERPRISE_ACCESS_KEY")
.map(env -> true)
.orElse(false)
)
.orElse(false)
.get();
}

static String envOrSystemProperty(ProviderFactory providers, String envName, String propertyName, String defaultValue) {
return providers.environmentVariable(envName)
.orElse(providers.gradleProperty(propertyName))
.getOrElse(defaultValue);
}
}

0 comments on commit 564c279

Please sign in to comment.