Initial commit
Some checks failed
CI-integ-test-full / caching-integ-tests (push) Failing after 32s
CI-integ-test-full / other-integ-tests (push) Failing after 29m15s
Update Wrapper checksums file / Update checksums (push) Failing after 3m7s
CI-codeql / Analyze (javascript-typescript) (push) Failing after 10m7s

This commit is contained in:
2024-09-25 17:07:42 +02:00
commit b3863e10a2
202 changed files with 944555 additions and 0 deletions

2
sources/test/init-scripts/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
build
.gradle

View File

@@ -0,0 +1,28 @@
plugins {
id 'groovy'
}
java {
toolchain {
languageVersion = JavaLanguageVersion.of(8)
}
}
repositories {
mavenCentral()
}
dependencies {
testImplementation gradleTestKit()
testImplementation 'org.spockframework:spock-core:2.3-groovy-3.0'
testImplementation('org.spockframework:spock-junit4:2.3-groovy-3.0')
testImplementation ('io.ratpack:ratpack-groovy-test:1.9.0') {
exclude group: 'org.codehaus.groovy', module: 'groovy-all'
}
testImplementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-smile:2.17.2'
}
test {
useJUnitPlatform()
}

Binary file not shown.

View File

@@ -0,0 +1,8 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionSha256Sum=5b9c5eb3f9fc2c94abaea57d90bd78747ca117ddbbf96c859d3741181a12bf2a
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

252
sources/test/init-scripts/gradlew vendored Executable file
View File

@@ -0,0 +1,252 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original 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.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

94
sources/test/init-scripts/gradlew.bat vendored Normal file
View File

@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -0,0 +1,13 @@
plugins {
id "com.gradle.develocity" version "3.18.1"
id "com.gradle.common-custom-user-data-gradle-plugin" version "2.0.1"
}
develocity {
buildScan {
termsOfUseUrl = "https://gradle.com/help/legal-terms-of-use"
termsOfUseAgree = "yes"
uploadInBackground = false
}
}
rootProject.name = 'test-init-scripts'

View File

@@ -0,0 +1,286 @@
package com.gradle.gradlebuildaction
import com.fasterxml.jackson.core.JsonFactory
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.dataformat.smile.SmileFactory
import org.gradle.testkit.runner.BuildResult
import org.gradle.testkit.runner.GradleRunner
import org.gradle.testkit.runner.internal.DefaultGradleRunner
import org.gradle.util.GradleVersion
import ratpack.groovy.test.embed.GroovyEmbeddedApp
import spock.lang.AutoCleanup
import spock.lang.Specification
import spock.lang.TempDir
import java.nio.file.Files
import java.util.zip.GZIPOutputStream
class BaseInitScriptTest extends Specification {
static final String DEVELOCITY_PLUGIN_VERSION = '3.18.1'
static final String CCUD_PLUGIN_VERSION = '2.0.1'
static final TestGradleVersion GRADLE_3_X = new TestGradleVersion(GradleVersion.version('3.5.1'), 7, 9)
static final TestGradleVersion GRADLE_4_X = new TestGradleVersion(GradleVersion.version('4.10.3'), 7, 10)
static final TestGradleVersion GRADLE_5_X = new TestGradleVersion(GradleVersion.version('5.6.4'), 8, 12)
static final TestGradleVersion GRADLE_6_0 = new TestGradleVersion(GradleVersion.version('6.0.1'), 8, 13)
static final TestGradleVersion GRADLE_6_NO_BUILD_SERVICE = new TestGradleVersion(GradleVersion.version('6.5.1'), 8, 14)
static final TestGradleVersion GRADLE_6_X = new TestGradleVersion(GradleVersion.version('6.9.4'), 8, 15)
static final TestGradleVersion GRADLE_7_1 = new TestGradleVersion(GradleVersion.version('7.1.1'), 8, 16)
static final TestGradleVersion GRADLE_7_X = new TestGradleVersion(GradleVersion.version('7.6.2'), 8, 19)
static final TestGradleVersion GRADLE_8_0 = new TestGradleVersion(GradleVersion.version('8.0.2'), 8, 19)
static final TestGradleVersion GRADLE_8_X = new TestGradleVersion(GradleVersion.version('8.10'), 8, 23)
static final List<TestGradleVersion> ALL_VERSIONS = [
GRADLE_3_X, // First version where TestKit supports environment variables
GRADLE_4_X,
GRADLE_5_X,
GRADLE_6_0,
GRADLE_6_NO_BUILD_SERVICE, // Last version without build service support
GRADLE_6_X,
GRADLE_7_1,
GRADLE_7_X,
GRADLE_8_0,
GRADLE_8_X,
]
static final List<TestGradleVersion> CONFIGURATION_CACHE_VERSIONS =
[GRADLE_7_X, GRADLE_8_0, GRADLE_8_X]
static final List<TestGradleVersion> SETTINGS_PLUGIN_VERSIONS =
[GRADLE_6_X, GRADLE_7_1, GRADLE_7_X, GRADLE_8_0, GRADLE_8_X]
static final String PUBLIC_BUILD_SCAN_ID = 'i2wepy2gr7ovw'
static final String DEFAULT_SCAN_UPLOAD_TOKEN = 'scan-upload-token'
static final String ROOT_PROJECT_NAME = 'test-init-script'
boolean failScanUpload = false
File settingsFile
File buildFile
boolean allowDevelocityDeprecationWarning = false
@TempDir
File testProjectDir
@AutoCleanup
def mockScansServer = GroovyEmbeddedApp.of {
def jsonWriter = new ObjectMapper(new JsonFactory()).writer()
def smileWriter = new ObjectMapper(new SmileFactory()).writer()
handlers {
post('in/:gradleVersion/:pluginVersion') {
if (failScanUpload) {
context.response.status(401).send()
return
}
def scanUrlString = "${mockScansServer.address}s/$PUBLIC_BUILD_SCAN_ID"
def body = [
id : PUBLIC_BUILD_SCAN_ID,
scanUrl: scanUrlString.toString(),
]
def out = new ByteArrayOutputStream()
new GZIPOutputStream(out).withStream { smileWriter.writeValue(it, body) }
context.response
.contentType('application/vnd.gradle.scan-ack')
.send(out.toByteArray())
}
prefix('scans/publish') {
post('gradle/:pluginVersion/token') {
if (failScanUpload) {
context.response.status(401).send()
return
}
def pluginVersion = context.pathTokens.pluginVersion
def scanUrlString = "${mockScansServer.address}s/$PUBLIC_BUILD_SCAN_ID"
def body = [
id : PUBLIC_BUILD_SCAN_ID,
scanUrl : scanUrlString.toString(),
scanUploadUrl : "${mockScansServer.address.toString()}scans/publish/gradle/$pluginVersion/upload".toString(),
scanUploadToken: DEFAULT_SCAN_UPLOAD_TOKEN
]
context.response
.contentType('application/vnd.gradle.scan-ack+json')
.send(jsonWriter.writeValueAsBytes(body))
}
post('gradle/:pluginVersion/upload') {
if (failScanUpload) {
context.response.status(401).send()
return
}
context.request.getBody(1024 * 1024 * 10).then {
context.response
.contentType('application/vnd.gradle.scan-upload-ack+json')
.send()
}
}
notFound()
}
}
}
def setup() {
settingsFile = new File(testProjectDir, 'settings.gradle')
buildFile = new File(testProjectDir, 'build.gradle')
File srcInitScriptsDir = new File("../../src/resources/init-scripts")
File targetInitScriptsDir = new File(testProjectDir, "initScripts")
targetInitScriptsDir.mkdirs()
for (File srcInitScript : srcInitScriptsDir.listFiles()) {
File targetInitScript = new File(targetInitScriptsDir, srcInitScript.name)
Files.copy(srcInitScript.toPath(), targetInitScript.toPath())
}
settingsFile << "rootProject.name = '${ROOT_PROJECT_NAME}'\n"
buildFile << ''
}
def declareDevelocityPluginApplication(GradleVersion gradleVersion, URI serverUrl = mockScansServer.address) {
settingsFile.text = maybeAddPluginsToSettings(gradleVersion, false, null, serverUrl) + settingsFile.text
buildFile.text = maybeAddPluginsToRootProject(gradleVersion, false, null, serverUrl) + buildFile.text
}
def declareLegacyGradleEnterprisePluginApplication(GradleVersion gradleVersion, URI serverUrl = mockScansServer.address) {
settingsFile.text = maybeAddPluginsToSettings(gradleVersion, true, null, serverUrl) + settingsFile.text
buildFile.text = maybeAddPluginsToRootProject(gradleVersion, true, null, serverUrl) + buildFile.text
}
def declareDevelocityPluginAndCcudPluginApplication(GradleVersion gradleVersion, URI serverUrl = mockScansServer.address) {
settingsFile.text = maybeAddPluginsToSettings(gradleVersion, false, CCUD_PLUGIN_VERSION, serverUrl) + settingsFile.text
buildFile.text = maybeAddPluginsToRootProject(gradleVersion, false, CCUD_PLUGIN_VERSION, serverUrl) + buildFile.text
}
String maybeAddPluginsToSettings(GradleVersion gradleVersion, boolean legacy, String ccudPluginVersion, URI serverUri) {
if (gradleVersion < GradleVersion.version('6.0')) {
'' // applied in build.gradle
} else {
configuredPlugin(gradleVersion, legacy, ccudPluginVersion, serverUri)
}
}
String maybeAddPluginsToRootProject(GradleVersion gradleVersion, boolean legacy, String ccudPluginVersion, URI serverUrl) {
if (gradleVersion < GradleVersion.version('5.0')) {
"""
plugins {
id 'com.gradle.build-scan' version '1.16'
${ccudPluginVersion ? "id 'com.gradle.common-custom-user-data-gradle-plugin' version '$ccudPluginVersion'" : ""}
}
buildScan {
server = '$serverUrl'
publishAlways()
}
"""
} else if (gradleVersion < GradleVersion.version('6.0')) {
configuredPlugin(gradleVersion, legacy, ccudPluginVersion, serverUrl)
} else {
'' // applied in settings.gradle
}
}
String configuredPlugin(GradleVersion gradleVersion, boolean legacy, String ccudPluginVersion, URI serverUri) {
def pluginId = legacy
? (gradleVersion < GradleVersion.version('6.0') ? 'com.gradle.build-scan' : 'com.gradle.enterprise')
: 'com.gradle.develocity'
def pluginVersion = legacy ? "3.16.2" : DEVELOCITY_PLUGIN_VERSION
def configBlock = legacy ? 'gradleEnterprise' : 'develocity'
"""
plugins {
id '$pluginId' version '$pluginVersion'
${ccudPluginVersion ? "id 'com.gradle.common-custom-user-data-gradle-plugin' version '$ccudPluginVersion'" : ""}
}
$configBlock {
server = '$serverUri'
${legacy ? "buildScan { publishAlways() }" : ""}
}
"""
}
def addFailingTaskToBuild() {
buildFile << '''
task expectFailure {
doLast {
throw new RuntimeException("Expected to fail")
}
}
'''
}
BuildResult run(List<String> args, String initScript, GradleVersion gradleVersion = GradleVersion.current(), List<String> jvmArgs = [], Map<String, String> envVars = [:]) {
def result = createRunner(args, initScript, gradleVersion, jvmArgs, envVars).build()
assertNoDeprecationWarning(result)
}
BuildResult runAndFail(List<String> args, String initScript, GradleVersion gradleVersion = GradleVersion.current(), List<String> jvmArgs = [], Map<String, String> envVars = [:]) {
def result = createRunner(args, initScript, gradleVersion, jvmArgs, envVars).buildAndFail()
assertNoDeprecationWarning(result)
}
GradleRunner createRunner(List<String> args, String initScript, GradleVersion gradleVersion = GradleVersion.current(), List<String> jvmArgs = [], Map<String, String> envVars = [:]) {
File initScriptsDir = new File(testProjectDir, "initScripts")
args << '-I' << new File(initScriptsDir, initScript).absolutePath
def runner = ((DefaultGradleRunner) GradleRunner.create())
.withGradleVersion(gradleVersion.version)
.withProjectDir(testProjectDir)
.withArguments(args)
.forwardOutput()
if (testKitSupportsEnvVars(gradleVersion)) {
runner.withEnvironment(envVars)
} else {
(runner as DefaultGradleRunner).withJvmArguments(jvmArgs)
}
runner
}
private boolean testKitSupportsEnvVars(GradleVersion gradleVersion) {
// TestKit supports env vars for Gradle 3.5+, except on M1 Mac where only 6.9+ is supported
def isM1Mac = System.getProperty("os.arch") == "aarch64"
if (isM1Mac) {
return gradleVersion >= GRADLE_6_X.gradleVersion
} else {
return gradleVersion >= GRADLE_3_X.gradleVersion
}
}
BuildResult assertNoDeprecationWarning(BuildResult result) {
if (!allowDevelocityDeprecationWarning) {
assert !result.output.contains("WARNING: The following functionality has been deprecated")
}
return result
}
static final class TestGradleVersion {
final GradleVersion gradleVersion
private final Integer jdkMin
private final Integer jdkMax
TestGradleVersion(GradleVersion gradleVersion, Integer jdkMin, Integer jdkMax) {
this.gradleVersion = gradleVersion
this.jdkMin = jdkMin
this.jdkMax = jdkMax
}
boolean isCompatibleWithCurrentJvm() {
def jvmVersion = getJvmVersion()
jdkMin <= jvmVersion && jvmVersion <= jdkMax
}
private static int getJvmVersion() {
String version = System.getProperty('java.version')
if (version.startsWith('1.')) {
Integer.parseInt(version.substring(2, 3))
} else {
Integer.parseInt(version.substring(0, version.indexOf('.')))
}
}
@Override
String toString() {
return "Gradle " + gradleVersion.version
}
}
}

View File

@@ -0,0 +1,278 @@
package com.gradle.gradlebuildaction
import groovy.json.JsonSlurper
import static org.junit.Assume.assumeTrue
class TestBuildResultRecorder extends BaseInitScriptTest {
def initScript = 'gradle-actions.build-result-capture.init.gradle'
def "produces build results file for build with #testGradleVersion"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
run(testGradleVersion.gradleVersion)
then:
assertResults('help', testGradleVersion, false)
where:
testGradleVersion << ALL_VERSIONS
}
def "produces build results file for failing build with #testGradleVersion"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
addFailingTaskToBuild()
runAndFail(testGradleVersion.gradleVersion)
then:
assertResults('expectFailure', testGradleVersion, true)
where:
testGradleVersion << ALL_VERSIONS
}
def "produces build results file for build with --configuration-cache on #testGradleVersion"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
run(['help', '--configuration-cache'], testGradleVersion.gradleVersion)
then:
assertResults('help', testGradleVersion, false, false)
assert buildResultFile.delete()
when:
run(['help', '--configuration-cache'], testGradleVersion.gradleVersion)
then:
assertResults('help', testGradleVersion, false, true)
where:
testGradleVersion << CONFIGURATION_CACHE_VERSIONS
}
def "produces build results file for #testGradleVersion with build scan published"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
declareDevelocityPluginApplication(testGradleVersion.gradleVersion)
run(testGradleVersion.gradleVersion)
then:
assertResults('help', testGradleVersion, false)
assertScanResults()
where:
testGradleVersion << ALL_VERSIONS
}
def "produces build results file for #testGradleVersion with legacy enterprise plugin publishing build scan"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
declareLegacyGradleEnterprisePluginApplication(testGradleVersion.gradleVersion)
run(testGradleVersion.gradleVersion)
then:
assertResults('help', testGradleVersion, false)
assertScanResults()
where:
testGradleVersion << ALL_VERSIONS
}
def "produces build results file for #testGradleVersion with Develocity plugin and no build scan published"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
declareDevelocityPluginApplication(testGradleVersion.gradleVersion)
run(['help', '--no-scan'], testGradleVersion.gradleVersion)
then:
assertResults('help', testGradleVersion, false)
where:
testGradleVersion << ALL_VERSIONS
}
def "produces build results file for failing build on #testGradleVersion with build scan published"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
declareDevelocityPluginApplication(testGradleVersion.gradleVersion)
addFailingTaskToBuild()
runAndFail(testGradleVersion.gradleVersion)
then:
assertResults('expectFailure', testGradleVersion, true)
assertScanResults()
where:
testGradleVersion << ALL_VERSIONS
}
def "produces build results file for build with --configuration-cache on #testGradleVersion with build scan published"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
declareDevelocityPluginApplication(testGradleVersion.gradleVersion)
run(['help', '--configuration-cache'], testGradleVersion.gradleVersion)
then:
assertResults('help', testGradleVersion, false, false)
assertScanResults()
assert buildResultFile.delete()
assert scanResultFile.delete()
when:
run(['help', '--configuration-cache'], testGradleVersion.gradleVersion)
then:
assertResults('help', testGradleVersion, false, true)
assertScanResults()
where:
testGradleVersion << CONFIGURATION_CACHE_VERSIONS
}
def "produces build results file for failing build on #testGradleVersion when build scan publish fails"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
declareDevelocityPluginApplication(testGradleVersion.gradleVersion)
addFailingTaskToBuild()
failScanUpload = true
runAndFail(testGradleVersion.gradleVersion)
then:
assertResults('expectFailure', testGradleVersion, true)
assertScanResults(true)
where:
testGradleVersion << ALL_VERSIONS
}
def "produces no build results file when GitHub env vars not set with #testGradleVersion"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
run(['help'], initScript, testGradleVersion.gradleVersion,
["-DRUNNER_TEMP=", "-DGITHUB_ACTION="],
[RUNNER_TEMP: '', GITHUB_ACTION: ''])
then:
def buildResultsDir = new File(testProjectDir, '.build-results')
assert !buildResultsDir.exists()
where:
testGradleVersion << ALL_VERSIONS
}
def "produces no build results file when RUNNER_TEMP dir is not a writable directory with #testGradleVersion"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
def invalidDir = new File(testProjectDir, 'invalid-runner-temp')
invalidDir.createNewFile()
run(['help'], initScript, testGradleVersion.gradleVersion,
["-DRUNNER_TEMP=${invalidDir.absolutePath}".toString()],
[RUNNER_TEMP: invalidDir.absolutePath])
then:
def buildResultsDir = new File(testProjectDir, '.build-results')
assert !buildResultsDir.exists()
where:
testGradleVersion << ALL_VERSIONS
}
def "produces build results file with build scan when Develocity plugin is applied in settingsEvaluated"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
settingsFile.text = """
plugins {
id 'com.gradle.develocity' version '3.18.1' apply(false)
}
gradle.settingsEvaluated {
apply plugin: 'com.gradle.develocity'
develocity {
server = '$mockScansServer.address'
}
}
""" + settingsFile.text
allowDevelocityDeprecationWarning = true
run(testGradleVersion.gradleVersion)
then:
assertResults('help', testGradleVersion, false)
assertScanResults()
where:
testGradleVersion << SETTINGS_PLUGIN_VERSIONS
}
def run(def args = ['help'], def gradleVersion) {
return run(args, initScript, gradleVersion, jvmArgs, envVars)
}
def runAndFail(def gradleVersion) {
return runAndFail(['expectFailure'], initScript, gradleVersion, jvmArgs, envVars)
}
def getJvmArgs() {
[
"-DRUNNER_TEMP=${testProjectDir.absolutePath}".toString(),
"-DGITHUB_ACTION=github-step-id".toString()
]
}
def getEnvVars() {
[
RUNNER_TEMP: testProjectDir.absolutePath,
GITHUB_ACTION: 'github-step-id'
]
}
void assertResults(String task, TestGradleVersion testGradleVersion, boolean hasFailure, boolean configCacheHit = false) {
def results = new JsonSlurper().parse(buildResultFile)
assert results['rootProjectName'] == ROOT_PROJECT_NAME
assert results['rootProjectDir'] == testProjectDir.canonicalPath
assert results['requestedTasks'] == task
assert results['gradleVersion'] == testGradleVersion.gradleVersion.version
assert results['gradleHomeDir'] != null
assert results['buildFailed'] == hasFailure
assert results['configCacheHit'] == configCacheHit
}
void assertScanResults(boolean scanUploadFailed = false) {
def scanResults = new JsonSlurper().parse(scanResultFile)
assert scanResults['buildScanUri'] == (scanUploadFailed ? null : "${mockScansServer.address}s/${PUBLIC_BUILD_SCAN_ID}")
assert scanResults['buildScanFailed'] == scanUploadFailed
}
private File getBuildResultFile() {
def buildResultsDir = new File(testProjectDir, '.gradle-actions/build-results')
assert buildResultsDir.directory
assert buildResultsDir.listFiles().size() == 1
def resultsFile = buildResultsDir.listFiles()[0]
assert resultsFile.name.startsWith('github-step-id')
assert resultsFile.text.count('rootProjectName') == 1
return resultsFile
}
private File getScanResultFile() {
def buildResultsDir = new File(testProjectDir, '.gradle-actions/build-scans')
assert buildResultsDir.directory
assert buildResultsDir.listFiles().size() == 1
def resultsFile = buildResultsDir.listFiles()[0]
assert resultsFile.name.startsWith('github-step-id')
assert resultsFile.text.count('buildScanUri') == 1
return resultsFile
}
}

View File

@@ -0,0 +1,213 @@
package com.gradle.gradlebuildaction
import org.gradle.util.GradleVersion
import static org.junit.Assume.assumeTrue
class TestDependencyGraph extends BaseInitScriptTest {
def initScript = 'gradle-actions.github-dependency-graph.init.gradle'
static final TestGradleVersion GRADLE_5_1 = new TestGradleVersion(GradleVersion.version('5.1.1'), 8, 12)
static final TestGradleVersion GRADLE_7_0 = new TestGradleVersion(GradleVersion.version('7.0.1'), 8, 12)
static final List<TestGradleVersion> NO_DEPENDENCY_GRAPH_VERSIONS = [GRADLE_3_X, GRADLE_4_X, GRADLE_5_1, GRADLE_7_0]
static final List<TestGradleVersion> DEPENDENCY_GRAPH_VERSIONS = ALL_VERSIONS - NO_DEPENDENCY_GRAPH_VERSIONS
def "does not produce dependency graph when not enabled"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
run(['help'], initScript, testGradleVersion.gradleVersion)
then:
assert !reportsDir.exists()
where:
testGradleVersion << ALL_VERSIONS
}
def "produces dependency graph when enabled"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
run(['help'], initScript, testGradleVersion.gradleVersion, jvmArgs, envVars)
then:
assert reportFile.exists()
where:
testGradleVersion << DEPENDENCY_GRAPH_VERSIONS
}
def "produces dependency graph with configuration-cache on latest Gradle"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
run(['help', '--configuration-cache'], initScript, testGradleVersion.gradleVersion, jvmArgs, envVars)
then:
assert reportFile.exists()
where:
// Dependency-graph plugin doesn't support config-cache for 8.0 of Gradle
testGradleVersion << [GRADLE_8_X]
}
def "warns and produces no dependency graph when enabled for older Gradle versions"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
def result = run(['help'], initScript, testGradleVersion.gradleVersion, jvmArgs, envVars)
then:
assert !reportsDir.exists()
assert result.output.contains("::warning::Dependency Graph is not supported for ${testGradleVersion}")
where:
testGradleVersion << NO_DEPENDENCY_GRAPH_VERSIONS
}
def "fails build when enabled for older Gradle versions if continue-on-failure is false"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
def vars = envVars
vars.put('GITHUB_DEPENDENCY_GRAPH_CONTINUE_ON_FAILURE', 'false')
def args = jvmArgs
Collections.replaceAll(args,
'-DGITHUB_DEPENDENCY_GRAPH_CONTINUE_ON_FAILURE=true',
'-DGITHUB_DEPENDENCY_GRAPH_CONTINUE_ON_FAILURE=false'
)
def result = runAndFail(['help'], initScript, testGradleVersion.gradleVersion, args, vars)
then:
assert !reportsDir.exists()
assert result.output.contains("Dependency Graph is not supported for ${testGradleVersion}")
where:
testGradleVersion << NO_DEPENDENCY_GRAPH_VERSIONS
}
def "constructs unique job correlator for each build invocation"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
def reportFile1 = new File(reportsDir, "CORRELATOR-1.json")
def reportFile2 = new File(reportsDir, "CORRELATOR-2.json")
buildFile << """
task firstTask {
doLast {
println "First"
}
}
task secondTask {
doLast {
println "Second"
}
}
"""
when:
run(['help'], initScript, testGradleVersion.gradleVersion, jvmArgs, envVars)
then:
assert reportFile.exists()
when:
run(['first'], initScript, testGradleVersion.gradleVersion, jvmArgs, envVars)
then:
assert reportFile.exists()
assert reportFile1.exists()
when:
run(['second'], initScript, testGradleVersion.gradleVersion, jvmArgs, envVars)
then:
assert reportFile.exists()
assert reportFile1.exists()
assert reportFile2.exists()
where:
testGradleVersion << DEPENDENCY_GRAPH_VERSIONS
}
def "can configure alternative repository for plugins"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
def vars = envVars
vars.put('GRADLE_PLUGIN_REPOSITORY_URL', 'https://plugins.grdev.net/m2')
// TODO:DAZ This props are set too late to control init-script plugin resolution
// This makes the tests fail on Mac with Gradle < 6
def args = jvmArgs
args.add('-DGRADLE_PLUGIN_REPOSITORY_URL=https://plugins.grdev.net/m2')
def result = run(['help', '--info'], initScript, testGradleVersion.gradleVersion, args, vars)
then:
assert reportFile.exists()
assert result.output.find("Resolving dependency graph plugin [\\d\\.]+ from plugin repository: https://plugins.grdev.net/m2")
where:
testGradleVersion << DEPENDENCY_GRAPH_VERSIONS
}
def "can provide credentials for alternative repository for plugins"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
def vars = envVars
vars.put('GRADLE_PLUGIN_REPOSITORY_URL', 'https://plugins.grdev.net/m2')
vars.put('GRADLE_PLUGIN_REPOSITORY_USERNAME', 'REPO_USER')
vars.put('GRADLE_PLUGIN_REPOSITORY_PASSWORD', 'REPO_PASSWORD')
// TODO:DAZ This props are set too late to control init-script plugin resolution
// This makes the tests fail on Mac with Gradle < 6
def args = jvmArgs
args.add('-DGRADLE_PLUGIN_REPOSITORY_URL=https://plugins.grdev.net/m2')
args.add('-DGRADLE_PLUGIN_REPOSITORY_USERNAME=REPO_USER')
args.add('-DGRADLE_PLUGIN_REPOSITORY_PASSWORD=REPO_PASSWORD')
def result = run(['help', '--info'], initScript, testGradleVersion.gradleVersion, args, vars)
then:
assert reportFile.exists()
assert result.output.find("Resolving dependency graph plugin [\\d\\.]+ from plugin repository: https://plugins.grdev.net/m2")
assert result.output.contains("Applying credentials for plugin repository: https://plugins.grdev.net/m2")
where:
testGradleVersion << DEPENDENCY_GRAPH_VERSIONS
}
def getEnvVars() {
return [
GITHUB_DEPENDENCY_GRAPH_ENABLED: "true",
GITHUB_DEPENDENCY_GRAPH_CONTINUE_ON_FAILURE: "true",
GITHUB_DEPENDENCY_GRAPH_JOB_CORRELATOR: "CORRELATOR",
GITHUB_DEPENDENCY_GRAPH_JOB_ID: "1",
GITHUB_DEPENDENCY_GRAPH_REF: "main",
GITHUB_DEPENDENCY_GRAPH_SHA: "123456",
GITHUB_DEPENDENCY_GRAPH_WORKSPACE: testProjectDir.absolutePath,
DEPENDENCY_GRAPH_REPORT_DIR: reportsDir.absolutePath,
]
}
def getJvmArgs() {
return [
"-DGITHUB_DEPENDENCY_GRAPH_ENABLED=true",
"-DGITHUB_DEPENDENCY_GRAPH_CONTINUE_ON_FAILURE=true",
"-DGITHUB_DEPENDENCY_GRAPH_JOB_CORRELATOR=CORRELATOR",
"-DGITHUB_DEPENDENCY_GRAPH_JOB_ID=1",
"-DGITHUB_DEPENDENCY_GRAPH_REF=main",
"-DGITHUB_DEPENDENCY_GRAPH_SHA=123456",
"-DGITHUB_DEPENDENCY_GRAPH_WORKSPACE=" + testProjectDir.absolutePath,
"-DDEPENDENCY_GRAPH_REPORT_DIR=" + reportsDir.absolutePath,
].collect {it.toString() } // Convert from GString to String
}
def getReportsDir() {
return new File(testProjectDir, 'build/reports/github-dependency-graph-snapshots')
}
def getReportFile() {
return new File(reportsDir, "CORRELATOR.json")
}
}

View File

@@ -0,0 +1,521 @@
package com.gradle.gradlebuildaction
import org.gradle.testkit.runner.BuildResult
import org.gradle.util.GradleVersion
import spock.lang.Requires
import static org.junit.Assume.assumeTrue
class TestDevelocityInjection extends BaseInitScriptTest {
static final List<TestGradleVersion> CCUD_COMPATIBLE_VERSIONS = ALL_VERSIONS - [GRADLE_3_X]
def initScript = 'gradle-actions.inject-develocity.init.gradle'
private static final GradleVersion GRADLE_5 = GradleVersion.version('5.0')
def "does not apply Develocity plugins when not requested"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
def result = run([], initScript, testGradleVersion.gradleVersion)
then:
outputMissesDevelocityPluginApplicationViaInitScript(result)
outputMissesCcudPluginApplicationViaInitScript(result)
where:
testGradleVersion << ALL_VERSIONS
}
def "does not override Develocity plugin when already defined in project"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
given:
declareDevelocityPluginApplication(testGradleVersion.gradleVersion)
when:
def result = run(testGradleVersion, testConfig())
then:
outputMissesDevelocityPluginApplicationViaInitScript(result)
outputMissesCcudPluginApplicationViaInitScript(result)
and:
outputContainsBuildScanUrl(result)
where:
testGradleVersion << ALL_VERSIONS
}
@Requires(
value = { data.testGradleVersion.gradleVersion >= GradleVersion.version("5.0") },
reason = "Prior to Gradle 5.0, we apply a fixed version of the plugin, which can't introduce this conflict"
)
def "does not override GE or Build Scan plugins even if Develocity plugin is requested"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
given:
declareLegacyGradleEnterprisePluginApplication(testGradleVersion.gradleVersion)
when:
def result = run(testGradleVersion, testConfig())
then:
outputMissesDevelocityPluginApplicationViaInitScript(result)
outputMissesCcudPluginApplicationViaInitScript(result)
and:
outputContainsBuildScanUrl(result)
where:
testGradleVersion << ALL_VERSIONS
}
def "applies Develocity plugin via init script when not defined in project"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
def result = run(testGradleVersion, testConfig())
then:
outputContainsDevelocityPluginApplicationViaInitScript(result, testGradleVersion.gradleVersion)
outputMissesCcudPluginApplicationViaInitScript(result)
and:
outputContainsBuildScanUrl(result)
where:
testGradleVersion << ALL_VERSIONS
}
def "applies deprecated Gradle Enterprise or Build Scan plugins if requested"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
given:
def appliedPluginClass = testGradleVersion.gradleVersion >= GradleVersion.version("6.0")
? "com.gradle.enterprise.gradleplugin.GradleEnterprisePlugin"
: "com.gradle.scan.plugin.BuildScanPlugin"
when:
// 3.16.2 is the latest version of deprecated plugins
def result = run(testGradleVersion, testConfig('3.16.2'))
then:
1 == result.output.count("Applying $appliedPluginClass via init script")
and:
outputContainsBuildScanUrl(result)
where:
testGradleVersion << ALL_VERSIONS
}
def "applies Develocity and CCUD plugins via init script when not defined in project"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
def result = run(testGradleVersion, testConfig().withCCUDPlugin())
then:
outputContainsDevelocityPluginApplicationViaInitScript(result, testGradleVersion.gradleVersion)
outputContainsCcudPluginApplicationViaInitScript(result)
and:
outputContainsBuildScanUrl(result)
where:
testGradleVersion << CCUD_COMPATIBLE_VERSIONS
}
def "applies CCUD plugin via init script where Develocity plugin already applied"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
given:
declareDevelocityPluginApplication(testGradleVersion.gradleVersion)
when:
// Init-script emits deprecation warnings when CCUD plugin is applied on Gradle 5.6.4
if (testGradleVersion.gradleVersion.version == "5.6.4") {
allowDevelocityDeprecationWarning = true
}
def result = run(testGradleVersion, testConfig().withCCUDPlugin())
then:
outputMissesDevelocityPluginApplicationViaInitScript(result)
outputContainsCcudPluginApplicationViaInitScript(result)
and:
outputContainsBuildScanUrl(result)
where:
testGradleVersion << CCUD_COMPATIBLE_VERSIONS
}
def "does not override CCUD plugin when already defined in project"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
given:
declareDevelocityPluginAndCcudPluginApplication(testGradleVersion.gradleVersion)
when:
def result = run(testGradleVersion, testConfig().withCCUDPlugin())
then:
outputMissesDevelocityPluginApplicationViaInitScript(result)
outputMissesCcudPluginApplicationViaInitScript(result)
and:
outputContainsBuildScanUrl(result)
where:
testGradleVersion << CCUD_COMPATIBLE_VERSIONS
}
def "ignores Develocity URL and allowUntrustedServer when Develocity plugin is not applied by the init script"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
given:
declareDevelocityPluginApplication(testGradleVersion.gradleVersion)
when:
def config = testConfig().withServer(URI.create('https://develocity-server.invalid'))
def result = run(testGradleVersion, config)
then:
outputMissesDevelocityPluginApplicationViaInitScript(result)
outputMissesCcudPluginApplicationViaInitScript(result)
and:
outputContainsBuildScanUrl(result)
where:
testGradleVersion << ALL_VERSIONS
}
def "configures Develocity URL and allowUntrustedServer when Develocity plugin is applied by the init script"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
def config = testConfig().withServer(mockScansServer.address)
def result = run(testGradleVersion, config)
then:
outputContainsDevelocityPluginApplicationViaInitScript(result, testGradleVersion.gradleVersion)
outputContainsDevelocityConnectionInfo(result, mockScansServer.address.toString(), true)
outputMissesCcudPluginApplicationViaInitScript(result)
outputContainsPluginRepositoryInfo(result, 'https://plugins.gradle.org/m2')
and:
outputContainsBuildScanUrl(result)
where:
testGradleVersion << ALL_VERSIONS
}
def "enforces Develocity URL and allowUntrustedServer in project if enforce url parameter is enabled"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
given:
declareDevelocityPluginApplication(testGradleVersion.gradleVersion, URI.create('https://develocity-server.invalid'))
when:
def config = testConfig().withServer(mockScansServer.address, true)
def result = run(testGradleVersion, config)
then:
outputMissesDevelocityPluginApplicationViaInitScript(result)
outputMissesCcudPluginApplicationViaInitScript(result)
and:
outputEnforcesDevelocityUrl(result, mockScansServer.address.toString(), true)
and:
outputContainsBuildScanUrl(result)
where:
testGradleVersion << ALL_VERSIONS
}
def "can configure alternative repository for plugins when Develocity plugin is applied by the init script"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
def config = testConfig().withPluginRepository(new URI('https://plugins.grdev.net/m2'))
def result = run(testGradleVersion, config)
then:
outputContainsDevelocityPluginApplicationViaInitScript(result, testGradleVersion.gradleVersion)
outputContainsDevelocityConnectionInfo(result, mockScansServer.address.toString(), true)
outputMissesCcudPluginApplicationViaInitScript(result)
outputContainsPluginRepositoryInfo(result, 'https://plugins.grdev.net/m2')
and:
outputContainsBuildScanUrl(result)
where:
testGradleVersion << ALL_VERSIONS
}
def "can configure alternative repository for plugins with credentials when Develocity plugin is applied by the init script"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
def config = testConfig().withPluginRepository(new URI('https://plugins.grdev.net/m2')).withPluginRepositoryCredentials("john", "doe")
def result = run(testGradleVersion, config)
then:
outputContainsDevelocityPluginApplicationViaInitScript(result, testGradleVersion.gradleVersion)
outputContainsDevelocityConnectionInfo(result, mockScansServer.address.toString(), true)
outputMissesCcudPluginApplicationViaInitScript(result)
outputContainsPluginRepositoryInfo(result, 'https://plugins.grdev.net/m2', true)
and:
outputContainsBuildScanUrl(result)
where:
testGradleVersion << ALL_VERSIONS
}
def "can configure capturing file fingerprints when Develocity plugin is applied by the init script"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
def config = testConfig().withCaptureFileFingerprints()
def result = run(testGradleVersion, config)
then:
outputContainsDevelocityPluginApplicationViaInitScript(result, testGradleVersion.gradleVersion)
outputContainsDevelocityConnectionInfo(result, mockScansServer.address.toString(), true)
outputMissesCcudPluginApplicationViaInitScript(result)
if (testGradleVersion.gradleVersion >= GRADLE_5_X.gradleVersion) {
outputCaptureFileFingerprints(result, true)
}
and:
outputContainsBuildScanUrl(result)
where:
testGradleVersion << ALL_VERSIONS
}
def "stops gracefully when requested CCUD plugin version is <1.7"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
def config = testConfig().withCCUDPlugin("1.6.6")
def result = run(testGradleVersion, config)
then:
outputMissesDevelocityPluginApplicationViaInitScript(result)
outputMissesCcudPluginApplicationViaInitScript(result)
result.output.contains('Common Custom User Data Gradle plugin must be at least 1.7. Configured version is 1.6.6.')
where:
testGradleVersion << ALL_VERSIONS
}
def "can configure Develocity via CCUD system property overrides when CCUD plugin is inject via init script"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
def config = testConfig().withCCUDPlugin().withServer(URI.create('https://develocity-server.invalid'))
def result = run(testGradleVersion, config, ["help", "-Ddevelocity.url=${mockScansServer.address}".toString()])
then:
outputContainsDevelocityPluginApplicationViaInitScript(result, testGradleVersion.gradleVersion)
outputContainsCcudPluginApplicationViaInitScript(result)
and:
outputContainsBuildScanUrl(result)
where:
testGradleVersion << CCUD_COMPATIBLE_VERSIONS
}
def "init script is configuration cache compatible"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
def config = testConfig().withCCUDPlugin()
def result = run(testGradleVersion, config, ["help", "--configuration-cache"])
then:
outputContainsDevelocityPluginApplicationViaInitScript(result, testGradleVersion.gradleVersion)
outputContainsCcudPluginApplicationViaInitScript(result)
and:
outputContainsBuildScanUrl(result)
when:
result = run(testGradleVersion, config, ["help", "--configuration-cache"])
then:
outputMissesDevelocityPluginApplicationViaInitScript(result)
outputMissesCcudPluginApplicationViaInitScript(result)
and:
outputContainsBuildScanUrl(result)
where:
testGradleVersion << CONFIGURATION_CACHE_VERSIONS
}
void outputContainsBuildScanUrl(BuildResult result) {
def message = "Publishing build scan...\n${mockScansServer.address}s/$PUBLIC_BUILD_SCAN_ID"
assert result.output.contains(message)
assert 1 == result.output.count(message)
}
void outputContainsDevelocityPluginApplicationViaInitScript(BuildResult result, GradleVersion gradleVersion) {
def pluginApplicationLogMsgGradle4 = "Applying com.gradle.scan.plugin.BuildScanPlugin via init script"
def pluginApplicationLogMsgGradle5AndHigher = "Applying com.gradle.develocity.agent.gradle.DevelocityPlugin via init script"
if (gradleVersion < GRADLE_5) {
assert result.output.contains(pluginApplicationLogMsgGradle4)
assert 1 == result.output.count(pluginApplicationLogMsgGradle4)
assert !result.output.contains(pluginApplicationLogMsgGradle5AndHigher)
} else {
assert result.output.contains(pluginApplicationLogMsgGradle5AndHigher)
assert 1 == result.output.count(pluginApplicationLogMsgGradle5AndHigher)
assert !result.output.contains(pluginApplicationLogMsgGradle4)
}
}
void outputMissesDevelocityPluginApplicationViaInitScript(BuildResult result) {
def pluginApplicationLogMsgGradle4 = "Applying com.gradle.scan.plugin.BuildScanPlugin via init script"
def pluginApplicationLogMsgGradle5AndHigher = "Applying com.gradle.develocity.agent.gradle.DevelocityPlugin via init script"
assert !result.output.contains(pluginApplicationLogMsgGradle4)
assert !result.output.contains(pluginApplicationLogMsgGradle5AndHigher)
}
void outputContainsCcudPluginApplicationViaInitScript(BuildResult result) {
def pluginApplicationLogMsg = "Applying com.gradle.CommonCustomUserDataGradlePlugin via init script"
assert result.output.contains(pluginApplicationLogMsg)
assert 1 == result.output.count(pluginApplicationLogMsg)
}
void outputMissesCcudPluginApplicationViaInitScript(BuildResult result) {
def pluginApplicationLogMsg = "Applying com.gradle.CommonCustomUserDataGradlePlugin via init script"
assert !result.output.contains(pluginApplicationLogMsg)
}
void outputContainsDevelocityConnectionInfo(BuildResult result, String develocityUrl, boolean develocityAllowUntrustedServer) {
def develocityConnectionInfo = "Connection to Develocity: $develocityUrl, allowUntrustedServer: $develocityAllowUntrustedServer"
assert result.output.contains(develocityConnectionInfo)
assert 1 == result.output.count(develocityConnectionInfo)
}
void outputCaptureFileFingerprints(BuildResult result, boolean captureFileFingerprints) {
def captureFileFingerprintsInfo = "Setting captureFileFingerprints: $captureFileFingerprints"
assert result.output.contains(captureFileFingerprintsInfo)
assert 1 == result.output.count(captureFileFingerprintsInfo)
}
void outputContainsPluginRepositoryInfo(BuildResult result, String gradlePluginRepositoryUrl, boolean withCredentials = false) {
def repositoryInfo = "Develocity plugins resolution: ${gradlePluginRepositoryUrl}"
assert result.output.contains(repositoryInfo)
assert 1 == result.output.count(repositoryInfo)
if (withCredentials) {
def credentialsInfo = "Using credentials for plugin repository"
assert result.output.contains(credentialsInfo)
assert 1 == result.output.count(credentialsInfo)
}
}
void outputEnforcesDevelocityUrl(BuildResult result, String develocityUrl, boolean develocityAllowUntrustedServer) {
def enforceUrl = "Enforcing Develocity: $develocityUrl, allowUntrustedServer: $develocityAllowUntrustedServer"
assert result.output.contains(enforceUrl)
assert 1 == result.output.count(enforceUrl)
}
private BuildResult run(TestGradleVersion testGradleVersion, TestConfig config, List<String> args = ["help"]) {
return run(args, initScript, testGradleVersion.gradleVersion, config.jvmArgs, config.envVars)
}
private TestConfig testConfig(String develocityPluginVersion = DEVELOCITY_PLUGIN_VERSION) {
new TestConfig(develocityPluginVersion)
}
class TestConfig {
String serverUrl = mockScansServer.address.toString()
boolean enforceUrl = false
String ccudPluginVersion = null
String pluginRepositoryUrl = null
String pluginRepositoryUsername = null
String pluginRepositoryPassword = null
boolean captureFileFingerprints = false
String develocityPluginVersion
TestConfig(String develocityPluginVersion) {
this.develocityPluginVersion = develocityPluginVersion
}
TestConfig withCCUDPlugin(String version = CCUD_PLUGIN_VERSION) {
ccudPluginVersion = version
return this
}
TestConfig withServer(URI url, boolean enforceUrl = false) {
serverUrl = url.toASCIIString()
this.enforceUrl = enforceUrl
return this
}
TestConfig withPluginRepository(URI pluginRepositoryUrl) {
this.pluginRepositoryUrl = pluginRepositoryUrl
return this
}
TestConfig withCaptureFileFingerprints() {
this.captureFileFingerprints = true
return this
}
TestConfig withPluginRepositoryCredentials(String pluginRepoUsername, String pluginRepoPassword) {
this.pluginRepositoryUsername = pluginRepoUsername
this.pluginRepositoryPassword = pluginRepoPassword
return this
}
def getEnvVars() {
Map<String, String> envVars = [
DEVELOCITY_INJECTION_INIT_SCRIPT_NAME : "gradle-actions.inject-develocity.init.gradle",
DEVELOCITY_INJECTION_ENABLED : "true",
DEVELOCITY_URL : serverUrl,
DEVELOCITY_ALLOW_UNTRUSTED_SERVER : "true",
DEVELOCITY_PLUGIN_VERSION : develocityPluginVersion,
DEVELOCITY_BUILD_SCAN_UPLOAD_IN_BACKGROUND: "true", // Need to upload in background since our Mock server doesn't cope with foreground upload
DEVELOCITY_AUTO_INJECTION_CUSTOM_VALUE : 'gradle-actions'
]
if (enforceUrl) envVars.put("DEVELOCITY_ENFORCE_URL", "true")
if (ccudPluginVersion != null) envVars.put("DEVELOCITY_CCUD_PLUGIN_VERSION", ccudPluginVersion)
if (pluginRepositoryUrl != null) envVars.put("GRADLE_PLUGIN_REPOSITORY_URL", pluginRepositoryUrl)
if (pluginRepositoryUsername != null) envVars.put("GRADLE_PLUGIN_REPOSITORY_USERNAME", pluginRepositoryUsername)
if (pluginRepositoryPassword != null) envVars.put("GRADLE_PLUGIN_REPOSITORY_PASSWORD", pluginRepositoryPassword)
if (captureFileFingerprints) envVars.put("DEVELOCITY_CAPTURE_FILE_FINGERPRINTS", "true")
return envVars
}
def getJvmArgs() {
List<String> jvmArgs = [
"-Ddevelocity.injection.init-script-name=gradle-actions.inject-develocity.init.gradle",
"-Ddevelocity.injection-enabled=true",
"-Ddevelocity.url=$serverUrl",
"-Ddevelocity.allow-untrusted-server=true",
"-Ddevelocity.plugin.version=$develocityPluginVersion",
"-Ddevelocity.build-scan.upload-in-background=true",
"-Ddevelocity.auto-injection.custom-value=gradle-actions"
]
if (enforceUrl) jvmArgs.add("-Ddevelocity.enforce-url=true")
if (ccudPluginVersion != null) jvmArgs.add("-Ddevelocity.ccud-plugin.version=$ccudPluginVersion")
if (pluginRepositoryUrl != null) jvmArgs.add("-Dgradle.plugin-repository.url=$pluginRepositoryUrl")
if (pluginRepositoryUsername != null) jvmArgs.add("-Dgradle.plugin-repository.username=$pluginRepositoryUsername")
if (pluginRepositoryPassword != null) jvmArgs.add("-Dgradle.plugin-repository.password=$pluginRepositoryPassword")
if (captureFileFingerprints) jvmArgs.add("-Ddevelocity.capture-file-fingerprints=true")
return jvmArgs.collect { it.toString() } // Convert from GStrings
}
}
}

1
sources/test/jest/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
tmp

View File

@@ -0,0 +1,109 @@
import * as exec from '@actions/exec'
import * as core from '@actions/core'
import * as glob from '@actions/glob'
import fs from 'fs'
import path from 'path'
import {CacheCleaner} from '../../src/caching/cache-cleaner'
jest.setTimeout(120000)
test('will cleanup unused dependency jars and build-cache entries', async () => {
const projectRoot = prepareTestProject()
const gradleUserHome = path.resolve(projectRoot, 'HOME')
const tmpDir = path.resolve(projectRoot, 'tmp')
const cacheCleaner = new CacheCleaner(gradleUserHome, tmpDir)
await runGradleBuild(projectRoot, 'build', '3.1')
const timestamp = await cacheCleaner.prepare()
await runGradleBuild(projectRoot, 'build', '3.1.1')
const commonsMath31 = path.resolve(gradleUserHome, "caches/modules-2/files-2.1/org.apache.commons/commons-math3/3.1")
const commonsMath311 = path.resolve(gradleUserHome, "caches/modules-2/files-2.1/org.apache.commons/commons-math3/3.1.1")
const buildCacheDir = path.resolve(gradleUserHome, "caches/build-cache-1")
expect(fs.existsSync(commonsMath31)).toBe(true)
expect(fs.existsSync(commonsMath311)).toBe(true)
expect(fs.readdirSync(buildCacheDir).length).toBe(4) // gc.properties, build-cache-1.lock, and 2 task entries
await cacheCleaner.forceCleanupFilesOlderThan(timestamp)
expect(fs.existsSync(commonsMath31)).toBe(false)
expect(fs.existsSync(commonsMath311)).toBe(true)
expect(fs.readdirSync(buildCacheDir).length).toBe(3) // 1 task entry has been cleaned up
})
test('will cleanup unused gradle versions', async () => {
const projectRoot = prepareTestProject()
const gradleUserHome = path.resolve(projectRoot, 'HOME')
const tmpDir = path.resolve(projectRoot, 'tmp')
const cacheCleaner = new CacheCleaner(gradleUserHome, tmpDir)
// Initialize HOME with 2 different Gradle versions
await runGradleWrapperBuild(projectRoot, 'build')
await runGradleBuild(projectRoot, 'build')
const timestamp = await cacheCleaner.prepare()
// Run with only one of these versions
await runGradleBuild(projectRoot, 'build')
const gradle802 = path.resolve(gradleUserHome, "caches/8.0.2")
const transforms3 = path.resolve(gradleUserHome, "caches/transforms-3")
const metadata100 = path.resolve(gradleUserHome, "caches/modules-2/metadata-2.100")
const wrapper802 = path.resolve(gradleUserHome, "wrapper/dists/gradle-8.0.2-bin")
const gradleCurrent = path.resolve(gradleUserHome, "caches/8.10")
const metadataCurrent = path.resolve(gradleUserHome, "caches/modules-2/metadata-2.106")
expect(fs.existsSync(gradle802)).toBe(true)
expect(fs.existsSync(transforms3)).toBe(true)
expect(fs.existsSync(metadata100)).toBe(true)
expect(fs.existsSync(wrapper802)).toBe(true)
expect(fs.existsSync(gradleCurrent)).toBe(true)
expect(fs.existsSync(metadataCurrent)).toBe(true)
// The wrapper won't be removed if it was recently downloaded. Age it.
setUtimes(wrapper802, new Date(Date.now() - 48 * 60 * 60 * 1000))
await cacheCleaner.forceCleanupFilesOlderThan(timestamp)
expect(fs.existsSync(gradle802)).toBe(false)
expect(fs.existsSync(transforms3)).toBe(false)
expect(fs.existsSync(metadata100)).toBe(false)
expect(fs.existsSync(wrapper802)).toBe(false)
expect(fs.existsSync(gradleCurrent)).toBe(true)
expect(fs.existsSync(metadataCurrent)).toBe(true)
})
async function runGradleBuild(projectRoot: string, args: string, version: string = '3.1'): Promise<void> {
const status31 = await exec.exec(`gradle -g HOME --no-daemon --build-cache -Dcommons_math3_version="${version}" ${args}`, [], {
cwd: projectRoot
})
console.log(`Gradle User Home initialized with commons_math3_version=${version} ${args}`)
}
async function runGradleWrapperBuild(projectRoot: string, args: string, version: string = '3.1'): Promise<void> {
const status31 = await exec.exec(`./gradlew -g HOME --no-daemon --build-cache -Dcommons_math3_version="${version}" ${args}`, [], {
cwd: projectRoot
})
console.log(`Gradle User Home initialized with commons_math3_version="${version}" ${args}`)
}
function prepareTestProject(): string {
const projectRoot = 'test/jest/resources/cache-cleanup'
fs.rmSync(path.resolve(projectRoot, 'HOME'), { recursive: true, force: true })
fs.rmSync(path.resolve(projectRoot, 'tmp'), { recursive: true, force: true })
fs.rmSync(path.resolve(projectRoot, 'build'), { recursive: true, force: true })
fs.rmSync(path.resolve(projectRoot, '.gradle'), { recursive: true, force: true })
return projectRoot
}
async function setUtimes(pattern: string, timestamp: Date): Promise<void> {
const globber = await glob.create(pattern)
for await (const file of globber.globGenerator()) {
fs.utimesSync(file, timestamp, timestamp)
}
}

View File

@@ -0,0 +1,35 @@
import * as path from 'path'
import * as fs from 'fs'
import {GradleUserHomeCache} from "../../src/caching/gradle-user-home-cache"
import {CacheConfig} from "../../src/configuration"
const testTmp = 'test/jest/tmp'
fs.rmSync(testTmp, {recursive: true, force: true})
describe("--info and --stacktrace", () => {
describe("will be created", () => {
it("when gradle.properties does not exists", async () => {
const emptyGradleHome = `${testTmp}/empty-gradle-home`
fs.mkdirSync(emptyGradleHome, {recursive: true})
const stateCache = new GradleUserHomeCache("ignored", emptyGradleHome, new CacheConfig())
stateCache.configureInfoLogLevel()
expect(fs.readFileSync(path.resolve(emptyGradleHome, "gradle.properties"), 'utf-8'))
.toBe("org.gradle.logging.level=info\norg.gradle.logging.stacktrace=all\n")
})
})
describe("will be added", () => {
it("and gradle.properties does exists", async () => {
const existingGradleHome = `${testTmp}/existing-gradle-home`
fs.mkdirSync(existingGradleHome, {recursive: true})
fs.writeFileSync(path.resolve(existingGradleHome, "gradle.properties"), "org.gradle.logging.level=debug\n")
const stateCache = new GradleUserHomeCache("ignored", existingGradleHome, new CacheConfig())
stateCache.configureInfoLogLevel()
expect(fs.readFileSync(path.resolve(existingGradleHome, "gradle.properties"), 'utf-8'))
.toBe("org.gradle.logging.level=info\norg.gradle.logging.stacktrace=all\n\norg.gradle.logging.level=debug\n")
})
})
})

View File

@@ -0,0 +1,98 @@
import exp from 'constants'
import {CacheEntryListener, CacheListener} from '../../src/caching/cache-reporting'
describe('caching report', () => {
describe('reports not fully restored', () => {
it('with one requested entry report', async () => {
const report = new CacheListener()
report.entry('foo').markRequested('1', ['2'])
report.entry('bar').markRequested('3').markRestored('4', 500, 1000)
expect(report.fullyRestored).toBe(false)
})
})
describe('reports fully restored', () => {
it('when empty', async () => {
const report = new CacheListener()
expect(report.fullyRestored).toBe(true)
})
it('with empty entry reports', async () => {
const report = new CacheListener()
report.entry('foo')
report.entry('bar')
expect(report.fullyRestored).toBe(true)
})
it('with restored entry report', async () => {
const report = new CacheListener()
report.entry('bar').markRequested('3').markRestored('4', 300, 1000)
expect(report.fullyRestored).toBe(true)
})
it('with multiple restored entry reportss', async () => {
const report = new CacheListener()
report.entry('foo').markRestored('4', 3300, 111)
report.entry('bar').markRequested('3').markRestored('4', 333, 1000)
expect(report.fullyRestored).toBe(true)
})
})
describe('can be stringified and rehydrated', () => {
it('when empty', async () => {
const report = new CacheListener()
const stringRep = report.stringify()
const reportClone: CacheListener = CacheListener.rehydrate(stringRep)
expect(reportClone.cacheEntries).toEqual([])
// Can call methods on rehydrated
expect(reportClone.entry('foo')).toBeInstanceOf(CacheEntryListener)
})
it('with entry reports', async () => {
const report = new CacheListener()
report.entry('foo')
report.entry('bar')
report.entry('baz')
const stringRep = report.stringify()
const reportClone: CacheListener = CacheListener.rehydrate(stringRep)
expect(reportClone.cacheEntries.length).toBe(3)
expect(reportClone.cacheEntries[0].entryName).toBe('foo')
expect(reportClone.cacheEntries[1].entryName).toBe('bar')
expect(reportClone.cacheEntries[2].entryName).toBe('baz')
expect(reportClone.entry('foo')).toBe(reportClone.cacheEntries[0])
})
it('with rehydrated entry report', async () => {
const report = new CacheListener()
const entryReport = report.entry('foo')
entryReport.markRequested('1', ['2', '3'])
entryReport.markSaved('4', 100, 1000)
const stringRep = report.stringify()
const reportClone: CacheListener = CacheListener.rehydrate(stringRep)
const entryClone = reportClone.entry('foo')
expect(entryClone.requestedKey).toBe('1')
expect(entryClone.requestedRestoreKeys).toEqual(['2', '3'])
expect(entryClone.savedKey).toBe('4')
expect(entryClone.savedSize).toBe(100)
expect(entryClone.savedTime).toBe(1000)
})
it('with live entry report', async () => {
const report = new CacheListener()
const entryReport = report.entry('foo')
entryReport.markRequested('1', ['2', '3'])
const stringRep = report.stringify()
const reportClone: CacheListener = CacheListener.rehydrate(stringRep)
const entryClone = reportClone.entry('foo')
// Check type and call method on rehydrated entry report
expect(entryClone).toBeInstanceOf(CacheEntryListener)
entryClone.markSaved('4', 100, 1000)
expect(entryClone.requestedKey).toBe('1')
expect(entryClone.requestedRestoreKeys).toEqual(['2', '3'])
expect(entryClone.savedKey).toBe('4')
})
})
})

View File

@@ -0,0 +1,20 @@
import * as cacheUtils from '../../src/caching/cache-utils'
describe('cacheUtils-utils', () => {
describe('can hash', () => {
it('a string', async () => {
const hash = cacheUtils.hashStrings(['foo'])
expect(hash).toBe('acbd18db4cc2f85cedef654fccc4a4d8')
})
it('multiple strings', async () => {
const hash = cacheUtils.hashStrings(['foo', 'bar', 'baz'])
expect(hash).toBe('6df23dc03f9b54cc38a0fc1483df6e21')
})
it('normalized filenames', async () => {
const fileNames = ['/foo/bar/baz.zip', '../boo.html']
const posixHash = cacheUtils.hashFileNames(fileNames)
const windowsHash = cacheUtils.hashFileNames(fileNames)
expect(posixHash).toBe(windowsHash)
})
})
})

View File

@@ -0,0 +1,22 @@
import * as inputParams from '../../src/configuration'
describe('input params', () => {
describe('parses numeric input', () => {
it('uses default value', () => {
const val = inputParams.parseNumericInput('param-name', '', 88)
expect(val).toBe(88)
})
it('parses numeric input', () => {
const val = inputParams.parseNumericInput('param-name', '34', 88)
expect(val).toBe(34)
})
it('fails on non-numeric input', () => {
const t = () => {
inputParams.parseNumericInput('param-name', 'xyz', 88)
};
expect(t).toThrow(TypeError)
expect(t).toThrow("The value 'xyz' is not a valid numeric value for 'param-name'.")
})
})
})

View File

@@ -0,0 +1,34 @@
import { DependencyGraphConfig } from "../../src/configuration"
describe('dependency-graph', () => {
describe('constructs job correlator', () => {
it('removes commas from workflow name', () => {
const id = DependencyGraphConfig.constructJobCorrelator('Workflow, with,commas', 'jobid', '{}')
expect(id).toBe('workflow_withcommas-jobid')
})
it('removes non word characters', () => {
const id = DependencyGraphConfig.constructJobCorrelator('Workflow!_with()characters', 'job-*id', '{"foo": "bar!@#$%^&*("}')
expect(id).toBe('workflow_withcharacters-job-id-bar')
})
it('replaces spaces', () => {
const id = DependencyGraphConfig.constructJobCorrelator('Workflow !_ with () characters, and spaces', 'job-*id', '{"foo": "bar!@#$%^&*("}')
expect(id).toBe('workflow___with_characters_and_spaces-job-id-bar')
})
it('without matrix', () => {
const id = DependencyGraphConfig.constructJobCorrelator('workflow', 'jobid', 'null')
expect(id).toBe('workflow-jobid')
})
it('with dashes in values', () => {
const id = DependencyGraphConfig.constructJobCorrelator('workflow-name', 'job-id', '{"os": "ubuntu-latest"}')
expect(id).toBe('workflow-name-job-id-ubuntu-latest')
})
it('with single matrix value', () => {
const id = DependencyGraphConfig.constructJobCorrelator('workflow', 'jobid', '{"os": "windows"}')
expect(id).toBe('workflow-jobid-windows')
})
it('with composite matrix value', () => {
const id = DependencyGraphConfig.constructJobCorrelator('workflow', 'jobid', '{"os": "windows", "java-version": "21.1", "other": "Value, with COMMA"}')
expect(id).toBe('workflow-jobid-windows-211-value_with_comma')
})
})
})

View File

@@ -0,0 +1,104 @@
import { describe } from 'node:test'
import { versionIsAtLeast, parseGradleVersionFromOutput } from '../../src/execution/gradle'
describe('gradle', () => {
describe('can compare version with', () => {
it('same version', async () => {
expect(versionIsAtLeast('6.7.1', '6.7.1')).toBe(true)
expect(versionIsAtLeast('7.0', '7.0')).toBe(true)
expect(versionIsAtLeast('7.0', '7.0.0')).toBe(true)
})
it('newer version', async () => {
expect(versionIsAtLeast('6.7.1', '6.7.2')).toBe(false)
expect(versionIsAtLeast('7.0', '8.0')).toBe(false)
expect(versionIsAtLeast('7.0', '7.0.1')).toBe(false)
})
it('older version', async () => {
expect(versionIsAtLeast('6.7.2', '6.7.1')).toBe(true)
expect(versionIsAtLeast('8.0', '7.0')).toBe(true)
expect(versionIsAtLeast('7.0.1', '7.0')).toBe(true)
})
it('rc version', async () => {
expect(versionIsAtLeast('8.0.2-rc-1', '8.0.1')).toBe(true)
expect(versionIsAtLeast('8.0.2-rc-1', '8.0.2')).toBe(false)
expect(versionIsAtLeast('8.1-rc-1', '8.0')).toBe(true)
expect(versionIsAtLeast('8.0-rc-1', '8.0')).toBe(false)
})
it('snapshot version', async () => {
expect(versionIsAtLeast('8.11-20240829002031+0000', '8.10')).toBe(true)
expect(versionIsAtLeast('8.11-20240829002031+0000', '8.10.1')).toBe(true)
expect(versionIsAtLeast('8.11-20240829002031+0000', '8.11')).toBe(false)
expect(versionIsAtLeast('8.10.2-20240828012138+0000', '8.10')).toBe(true)
expect(versionIsAtLeast('8.10.2-20240828012138+0000', '8.10.1')).toBe(true)
expect(versionIsAtLeast('8.10.2-20240828012138+0000', '8.10.2')).toBe(false)
expect(versionIsAtLeast('8.10.2-20240828012138+0000', '8.11')).toBe(false)
expect(versionIsAtLeast('9.1-branch-provider_api_migration_public_api_changes-20240826121451+0000', '9.0')).toBe(true)
expect(versionIsAtLeast('9.1-branch-provider_api_migration_public_api_changes-20240826121451+0000', '9.0.1')).toBe(true)
expect(versionIsAtLeast('9.1-branch-provider_api_migration_public_api_changes-20240826121451+0000', '9.1')).toBe(false)
})
})
describe('can parse version from output', () => {
it('major version', async () => {
const output = `
------------------------------------------------------------
Gradle 8.9
------------------------------------------------------------
`
const version = await parseGradleVersionFromOutput(output)!
expect(version).toBe('8.9')
})
it('patch version', async () => {
const output = `
------------------------------------------------------------
Gradle 8.9.1
------------------------------------------------------------
`
const version = await parseGradleVersionFromOutput(output)!
expect(version).toBe('8.9.1')
})
it('rc version', async () => {
const output = `
------------------------------------------------------------
Gradle 8.9-rc-1
------------------------------------------------------------
`
const version = await parseGradleVersionFromOutput(output)!
expect(version).toBe('8.9-rc-1')
})
it('milestone version', async () => {
const output = `
------------------------------------------------------------
Gradle 8.0-milestone-6
------------------------------------------------------------
`
const version = await parseGradleVersionFromOutput(output)!
expect(version).toBe('8.0-milestone-6')
})
it('snapshot version', async () => {
const output = `
------------------------------------------------------------
Gradle 8.10.2-20240828012138+0000
------------------------------------------------------------
`
const version = await parseGradleVersionFromOutput(output)!
expect(version).toBe('8.10.2-20240828012138+0000')
})
it('branch version', async () => {
const output = `
------------------------------------------------------------
Gradle 9.0-branch-provider_api_migration_public_api_changes-20240830060514+0000
------------------------------------------------------------
`
const version = await parseGradleVersionFromOutput(output)!
expect(version).toBe('9.0-branch-provider_api_migration_public_api_changes-20240830060514+0000')
})
})
})

View File

@@ -0,0 +1,178 @@
import { BuildResult } from '../../src/build-results'
import { renderSummaryTable } from '../../src/job-summary'
import dedent from 'dedent'
const successfulHelpBuild: BuildResult = {
rootProjectName: 'root',
rootProjectDir: '/',
requestedTasks: 'help',
gradleVersion: '8.0',
gradleHomeDir: '/opt/gradle',
buildFailed: false,
configCacheHit: false,
buildScanUri: 'https://scans.gradle.com/s/abc123',
buildScanFailed: false
}
const failedHelpBuild: BuildResult = {
...successfulHelpBuild,
buildFailed: true
}
const longArgsBuild: BuildResult = {
...successfulHelpBuild,
requestedTasks: 'check publishMyLongNamePluginPublicationToMavenCentral publishMyLongNamePluginPublicationToPluginPortal',
}
const scanPublishDisabledBuild: BuildResult = {
...successfulHelpBuild,
buildScanUri: '',
buildScanFailed: false,
}
const scanPublishFailedBuild: BuildResult = {
...successfulHelpBuild,
buildScanUri: '',
buildScanFailed: true,
}
describe('renderSummaryTable', () => {
describe('renders', () => {
it('successful build', () => {
const table = renderSummaryTable([successfulHelpBuild])
expect(table.trim()).toBe(dedent`
<table>
<tr>
<th>Gradle Root Project</th>
<th>Requested Tasks</th>
<th>Gradle Version</th>
<th>Build Outcome</th>
<th>Build&nbsp;Scan®</th>
</tr>
<tr>
<td>root</td>
<td>help</td>
<td align='center'>8.0</td>
<td align='center'>:white_check_mark:</td>
<td><a href="https://scans.gradle.com/s/abc123" rel="nofollow" target="_blank"><img src="https://img.shields.io/badge/Build%20Scan%C2%AE-06A0CE?logo=Gradle" alt="Build Scan published" /></a></td>
</tr>
</table>
`);
})
it('failed build', () => {
const table = renderSummaryTable([failedHelpBuild])
expect(table.trim()).toBe(dedent`
<table>
<tr>
<th>Gradle Root Project</th>
<th>Requested Tasks</th>
<th>Gradle Version</th>
<th>Build Outcome</th>
<th>Build&nbsp;Scan®</th>
</tr>
<tr>
<td>root</td>
<td>help</td>
<td align='center'>8.0</td>
<td align='center'>:x:</td>
<td><a href="https://scans.gradle.com/s/abc123" rel="nofollow" target="_blank"><img src="https://img.shields.io/badge/Build%20Scan%C2%AE-06A0CE?logo=Gradle" alt="Build Scan published" /></a></td>
</tr>
</table>
`);
})
describe('when build scan', () => {
it('publishing disabled', () => {
const table = renderSummaryTable([scanPublishDisabledBuild])
expect(table.trim()).toBe(dedent`
<table>
<tr>
<th>Gradle Root Project</th>
<th>Requested Tasks</th>
<th>Gradle Version</th>
<th>Build Outcome</th>
<th>Build&nbsp;Scan®</th>
</tr>
<tr>
<td>root</td>
<td>help</td>
<td align='center'>8.0</td>
<td align='center'>:white_check_mark:</td>
<td><a href="https://scans.gradle.com" rel="nofollow" target="_blank"><img src="https://img.shields.io/badge/Not%20published-lightgrey" alt="Build Scan not published" /></a></td>
</tr>
</table>
`);
})
it('publishing failed', () => {
const table = renderSummaryTable([scanPublishFailedBuild])
expect(table.trim()).toBe(dedent`
<table>
<tr>
<th>Gradle Root Project</th>
<th>Requested Tasks</th>
<th>Gradle Version</th>
<th>Build Outcome</th>
<th>Build&nbsp;Scan®</th>
</tr>
<tr>
<td>root</td>
<td>help</td>
<td align='center'>8.0</td>
<td align='center'>:white_check_mark:</td>
<td><a href="https://docs.gradle.com/develocity/gradle-plugin/#troubleshooting" rel="nofollow" target="_blank"><img src="https://img.shields.io/badge/Publish%20failed-orange" alt="Build Scan publish failed" /></a></td>
</tr>
</table>
`);
})
})
it('multiple builds', () => {
const table = renderSummaryTable([successfulHelpBuild, failedHelpBuild])
expect(table.trim()).toBe(dedent`
<table>
<tr>
<th>Gradle Root Project</th>
<th>Requested Tasks</th>
<th>Gradle Version</th>
<th>Build Outcome</th>
<th>Build&nbsp;Scan®</th>
</tr>
<tr>
<td>root</td>
<td>help</td>
<td align='center'>8.0</td>
<td align='center'>:white_check_mark:</td>
<td><a href="https://scans.gradle.com/s/abc123" rel="nofollow" target="_blank"><img src="https://img.shields.io/badge/Build%20Scan%C2%AE-06A0CE?logo=Gradle" alt="Build Scan published" /></a></td>
</tr>
<tr>
<td>root</td>
<td>help</td>
<td align='center'>8.0</td>
<td align='center'>:x:</td>
<td><a href="https://scans.gradle.com/s/abc123" rel="nofollow" target="_blank"><img src="https://img.shields.io/badge/Build%20Scan%C2%AE-06A0CE?logo=Gradle" alt="Build Scan published" /></a></td>
</tr>
</table>
`);
})
it('truncating long requested tasks', () => {
const table = renderSummaryTable([longArgsBuild])
expect(table.trim()).toBe(dedent`
<table>
<tr>
<th>Gradle Root Project</th>
<th>Requested Tasks</th>
<th>Gradle Version</th>
<th>Build Outcome</th>
<th>Build&nbsp;Scan®</th>
</tr>
<tr>
<td>root</td>
<td><div title='check publishMyLongNamePluginPublicationToMavenCentral publishMyLongNamePluginPublicationToPluginPortal'>check publishMyLongNamePluginPublicationToMavenCentral publ…</div></td>
<td align='center'>8.0</td>
<td align='center'>:white_check_mark:</td>
<td><a href="https://scans.gradle.com/s/abc123" rel="nofollow" target="_blank"><img src="https://img.shields.io/badge/Build%20Scan%C2%AE-06A0CE?logo=Gradle" alt="Build Scan published" /></a></td>
</tr>
</table>
`);
})
})
})

View File

@@ -0,0 +1,117 @@
import {getPredefinedToolchains, mergeToolchainContent} from "../../src/caching/gradle-user-home-utils";
describe('predefined-toolchains', () => {
const OLD_ENV = process.env
afterAll(() => {
process.env = OLD_ENV
});
describe('returns', () => {
it('null if no JAVA_HOME_ envs are set', async () => {
jest.resetModules()
process.env = {
"JAVA_HOME": "/jdks/foo_8"
}
const predefinedToolchains = getPredefinedToolchains()
expect(predefinedToolchains).toBe(null)
})
it('valid toolchains.xml if JAVA_HOME_ envs are set', async () => {
jest.resetModules()
process.env = {
"JAVA_HOME": "/jdks/foo_8",
"JAVA_HOME_8_X64": "/jdks/foo_8",
"JAVA_HOME_11_X64": "/jdks/foo_11",
"JAVA_HOME_21_ARM64": "/jdks/foo_21",
}
const predefinedToolchains = getPredefinedToolchains()
expect(predefinedToolchains).toBe(
// language=XML
`<?xml version="1.0" encoding="UTF-8"?>
<toolchains>
<!-- JDK Toolchains installed by default on GitHub-hosted runners -->
<toolchain>
<type>jdk</type>
<provides>
<version>8</version>
</provides>
<configuration>
<jdkHome>\${env.JAVA_HOME_8_X64}</jdkHome>
</configuration>
</toolchain>
<toolchain>
<type>jdk</type>
<provides>
<version>11</version>
</provides>
<configuration>
<jdkHome>\${env.JAVA_HOME_11_X64}</jdkHome>
</configuration>
</toolchain>
<toolchain>
<type>jdk</type>
<provides>
<version>21</version>
</provides>
<configuration>
<jdkHome>\${env.JAVA_HOME_21_ARM64}</jdkHome>
</configuration>
</toolchain>
</toolchains>
`)
})
})
it("merges with existing toolchains", async () => {
jest.resetModules()
process.env = {
"JAVA_HOME_11_X64": "/jdks/foo_11",
}
// language=XML
const existingToolchains =
`<?xml version="1.0" encoding="UTF-8"?>
<toolchains>
<toolchain>
<type>jdk</type>
<provides>
<version>8</version>
</provides>
<configuration>
<jdkHome>\${env.JAVA_HOME_8_X64}</jdkHome>
</configuration>
</toolchain>
</toolchains>
`
const mergedContent = mergeToolchainContent(existingToolchains, getPredefinedToolchains()!)
expect(mergedContent).toBe(
// language=XML
`<?xml version="1.0" encoding="UTF-8"?>
<toolchains>
<toolchain>
<type>jdk</type>
<provides>
<version>8</version>
</provides>
<configuration>
<jdkHome>\${env.JAVA_HOME_8_X64}</jdkHome>
</configuration>
</toolchain>
<!-- JDK Toolchains installed by default on GitHub-hosted runners -->
<toolchain>
<type>jdk</type>
<provides>
<version>11</version>
</provides>
<configuration>
<jdkHome>\${env.JAVA_HOME_11_X64}</jdkHome>
</configuration>
</toolchain>
</toolchains>
`)
})
})

View File

@@ -0,0 +1,6 @@
#
# https://help.github.com/articles/dealing-with-line-endings/
#
# These are explicitly windows files and should use crlf
*.bat text eol=crlf

View File

@@ -0,0 +1,8 @@
# Ignore Gradle project-specific cache directory
.gradle
# Ignore Gradle build output directory
build
HOME
tmp

View File

@@ -0,0 +1,11 @@
plugins {
id 'java-library'
}
repositories {
mavenCentral()
}
dependencies {
api "org.apache.commons:commons-math3:${System.properties['commons_math3_version']}"
}

View File

@@ -0,0 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
# Deliberately not using the latest Gradle version for cache cleanup testing
distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@@ -0,0 +1,245 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original 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.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

View File

@@ -0,0 +1,92 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -0,0 +1 @@
rootProject.name = 'unused-dependencies'

View File

@@ -0,0 +1,10 @@
/*
* This Java source file was generated by the Gradle 'init' task.
*/
package unused.dependencies;
public class Library {
public boolean someLibraryMethod() {
return true;
}
}

View File

@@ -0,0 +1,127 @@
import {DevelocityAccessCredentials, getToken} from "../../src/develocity/short-lived-token";
import nock from "nock";
describe('short lived tokens', () => {
it('parse valid access key should return an object', async () => {
let develocityAccessCredentials = DevelocityAccessCredentials.parse('some-host.local=key1;host2=key2');
expect(develocityAccessCredentials).toStrictEqual(DevelocityAccessCredentials.of([
{hostname: 'some-host.local', key: 'key1'},
{hostname: 'host2', key: 'key2'}])
)
})
it('parse wrong access key should return null', async () => {
let develocityAccessCredentials = DevelocityAccessCredentials.parse('random;foo');
expect(develocityAccessCredentials).toBeNull()
})
it('parse empty access key should return null', async () => {
let develocityAccessCredentials = DevelocityAccessCredentials.parse('');
expect(develocityAccessCredentials).toBeNull()
})
it('access key as raw string', async () => {
let develocityAccessCredentials = DevelocityAccessCredentials.parse('host1=key1;host2=key2');
expect(develocityAccessCredentials?.raw()).toBe('host1=key1;host2=key2')
})
it('get short lived token fails when cannot connect', async () => {
nock('http://localhost:3333')
.post('/api/auth/token')
.times(3)
.replyWithError({
message: 'connect ECONNREFUSED 127.0.0.1:3333',
code: 'ECONNREFUSED'
})
await expect(getToken('localhost=key0', ''))
.resolves
.toBeNull()
})
it('get short lived token is null when request fails', async () => {
nock('http://dev:3333')
.post('/api/auth/token')
.times(3)
.reply(500, 'Internal error')
expect.assertions(1)
await expect(getToken('dev=xyz', ''))
.resolves
.toBeNull()
})
it('get short lived token returns null when access key is empty', async () => {
expect.assertions(1)
await expect(getToken('', ''))
.resolves
.toBeNull()
})
it('get short lived token succeeds when single key is set', async () => {
nock('https://dev')
.post('/api/auth/token')
.reply(200, 'token')
expect.assertions(1)
await expect(getToken('dev=key1', ''))
.resolves
.toEqual({"keys": [{"hostname": "dev", "key": "token"}]})
})
it('get short lived token succeeds when multiple keys are set', async () => {
nock('https://dev')
.post('/api/auth/token')
.reply(200, 'token1')
nock('https://prod')
.post('/api/auth/token')
.reply(200, 'token2')
expect.assertions(1)
await expect(getToken('dev=key1;prod=key2', ''))
.resolves
.toEqual({"keys": [{"hostname": "dev", "key": "token1"}, {"hostname": "prod", "key": "token2"}]})
})
it('get short lived token succeeds when multiple keys are set and one is failing', async () => {
nock('https://dev')
.post('/api/auth/token')
.reply(200, 'token1')
nock('https://bogus')
.post('/api/auth/token')
.times(3)
.reply(500, 'Internal Error')
nock('https://prod')
.post('/api/auth/token')
.reply(200, 'token2')
expect.assertions(1)
await expect(getToken('dev=key1;bogus=key0;prod=key2', ''))
.resolves
.toEqual({"keys": [{"hostname": "dev", "key": "token1"}, {"hostname": "prod", "key": "token2"}]})
})
it('get short lived token is null when multiple keys are set and all are failing', async () => {
nock('https://dev')
.post('/api/auth/token')
.times(3)
.reply(500, 'Internal Error')
nock('https://bogus')
.post('/api/auth/token')
.times(3)
.reply(500, 'Internal Error')
expect.assertions(1)
await expect(getToken('dev=key1;bogus=key0', ''))
.resolves
.toBeNull()
})
it('get short lived token with custom expiry', async () => {
nock('https://dev')
.post('/api/auth/token?expiresInHours=4')
.reply(200, 'token')
expect.assertions(1)
await expect(getToken('dev=key1', '4'))
.resolves
.toEqual({"keys": [{"hostname": "dev", "key": "token"}]})
})
})

View File

@@ -0,0 +1,71 @@
import * as checksums from '../../../src/wrapper-validation/checksums'
import nock from 'nock'
import {afterEach, describe, expect, test, jest} from '@jest/globals'
jest.setTimeout(30000)
test('has loaded hardcoded wrapper jars checksums', async () => {
// Sanity check that generated checksums file is not empty and was properly imported
expect(checksums.KNOWN_CHECKSUMS.checksums.size).toBeGreaterThan(10)
// Verify that checksums of arbitrary versions are contained
expect(
checksums.KNOWN_CHECKSUMS.checksums.get(
'660ab018b8e319e9ae779fdb1b7ac47d0321bde953bf0eb4545f14952cfdcaa3'
)
).toEqual(new Set(['4.10.3']))
expect(
checksums.KNOWN_CHECKSUMS.checksums.get(
'28b330c20a9a73881dfe9702df78d4d78bf72368e8906c70080ab6932462fe9e'
)
).toEqual(new Set(['6.0-rc-1', '6.0-rc-2', '6.0-rc-3', '6.0', '6.0.1']))
})
test('fetches wrapper jars checksums', async () => {
const validChecksums = await checksums.fetchUnknownChecksums(false, new checksums.WrapperChecksums)
expect(validChecksums.size).toBeGreaterThan(10)
// Verify that checksum of arbitrary version is contained
expect(
validChecksums.has(
// Checksum for version 6.0
'28b330c20a9a73881dfe9702df78d4d78bf72368e8906c70080ab6932462fe9e'
)
).toBe(true)
})
test('fetches wrapper jar checksums for snapshots', async () => {
const nonSnapshotChecksums = await checksums.fetchUnknownChecksums(false, new checksums.WrapperChecksums)
const validChecksums = await checksums.fetchUnknownChecksums(true, new checksums.WrapperChecksums)
// Expect that at least one snapshot checksum is different from the non-snapshot checksums
expect(validChecksums.size).toBeGreaterThan(nonSnapshotChecksums.size)
})
test('fetches all wrapper checksum URLS for snapshots', async () => {
const checksumUrls: string[] = []
await checksums.addDistributionSnapshotChecksums(checksumUrls)
expect(checksumUrls.length).toBeGreaterThan(100) // May only be a few unique checksums
console.log(checksumUrls)
})
describe('retry', () => {
afterEach(() => {
nock.cleanAll()
})
describe('for /versions/all API', () => {
test('retry three times', async () => {
nock('https://services.gradle.org', {allowUnmocked: true})
.get('/versions/all')
.times(3)
.replyWithError({
message: 'connect ECONNREFUSED 104.18.191.9:443',
code: 'ECONNREFUSED'
})
const validChecksums = await checksums.fetchUnknownChecksums(false, new checksums.WrapperChecksums)
expect(validChecksums.size).toBeGreaterThan(10)
nock.isDone()
})
})
})

View File

@@ -0,0 +1,12 @@
import * as path from 'path'
import * as find from '../../../src/wrapper-validation/find'
import {expect, test} from '@jest/globals'
test('finds test data wrapper jars', async () => {
const repoRoot = path.resolve('./test/jest/wrapper-validation')
const wrapperJars = await find.findWrapperJars(repoRoot)
expect(wrapperJars.length).toBe(3)
expect(wrapperJars).toContain('data/valid/gradle-wrapper.jar')
expect(wrapperJars).toContain('data/invalid/gradle-wrapper.jar')
expect(wrapperJars).toContain('data/invalid/gradlе-wrapper.jar') // homoglyph
})

View File

@@ -0,0 +1,12 @@
import * as path from 'path'
import * as hash from '../../../src/wrapper-validation/hash'
import {expect, test} from '@jest/globals'
test('can sha256 files', async () => {
const sha = await hash.sha256File(
path.resolve('test/jest/wrapper-validation/data/invalid/gradle-wrapper.jar')
)
expect(sha).toEqual(
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
)
})

View File

@@ -0,0 +1,116 @@
import * as path from 'path'
import * as fs from 'fs'
import * as validate from '../../../src/wrapper-validation/validate'
import {expect, test, jest} from '@jest/globals'
import { WrapperChecksums } from '../../../src/wrapper-validation/checksums'
import { ChecksumCache } from '../../../src/wrapper-validation/cache'
import exp from 'constants'
jest.setTimeout(30000)
const baseDir = path.resolve('./test/jest/wrapper-validation')
const tmpDir = path.resolve('./test/jest/tmp')
test('succeeds if all found wrapper jars are valid', async () => {
const result = await validate.findInvalidWrapperJars(baseDir, false, [
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
])
expect(result.isValid()).toBe(true)
// Only hardcoded and explicitly allowed checksums should have been used
expect(result.fetchedChecksums).toBe(false)
expect(result.toDisplayString()).toBe(
'✓ Found known Gradle Wrapper JAR files:\n' +
' e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 data/invalid/gradle-wrapper.jar\n' +
' e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 data/invalid/gradlе-wrapper.jar\n' + // homoglyph
' 3888c76faa032ea8394b8a54e04ce2227ab1f4be64f65d450f8509fe112d38ce data/valid/gradle-wrapper.jar'
)
})
test('succeeds if all found wrapper jars are previously valid', async () => {
const result = await validate.findInvalidWrapperJars(baseDir, false, [], [
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',
'3888c76faa032ea8394b8a54e04ce2227ab1f4be64f65d450f8509fe112d38ce'
])
expect(result.isValid()).toBe(true)
// Only hardcoded and explicitly allowed checksums should have been used
expect(result.fetchedChecksums).toBe(false)
expect(result.toDisplayString()).toBe(
'✓ Found known Gradle Wrapper JAR files:\n' +
' e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 data/invalid/gradle-wrapper.jar\n' +
' e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 data/invalid/gradlе-wrapper.jar\n' + // homoglyph
' 3888c76faa032ea8394b8a54e04ce2227ab1f4be64f65d450f8509fe112d38ce data/valid/gradle-wrapper.jar'
)
})
test('succeeds if all found wrapper jars are valid (and checksums are fetched from Gradle API)', async () => {
const knownValidChecksums = new WrapperChecksums()
const result = await validate.findInvalidWrapperJars(
baseDir,
false,
['e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'],
[],
knownValidChecksums
)
console.log(`fetchedChecksums = ${result.fetchedChecksums}`)
expect(result.isValid()).toBe(true)
// Should have fetched checksums because no known checksums were provided
expect(result.fetchedChecksums).toBe(true)
expect(result.toDisplayString()).toBe(
'✓ Found known Gradle Wrapper JAR files:\n' +
' e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 data/invalid/gradle-wrapper.jar\n' +
' e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 data/invalid/gradlе-wrapper.jar\n' + // homoglyph
' 3888c76faa032ea8394b8a54e04ce2227ab1f4be64f65d450f8509fe112d38ce data/valid/gradle-wrapper.jar'
)
})
test('fails if invalid wrapper jars are found', async () => {
const result = await validate.findInvalidWrapperJars(baseDir, false, [])
expect(result.isValid()).toBe(false)
expect(result.valid).toEqual([
new validate.WrapperJar(
'data/valid/gradle-wrapper.jar',
'3888c76faa032ea8394b8a54e04ce2227ab1f4be64f65d450f8509fe112d38ce'
)
])
expect(result.invalid).toEqual([
new validate.WrapperJar(
'data/invalid/gradle-wrapper.jar',
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
),
new validate.WrapperJar(
'data/invalid/gradlе-wrapper.jar', // homoglyph
'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
)
])
expect(result.toDisplayString()).toBe(
'✗ Found unknown Gradle Wrapper JAR files:\n' +
' e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 data/invalid/gradle-wrapper.jar\n' +
' e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 data/invalid/gradlе-wrapper.jar\n' + // homoglyph
'✓ Found known Gradle Wrapper JAR files:\n' +
' 3888c76faa032ea8394b8a54e04ce2227ab1f4be64f65d450f8509fe112d38ce data/valid/gradle-wrapper.jar'
)
})
test('can save and load checksums', async () => {
const cacheDir = path.join(tmpDir, 'wrapper-validation-cache')
fs.rmSync(cacheDir, {recursive: true, force: true})
const checksumCache = new ChecksumCache(cacheDir)
expect(checksumCache.load()).toEqual([])
checksumCache.save(['123', '456'])
expect(checksumCache.load()).toEqual(['123', '456'])
expect(fs.existsSync(cacheDir)).toBe(true)
})