diff --git a/.github/workflows/compatibility.yml b/.github/workflows/compatibility.yml new file mode 100644 index 00000000..eb1ab81b --- /dev/null +++ b/.github/workflows/compatibility.yml @@ -0,0 +1,29 @@ +name: Gradle and Java compatibility + +on: + push: + pull_request: + workflow_dispatch: + +permissions: + contents: read + +jobs: + compatibility: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + java: ['11', '14', '15', '24'] + name: Java ${{ matrix.java }} / Gradle 8.14.6 + steps: + - uses: actions/checkout@v7 + with: + submodules: recursive + - uses: actions/setup-java@v6 + with: + distribution: zulu + java-version: ${{ matrix.java }} + - uses: gradle/actions/setup-gradle@v6 + - run: ./gradlew build compileSamplesKotlin dokka --console=plain + - run: ./template/gradlew -p template --include-build "$PWD" tasks --all --console=plain diff --git a/.gitignore b/.gitignore index 573dff46..890510e0 100644 --- a/.gitignore +++ b/.gitignore @@ -11,3 +11,6 @@ misc/ # Ignore Gradle build output directory build + +# Kotlin compiler cache +.kotlin diff --git a/README.md b/README.md index 36af9d05..92d1e816 100644 --- a/README.md +++ b/README.md @@ -217,14 +217,15 @@ ftppass=password To use SubKt you will need: -* A [recent version of the JDK](https://www.oracle.com/uk/java/technologies/javase-downloads.html) +* A [JDK](https://www.oracle.com/java/technologies/downloads/), Java 11–24 (tested on Java 11, 14, 15, and 24). The included wrapper downloads Gradle 8.14.6 automatically. * [mkvmerge](https://mkvtoolnix.download/downloads.html) Ensure that both `java` and `mkvmerge` are available on the PATH. -Instructions for setting the PATH for JDK 14 on Windows can be found [here](https://docs.oracle.com/en/java/javase/14/install/installation-jdk-microsoft-windows-platforms.html#GUID-96EB3876-8C7A-4A25-9F3A-A2983FEC016A). +Set `JAVA_HOME` to your JDK installation and add its `bin` directory to the PATH. The same procedure can be used to add `mkvmerge` to the PATH; take note of where you installed/extracted it. -Download the [project template](https://github.com/Myaamori/SubKt/releases/download/0.1.19/subkt-template-0.1.19.zip) and place the files in the directory where you keep your project files. +Use the files in the [`template`](template) directory for new projects. Older release archives contain an obsolete Gradle wrapper and do not include this JDK upgrade. +Until this upgrade is released, use a local SubKt checkout as described below, passing `--include-build /absolute/path/to/SubKt` when running the template's wrapper. After you have modified `build.gradle.kts` and `sub.properties` as needed, you can run tasks using `gradlew`. For instance, to run the `mux` task for episode `03`, navigate to the same directory as the `build.gradle.kts` file in a terminal, and run `./gradlew mux.03`. On Windows, simply run `gradlew mux.03` from `cmd.exe`. @@ -232,15 +233,23 @@ On Windows, simply run `gradlew mux.03` from `cmd.exe`. **Note**: The first time you run `gradlew` may take some time as Gradle as well as all dependencies need to be downloaded. Future runs will be much quicker. +## Working alongside older projects + +The updated SubKt source and template use Gradle 8.14.6 on Java 11–24. Collaborators can run the same project's `gradlew` with different supported Java installations, without editing the wrapper configuration or installing another JDK. The wrapper downloads Gradle and verifies its SHA-256 checksum. + +Keep older projects on their existing SubKt and wrapper versions. For an updated project, copy both launchers and the `gradle/wrapper` directory from the template and select the updated SubKt source. Until this upgrade is released, use `--include-build` as described below; the template's default `subktVersion=0.1.19` still selects the old release. Gradle 8.14.6 cannot run on Java 25 or newer. + ## Building and using a local checkout Initialize the bundled torrent library, then build with the installed JDK: ```sh git submodule update --init --recursive -./gradlew build +./gradlew build compileSamplesKotlin ``` +Build plugins come from the Gradle Plugin Portal and dependencies from Maven Central; JCenter is no longer used. Java and Kotlin compile to Java 11 bytecode without downloading a separate JDK. Kotlin dependencies match the host Gradle's embedded Kotlin runtime, and Kotlin language/API version 2.0 keeps the plugin readable by Gradle 8.14's Kotlin DSL compiler. + To use this checkout from the included template: ```sh @@ -251,8 +260,17 @@ cd template For a template copied elsewhere, pass `--include-build /absolute/path/to/SubKt`. Gradle substitutes the local checkout for the `myaa:subkt` dependency, including uncommitted changes. Keep `subktRepo` and `subktVersion` configured: without `--include-build`, they select the Git repository and version as usual. +Run `./gradlew dokka` to generate Markdown API documentation in `build/dokka/gfm`. The checked-in documentation is not overwritten. + Projects using FTPS with `sslSessionReuse` enabled also need the two `--add-opens` JVM arguments in the template's `gradle.properties`. They allow the existing session-reuse implementation to access the JDK's SSL session cache on Java 17+. Merge these arguments into any existing `org.gradle.jvmargs` setting. +The compatibility workflow builds the plugin and samples, runs the functional tests, generates documentation, and loads the template on Java 11, 14, 15, and 24. Select a supported JDK with `JAVA_HOME`, then run: + +```sh +./gradlew build compileSamplesKotlin dokka +./template/gradlew -p template --include-build "$PWD" tasks --all +``` + # Manual A detailed description of the different tasks, functions and classes provided can be found in [the documentation](docs/subkt/index.md). diff --git a/build.gradle.kts b/build.gradle.kts index bc6093ee..169f8533 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,11 +1,12 @@ import java.net.URI -import java.net.URL -import org.jetbrains.dokka.gradle.DokkaTask +import org.jetbrains.dokka.gradle.formats.DokkaFormatPlugin +import org.jetbrains.kotlin.gradle.dsl.JvmTarget +import org.jetbrains.kotlin.gradle.dsl.KotlinVersion plugins { - kotlin("jvm") version "1.3.72" + kotlin("jvm") version "2.4.21" `java-gradle-plugin` - id("org.jetbrains.dokka") version "0.9.18" + id("org.jetbrains.dokka") version "2.2.0" } gradlePlugin { @@ -40,8 +41,9 @@ sourceSets { } dependencies { - implementation(kotlin("stdlib-jdk8", "1.3.72")) - implementation(kotlin("reflect", "1.3.72")) + // Use the host Gradle's Kotlin runtime, including 2.0.21 on Gradle 8.14. + implementation(kotlin("stdlib", embeddedKotlinVersion)) + implementation(kotlin("reflect", embeddedKotlinVersion)) implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.7") implementation(gradleApi()) implementation(gradleKotlinDsl()) @@ -61,46 +63,66 @@ dependencies { implementation("commons-codec:commons-codec:1.14") "samplesImplementation"(sourceSets["main"].output) + testImplementation(gradleTestKit()) + testImplementation(kotlin("test-junit", embeddedKotlinVersion)) } -tasks { - withType().configureEach { - kotlinOptions.jvmTarget = "1.8" - kotlinOptions.freeCompilerArgs += "-Xopt-in=kotlin.RequiresOptIn" +// Keep the plugin usable on Java 11–16 with Gradle 8.14 as well as modern Gradle. +java { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 +} + +kotlin { + compilerOptions { + jvmTarget.set(JvmTarget.JVM_11) + // Gradle 8.14's Kotlin DSL compiler must be able to read our metadata. + languageVersion.set(KotlinVersion.KOTLIN_2_0) + apiVersion.set(KotlinVersion.KOTLIN_2_0) } +} - val dokka by getting(DokkaTask::class) { - outputFormat = "gfm" - outputDirectory = "docs" +tasks.withType().configureEach { + options.release.set(11) +} - // configuration { - noStdlibLink = false - noJdkLink = false - jdkVersion = 9 - //platform = "JVM" +// Dokka v2 ships HTML/Javadoc formats; retain the existing Markdown output too. +abstract class DokkaGfmPlugin : DokkaFormatPlugin("gfm") +apply() - includes = listOf("src/docs/markdown/packages.md") - samples = listOf("src/samples/kotlin/tasks.kt") +dependencies { + add("dokkaGfmPlugin", "org.jetbrains.dokka:gfm-plugin:2.2.0") +} - externalDocumentationLink { - url = URL("https://docs.gradle.org/current/javadoc/") +dokka { + dokkaPublications.named("gfm") { + outputDirectory.set(layout.buildDirectory.dir("dokka/gfm")) + } + dokkaSourceSets.named("main") { + jdkVersion.set(11) + includes.from("src/docs/markdown/packages.md") + samples.from("src/samples/kotlin/tasks.kt") + externalDocumentationLinks.register("gradle") { + url.set(URI("https://docs.gradle.org/current/javadoc/")) + packageListUrl.set(URI("https://docs.gradle.org/current/javadoc/element-list")) } - - externalDocumentationLink { - url = URL("https://velocity.apache.org/engine/2.2/apidocs/") + externalDocumentationLinks.register("velocity") { + url.set(URI("https://velocity.apache.org/engine/2.2/apidocs/")) } - - packageOptions/*perPackageOption*/ { - prefix = "com.turn.ttorrent" - suppress = true + perPackageOption { + matchingRegex.set("com\\.turn\\.ttorrent.*") + suppress.set(true) } - - linkMapping { - // replace \ with / since only unix paths are allowed - dir = project.file("src/main/kotlin").absolutePath.replace('\\', '/') - url = "https://github.com/Myaamori/SubKt/blob/$version/src/main/kotlin" - suffix = "#L" + sourceLink { + localDirectory.set(file("src/main/kotlin")) + remoteUrl.set(URI("https://github.com/Myaamori/SubKt/blob/$version/src/main/kotlin")) + remoteLineSuffix.set("#L") } - // } } -} \ No newline at end of file +} + +tasks.register("dokka") { + group = "documentation" + description = "Generates Markdown API documentation." + dependsOn("dokkaGeneratePublicationGfm") +} diff --git a/gradle.properties b/gradle.properties index 55a902b4..98461f08 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1 +1,2 @@ org.gradle.warning.mode=all +org.jetbrains.dokka.experimental.gradle.pluginMode=V2Enabled diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 62d4c053..02f06ab2 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 622ab64a..f900c206 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,8 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip +distributionSha256Sum=7988ed071b2a07900e2ec715fca15c6ab72bce6db433af301fa7fa7e9407bd24 +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.6-bin.zip +networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index fbd7c515..23d15a93 100755 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ -#!/usr/bin/env sh +#!/bin/sh # -# Copyright 2015 the original author or authors. +# 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. @@ -15,81 +15,115 @@ # 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 UN*X -## +# +# 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 -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +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 -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# 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"' +# 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\n' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +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 - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +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 +CLASSPATH="\\\"\\\"" # 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" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -98,88 +132,120 @@ 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. + 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" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +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 -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -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" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi +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 - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + 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 - i=`expr $i + 1` + # 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 - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" +# 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 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" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# 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" "$@" diff --git a/gradlew.bat b/gradlew.bat index a9f778a7..5eed7ee8 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -13,8 +13,10 @@ @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 +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @@ -25,7 +27,8 @@ if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @@ -40,13 +43,13 @@ if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init +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. +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 @@ -54,49 +57,36 @@ goto fail set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe -if exist "%JAVA_EXE%" goto init +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. +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 -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - :execute @rem Setup the command line -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar +set CLASSPATH= @rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* :end @rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd +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! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 +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 diff --git a/src/main/kotlin/myaa/subkt/ass/parser.kt b/src/main/kotlin/myaa/subkt/ass/parser.kt index 18004fa2..ff54a429 100644 --- a/src/main/kotlin/myaa/subkt/ass/parser.kt +++ b/src/main/kotlin/myaa/subkt/ass/parser.kt @@ -757,9 +757,9 @@ enum class Collisions(val value: String) { class CollisionsSerializer : ASSSerializer { override fun deserialize(s: String) = - when (s.toLowerCase()) { - Collisions.NORMAL.value.toLowerCase() -> Collisions.NORMAL - Collisions.REVERSE.value.toLowerCase() -> Collisions.REVERSE + when (s.lowercase()) { + Collisions.NORMAL.value.lowercase() -> Collisions.NORMAL + Collisions.REVERSE.value.lowercase() -> Collisions.REVERSE else -> error("Invalid value for Collisions: $s") } diff --git a/src/main/kotlin/myaa/subkt/tasks/muxtask.kt b/src/main/kotlin/myaa/subkt/tasks/muxtask.kt index 212605c5..4cc3ec46 100644 --- a/src/main/kotlin/myaa/subkt/tasks/muxtask.kt +++ b/src/main/kotlin/myaa/subkt/tasks/muxtask.kt @@ -44,7 +44,7 @@ interface Filterable { * Filter files by file extension. Case-insensitive. */ fun PatternFilterable.includeExtensions(vararg extensions: String) { - include { it.file.extension.toLowerCase() in extensions } + include { it.file.extension.lowercase() in extensions } } /** @@ -972,7 +972,7 @@ open class Mux : PropertyTask() { // attachments toAttach.forEach { - val mime = mimeTypes[it.extension.toLowerCase()] + val mime = mimeTypes[it.extension.lowercase()] logger.lifecycle("Attaching ${it.name} (content-type: ${mime ?: "autodetected"})") mime?.let { yield("--attachment-mime-type") diff --git a/src/main/kotlin/myaa/subkt/tasks/tasks.kt b/src/main/kotlin/myaa/subkt/tasks/tasks.kt index d41f9a89..7416f779 100644 --- a/src/main/kotlin/myaa/subkt/tasks/tasks.kt +++ b/src/main/kotlin/myaa/subkt/tasks/tasks.kt @@ -1726,10 +1726,10 @@ private class SSLSessionReuseFTPSClient(implicit: Boolean) : FTPSClient(implicit method.setAccessible(true) method.invoke(cache, String.format("%s:%s", socket.getInetAddress() .hostName, socket.getPort().toString()) - .toLowerCase(Locale.ROOT), session) + .lowercase(Locale.ROOT), session) method.invoke(cache, String.format("%s:%s", socket.getInetAddress() .hostAddress, socket.getPort().toString()) - .toLowerCase(Locale.ROOT), session) + .lowercase(Locale.ROOT), session) } else { throw error("Invalid SSL Session") } diff --git a/src/main/kotlin/myaa/subkt/tasks/utils/fontvalidator.kt b/src/main/kotlin/myaa/subkt/tasks/utils/fontvalidator.kt index 2bc9a32f..989382ff 100644 --- a/src/main/kotlin/myaa/subkt/tasks/utils/fontvalidator.kt +++ b/src/main/kotlin/myaa/subkt/tasks/utils/fontvalidator.kt @@ -202,10 +202,10 @@ private class FontCollection(fontFiles: Iterable) { } } - val byFullName = fonts.flatMap { font -> font.exactNames.map { it.toLowerCase() to font } }.toMap() + val byFullName = fonts.flatMap { font -> font.exactNames.map { it.lowercase() to font } }.toMap() val byFamilyName = fonts - .flatMap { font -> font.families.map { it.toLowerCase() to font } } + .flatMap { font -> font.families.map { it.lowercase() to font } } .groupBy({ it.first }, { it.second }) private val cache = mutableMapOf() @@ -227,7 +227,7 @@ private class FontCollection(fontFiles: Iterable) { } fun match(state: State): FontMatch { - val s = state.copy(font = state.font.toLowerCase(), drawing = false) + val s = state.copy(font = state.font.lowercase(), drawing = false) return when (val f = cache[s]) { null -> { diff --git a/src/test/kotlin/myaa/subkt/GradleCompatibilityTest.kt b/src/test/kotlin/myaa/subkt/GradleCompatibilityTest.kt new file mode 100644 index 00000000..309ace1b --- /dev/null +++ b/src/test/kotlin/myaa/subkt/GradleCompatibilityTest.kt @@ -0,0 +1,143 @@ +package myaa.subkt + +import myaa.subkt.ass.ASSFile +import com.sun.net.httpserver.HttpServer +import org.gradle.testkit.runner.GradleRunner +import org.gradle.testkit.runner.TaskOutcome +import org.junit.Assume.assumeTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File +import java.net.InetSocketAddress +import java.util.Properties +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +class GradleCompatibilityTest { + @get:Rule + val temporaryFolder = TemporaryFolder() + + private fun project(script: String): File = temporaryFolder.newFolder().apply { + resolve("settings.gradle.kts").writeText(""" + rootProject.name = "compatibility-test" + check(JavaVersion.current().majorVersion == "${System.getProperty("java.specification.version")}") { + "The consumer build must run on the same JDK as the compatibility tests" + } + """.trimIndent()) + resolve("gradle.properties").writer().use { writer -> + Properties().apply { + setProperty("org.gradle.java.home", System.getProperty("java.home")) + }.store(writer, "Keep the consumer on the JDK being tested") + } + resolve("build.gradle.kts").writeText(""" + import myaa.subkt.tasks.* + plugins { id("myaa.subkt") } + $script + """.trimIndent()) + } + + private fun run(project: File, vararg tasks: String) = GradleRunner.create() + .withProjectDir(project) + .withPluginClasspath() + .withArguments(*tasks, "--stacktrace", "--console=plain") + .build() + + @Test + fun `subtitle task chain and torrent execute on the current JDK`() { + val project = project(""" + subs { + episodes("01") + release("TV") + merge { + from("dialogue.ass") { incrementLayer(10) } + } + swap { from(merge.item()) } + chapters { from(merge.item()) } + torrent { + from(swap.item()) + trackers("https://tracker.invalid/announce") + } + } + """.trimIndent()) + project.resolve("dialogue.ass").writeText(""" + [Script Info] + ScriptType: v4.00+ + PlayResX: 1920 + PlayResY: 1080 + + [V4+ Styles] + Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding + Style: Default,Arial,48,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2,0,2,10,10,10,1 + + [Events] + Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text + Dialogue: 0,0:00:01.00,0:00:03.00,Default,,0,0,0,,Karen{**-chan} + Comment: 0,0:00:05.00,0:00:06.00,Default,chptr,0,0,0,,Part A + """.trimIndent()) + + val result = run(project, "torrent.01", "chapters.01") + for (task in listOf("merge.01", "swap.01", "chapters.01", "torrent.01")) { + assertEquals(TaskOutcome.SUCCESS, result.task(":$task.TV")?.outcome, result.output) + } + val swapped = ASSFile(project.resolve("build/swap.01.TV.ass")) + assertEquals(10, swapped.events.lines.first().layer) + assertEquals("Karen{*}-chan{*}", swapped.events.lines.first().text) + assertTrue(project.resolve("build/chapters.01.TV.txt").readText().contains("CHAPTER02=00:00:05.000")) + assertTrue(project.resolve("build/torrent.01.TV.torrent").length() > 0) + + val rerun = run(project, "torrent.01", "chapters.01") + assertEquals(TaskOutcome.UP_TO_DATE, rerun.task(":merge.01.TV")?.outcome) + assertEquals(TaskOutcome.UP_TO_DATE, rerun.task(":swap.01.TV")?.outcome) + } + + @Test + fun `HTTP task runs with the Gradle Kotlin runtime`() { + val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0) + server.createContext("/test") { exchange -> + val response = "{\"ok\":true}".toByteArray() + exchange.responseHeaders.add("Content-Type", "application/json") + exchange.sendResponseHeaders(200, response.size.toLong()) + exchange.responseBody.use { it.write(response) } + } + server.start() + try { + val project = project(""" + val request by tasks.registering(HTTP::class) { + host("127.0.0.1") + https(false) + port(${server.address.port}) + endpoint("/test") + } + tasks.register("verifyResponse") { + dependsOn(request) + doLast { check(request.get().responseJson.asJsonObject["ok"].asBoolean) } + } + """.trimIndent()) + assertEquals(TaskOutcome.SUCCESS, run(project, "verifyResponse").task(":request")?.outcome) + } finally { + server.stop(0) + } + } + + @Test + fun `automation executes a subprocess through Gradle services`() { + assumeTrue("The fake Aegisub executable requires a POSIX shell", File("/bin/sh").exists()) + val project = project(""" + tasks.register("automate") { + aegisubCli(file("fake-aegisub").absolutePath) + from("input.ass") + out("output.ass") + macro("test macro") + } + """.trimIndent()) + // This fixture substitutes for Aegisub so the test needs no external installation. + project.resolve("fake-aegisub").apply { + writeText("#!/bin/sh\n[ \"${'$'}3\" = \"test macro\" ] || exit 1\ncp \"${'$'}1\" \"${'$'}2\"\n") + setExecutable(true) + } + project.resolve("input.ass").writeText("test subtitle") + assertEquals(TaskOutcome.SUCCESS, run(project, "automate").task(":automate")?.outcome) + assertEquals("test subtitle", project.resolve("output.ass").readText()) + } +} diff --git a/template/gradle/wrapper/gradle-wrapper.jar b/template/gradle/wrapper/gradle-wrapper.jar index 62d4c053..02f06ab2 100644 Binary files a/template/gradle/wrapper/gradle-wrapper.jar and b/template/gradle/wrapper/gradle-wrapper.jar differ diff --git a/template/gradle/wrapper/gradle-wrapper.properties b/template/gradle/wrapper/gradle-wrapper.properties index 622ab64a..f900c206 100644 --- a/template/gradle/wrapper/gradle-wrapper.properties +++ b/template/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,8 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip +distributionSha256Sum=7988ed071b2a07900e2ec715fca15c6ab72bce6db433af301fa7fa7e9407bd24 +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.6-bin.zip +networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/template/gradlew b/template/gradlew index fbd7c515..23d15a93 100755 --- a/template/gradlew +++ b/template/gradlew @@ -1,7 +1,7 @@ -#!/usr/bin/env sh +#!/bin/sh # -# Copyright 2015 the original author or authors. +# 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. @@ -15,81 +15,115 @@ # 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 UN*X -## +# +# 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 -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +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 -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# 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"' +# 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\n' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +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 - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +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 +CLASSPATH="\\\"\\\"" # 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" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -98,88 +132,120 @@ 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. + 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" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +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 -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -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" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi +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 - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + 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 - i=`expr $i + 1` + # 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 - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" +# 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 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" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# 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" "$@" diff --git a/template/gradlew.bat b/template/gradlew.bat index a9f778a7..5eed7ee8 100644 --- a/template/gradlew.bat +++ b/template/gradlew.bat @@ -13,8 +13,10 @@ @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 +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @@ -25,7 +27,8 @@ if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @@ -40,13 +43,13 @@ if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init +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. +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 @@ -54,49 +57,36 @@ goto fail set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe -if exist "%JAVA_EXE%" goto init +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. +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 -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* - :execute @rem Setup the command line -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar +set CLASSPATH= @rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* :end @rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd +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! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 +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