├── settings.gradle.kts ├── .gitignore ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── src └── main │ └── kotlin │ └── com │ └── bnorm │ └── robocode │ ├── sf │ ├── RssItem.kt │ ├── RssChannel.kt │ ├── RssFeed.kt │ └── SourceForge.kt │ ├── RobocodeRobot.kt │ ├── RobocodeExtension.kt │ ├── RobocodeDownload.kt │ └── RobocodePlugin.kt ├── .github └── workflows │ └── publish.yml ├── gradlew.bat ├── README.md └── gradlew /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "robocode-gradle-plugin" 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Gradle 2 | build/ 3 | .gradle/ 4 | 5 | # IntelliJ 6 | *.iml 7 | .idea 8 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bnorm/robocode-gradle-plugin/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /src/main/kotlin/com/bnorm/robocode/sf/RssItem.kt: -------------------------------------------------------------------------------- 1 | package com.bnorm.robocode.sf 2 | 3 | internal data class RssItem( 4 | val title: String, 5 | val link: String 6 | ) 7 | -------------------------------------------------------------------------------- /src/main/kotlin/com/bnorm/robocode/RobocodeRobot.kt: -------------------------------------------------------------------------------- 1 | package com.bnorm.robocode 2 | 3 | data class RobocodeRobot( 4 | val name: String 5 | ) { 6 | lateinit var classPath: String 7 | var version: String? = null 8 | var description: String? = null 9 | } 10 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip 4 | networkTimeout=10000 5 | zipStoreBase=GRADLE_USER_HOME 6 | zipStorePath=wrapper/dists 7 | -------------------------------------------------------------------------------- /src/main/kotlin/com/bnorm/robocode/sf/RssChannel.kt: -------------------------------------------------------------------------------- 1 | package com.bnorm.robocode.sf 2 | 3 | import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper 4 | import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty 5 | 6 | internal data class RssChannel( 7 | val title: String, 8 | @JacksonXmlElementWrapper(useWrapping = false) 9 | @JacksonXmlProperty(localName = "item") 10 | val items: List 11 | ) 12 | -------------------------------------------------------------------------------- /src/main/kotlin/com/bnorm/robocode/sf/RssFeed.kt: -------------------------------------------------------------------------------- 1 | package com.bnorm.robocode.sf 2 | 3 | import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper 4 | import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty 5 | import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement 6 | 7 | @JacksonXmlRootElement(localName = "rss") 8 | internal data class RssFeed( 9 | @JacksonXmlElementWrapper(useWrapping = false) 10 | @JacksonXmlProperty(localName = "channel") 11 | val channels: List 12 | ) 13 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish Plugin 2 | 3 | on: 4 | push: 5 | tags: 6 | - "v*.*.*" 7 | 8 | env: 9 | GRADLE_OPTS: "-Dorg.gradle.jvmargs=-Xmx4g -Dorg.gradle.daemon=false -Dkotlin.incremental=false" 10 | 11 | jobs: 12 | publish: 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - uses: actions/checkout@v3 17 | - uses: gradle/wrapper-validation-action@v1 18 | 19 | - name: Configure JDK 20 | uses: actions/setup-java@v3 21 | with: 22 | distribution: 'zulu' 23 | java-version: 11 24 | 25 | - name: Build Project 26 | uses: gradle/gradle-build-action@v2 27 | env: 28 | GRADLE_PUBLISH_KEY: ${{ secrets.GRADLE_PUBLISH_KEY }} 29 | GRADLE_PUBLISH_SECRET: ${{ secrets.GRADLE_PUBLISH_SECRET }} 30 | with: 31 | arguments: publishPlugins 32 | -------------------------------------------------------------------------------- /src/main/kotlin/com/bnorm/robocode/sf/SourceForge.kt: -------------------------------------------------------------------------------- 1 | package com.bnorm.robocode.sf 2 | 3 | import com.fasterxml.jackson.databind.DeserializationFeature 4 | import com.fasterxml.jackson.dataformat.xml.XmlMapper 5 | import com.fasterxml.jackson.module.kotlin.KotlinModule 6 | import okhttp3.OkHttpClient 7 | import okhttp3.Request 8 | import okio.BufferedSource 9 | 10 | internal object SourceForge { 11 | private val client = OkHttpClient() 12 | private val mapper = XmlMapper().apply { 13 | disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) 14 | registerModule(KotlinModule()) 15 | } 16 | 17 | private const val SOURCEFORGE_ROBOCODE_RSS = "https://sourceforge.net/projects/robocode/rss?limit=2" 18 | private val ROBOCODE_FILE_REGEX = "/robocode/([0-9.]+)/robocode-([0-9.]+)-setup.jar".toRegex() 19 | 20 | private fun downloadLink(version: String) = 21 | "https://sourceforge.net/projects/robocode/files/robocode/$version/robocode-$version-setup.jar/download" 22 | 23 | fun download(version: String): BufferedSource { 24 | val request = Request.Builder().get().url(downloadLink(version)).build() 25 | val response = client.newCall(request).execute() 26 | if (!response.isSuccessful) error("") 27 | return response.body!!.source() 28 | } 29 | 30 | fun findLatestVersion(): String { 31 | val request = Request.Builder().get().url(SOURCEFORGE_ROBOCODE_RSS).build() 32 | val response = client.newCall(request).execute() 33 | if (!response.isSuccessful) error("") 34 | val feed = mapper.readValue(response.body!!.string(), RssFeed::class.java) 35 | val channel = feed.channels.firstOrNull { it.title == "Robocode" } ?: error("") 36 | val item = channel.items 37 | .mapNotNull { ROBOCODE_FILE_REGEX.matchEntire(it.title) } 38 | .firstOrNull() ?: error("") 39 | return item.destructured.component1() 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/kotlin/com/bnorm/robocode/RobocodeExtension.kt: -------------------------------------------------------------------------------- 1 | package com.bnorm.robocode 2 | 3 | import com.bnorm.robocode.sf.SourceForge 4 | import org.gradle.api.Action 5 | import org.gradle.api.NamedDomainObjectContainer 6 | import org.gradle.api.file.Directory 7 | import org.gradle.api.file.ProjectLayout 8 | import org.gradle.api.model.ObjectFactory 9 | import org.gradle.api.provider.ProviderFactory 10 | import org.gradle.internal.os.OperatingSystem 11 | import org.gradle.kotlin.dsl.domainObjectContainer 12 | import org.gradle.kotlin.dsl.getValue 13 | import org.gradle.kotlin.dsl.property 14 | import org.gradle.kotlin.dsl.provideDelegate 15 | import org.gradle.kotlin.dsl.setValue 16 | import java.io.File 17 | 18 | open class RobocodeExtension( 19 | objects: ObjectFactory, 20 | layout: ProjectLayout, 21 | providerFactory: ProviderFactory 22 | ) { 23 | var download: Boolean by objects.property().apply { 24 | // Download Robocode by default to make it easier for CI/CD environments 25 | convention(true) 26 | } 27 | 28 | var downloadVersion: String by objects.property().apply { 29 | // Download the latest version of Robocode by default 30 | // TODO What if a connection to SourceForge cannot be made? 31 | // - Most importantly, a download of Robocode should continue to work. 32 | convention(providerFactory.provider { SourceForge.findLatestVersion() }) 33 | } 34 | 35 | internal var downloadDir: Directory by objects.directoryProperty().apply { 36 | // Default directory is outside build directory to avoid a clean clearing robot cache 37 | convention(layout.projectDirectory.dir(".robocode")) 38 | } 39 | 40 | var installDir: Directory by objects.directoryProperty().apply { 41 | val os = OperatingSystem.current() 42 | val robocodeHomeDir = if (os.isWindows) { 43 | providerFactory.provider { File("/") /* C:\ directory */ } 44 | .map { File(it, "robocode") } 45 | } else { 46 | providerFactory.systemProperty("user.home") 47 | .map { File(it, "robocode") } 48 | } 49 | // Default to the default install directory of Robocode 50 | convention(layout.dir(robocodeHomeDir)) 51 | } 52 | 53 | val robocodeDir: Directory get() = if (download) downloadDir else installDir 54 | 55 | val robots = objects.domainObjectContainer(RobocodeRobot::class) { RobocodeRobot(it) } 56 | fun robots(action: Action>) { 57 | action.execute(robots) 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 48 | echo. 49 | echo Please set the JAVA_HOME variable in your environment to match the 50 | echo location of your Java installation. 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 62 | echo. 63 | echo Please set the JAVA_HOME variable in your environment to match the 64 | echo location of your Java installation. 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /src/main/kotlin/com/bnorm/robocode/RobocodeDownload.kt: -------------------------------------------------------------------------------- 1 | package com.bnorm.robocode 2 | 3 | import com.bnorm.robocode.sf.SourceForge 4 | import okio.sink 5 | import okio.buffer 6 | import okio.source 7 | import org.gradle.api.DefaultTask 8 | import org.gradle.api.file.Directory 9 | import org.gradle.api.provider.Provider 10 | import org.gradle.api.tasks.Input 11 | import org.gradle.api.tasks.OutputDirectory 12 | import org.gradle.api.tasks.TaskAction 13 | import org.gradle.kotlin.dsl.getValue 14 | import org.gradle.kotlin.dsl.property 15 | import org.gradle.kotlin.dsl.provideDelegate 16 | import org.gradle.kotlin.dsl.setValue 17 | 18 | open class RobocodeDownload : DefaultTask() { 19 | @get:Input 20 | var downloadDir by project.objects.property() 21 | 22 | @get:Input 23 | var downloadVersion by project.objects.property() 24 | 25 | /* 26 | * The only output for this task to care about is the libs directory. Everything else *should* 27 | * be ignored so this task remains UP-TO-DATE even after running Robocode. 28 | */ 29 | // TODO Should we only care about specific files in the libs directory? Only Jar files? 30 | @get:OutputDirectory 31 | val libsDir: Provider 32 | get() = project.layout.dir(project.provider { project.file("$downloadDir/libs") }) 33 | 34 | @TaskAction 35 | fun perform() { 36 | val setupJar = project.file("$downloadDir/robocode-$downloadVersion-setup.jar") 37 | 38 | setupJar.parentFile.mkdirs() 39 | SourceForge.download(downloadVersion).use { source -> 40 | source.readAll(setupJar.sink()) 41 | } 42 | 43 | /* 44 | * Use copy and *not* sync to avoid deleting bot jar files which have been downloaded and 45 | * any configuration that has been changed by running Robocode. 46 | */ 47 | project.copy { 48 | from(project.zipTree(setupJar)) 49 | into(downloadDir) 50 | } 51 | 52 | /* 53 | * Automatically add the bot 'bin' directory to the development path of Robocode. This 54 | * avoids needing to manually configure the directory the first time Robocode is installed. 55 | */ 56 | val propertiesFile = project.file("$downloadDir/config/robocode.properties") 57 | propertiesFile.parentFile.mkdirs() 58 | 59 | val properties = if (!propertiesFile.exists()) emptyList() 60 | else propertiesFile.source().buffer().readUtf8().split("\n") 61 | 62 | val devPath = "${project.buildDir}/robocode/robots/bin" 63 | propertiesFile.sink().buffer().use { sink -> 64 | var foundDevPath = false 65 | for (property in properties) { 66 | sink.writeUtf8(property) 67 | if ("robocode.options.development.path=" in property) { 68 | foundDevPath = true 69 | if (devPath !in property) { 70 | sink.writeUtf8(",").writeUtf8(devPath) 71 | } 72 | } 73 | sink.writeUtf8("\n") 74 | } 75 | if (!foundDevPath) { 76 | sink.writeUtf8("robocode.options.development.path=$devPath\n") 77 | } 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # robocode-gradle-plugin 2 | 3 | > Build the best... 4 | 5 | [Gradle] plugin for building (and running) bots for [Robocode]. To use, add the 6 | [latest version of the plugin][com.bnorm.robocode] to a project. 7 | 8 | ```kotlin 9 | plugins { 10 | id("com.bnorm.robocode") version "0.2.0" 11 | } 12 | ``` 13 | 14 | Robocode doesn't natively allow robots to depend on third-party jars, but this 15 | plugin uses the [Shadow] Gradle plugin to combine everything into a single jar 16 | to work around this problem. 17 | 18 | # Robots 19 | 20 | Robots can be configured via the plugin extension. Multiple robots can be 21 | configured if desired. 22 | 23 | ```kotlin 24 | robocode { 25 | robots { 26 | register("Name") { 27 | classPath = "package.Name" 28 | version = "1.0" 29 | description = "Description" 30 | } 31 | } 32 | } 33 | ``` 34 | 35 | For each added robot, a task is added for building a jar file which can be 36 | published for others to use. For example, given a robot with the name of 37 | `Name`, a task named `robotNameJar` will be available which outputs to 38 | `$buildDir/robocode/robots/Name/Name_1.0.jar`. 39 | 40 | For robot development, a task named `robotBin` is available which outputs all 41 | class files needed to run the robot via Robocode. This task can be run with 42 | Gradle continuous mode to constantly build all robots. 43 | 44 | ```shell 45 | $ ./gradlew robotBin --continuous 46 | ``` 47 | 48 | # Robocode 49 | 50 | A dependency on the `robocode.jar` file is automatically added to the 51 | `implementation` configuration by the plugin. To achieve this, the file must 52 | already exist in an existing installed version of Robocode or be downloaded by 53 | the plugin. If this behavior is not the desired, use the following configuration 54 | options available in the plugin extension. 55 | 56 | ```kotlin 57 | robocode { 58 | download = true // default - if Robocode should be downloaded, otherwise the installDir is used 59 | downloadVersion = // default - version of Robocode to download 60 | downloadDir = layout.projectDirectory.dir(".robocode") // default - where Robocode should be downloaded 61 | installDir = // default - the location where Robocode is installed 62 | } 63 | ``` 64 | 65 | When Robocode is downloaded, it will automatically add the development output 66 | folder to the Robocode configuration. This allows Robocode to automatically use 67 | the development build of robots. 68 | 69 | Also, because the plugin knows the location of a Robocode installation, either 70 | specified or downloaded, it means that Robocode can be run directly from Gradle. 71 | To do so, use the task `robocodeRun`. 72 | 73 | # Test Battles 74 | 75 | Much of robot development is running battles against other robots for testing. 76 | Because of this, the plugin makes all Robocode jar files available in a Gradle 77 | configuration called `robocodeRuntime`. Gradle can be configured to add a source 78 | set which extends from this configuration for running battles. 79 | 80 | ```kotlin 81 | val battles by sourceSets.registering 82 | 83 | val battlesImplementation by configurations.getting { 84 | extendsFrom(configurations.robocode.get()) 85 | } 86 | 87 | val battlesRuntimeOnly by configurations.getting { 88 | extendsFrom(configurations.robocodeRuntime.get()) 89 | } 90 | 91 | dependencies { 92 | // Use JUnit to run the battles as "tests" 93 | battlesImplementation("org.junit.jupiter:junit-jupiter-api:5.6.0") 94 | battlesRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.6.0") 95 | } 96 | 97 | val runBattles by project.tasks.registering(Test::class) { 98 | dependsOn("robotBin") 99 | 100 | description = "Runs Robocode battles" 101 | group = "battles" 102 | 103 | useJUnitPlatform() 104 | testClassesDirs = battles.get().output.classesDirs 105 | classpath = battles.get().runtimeClasspath 106 | } 107 | ``` 108 | 109 | [Gradle]: https://gradle.org/ 110 | [Robocode]: https://robocode.sourceforge.io/ 111 | [com.bnorm.robocode]: https://plugins.gradle.org/plugin/com.bnorm.robocode 112 | [Shadow]: https://imperceptiblethoughts.com/shadow/ 113 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 87 | 88 | # Use the maximum available, or set MAX_FD != -1 to use that value. 89 | MAX_FD=maximum 90 | 91 | warn () { 92 | echo "$*" 93 | } >&2 94 | 95 | die () { 96 | echo 97 | echo "$*" 98 | echo 99 | exit 1 100 | } >&2 101 | 102 | # OS specific support (must be 'true' or 'false'). 103 | cygwin=false 104 | msys=false 105 | darwin=false 106 | nonstop=false 107 | case "$( uname )" in #( 108 | CYGWIN* ) cygwin=true ;; #( 109 | Darwin* ) darwin=true ;; #( 110 | MSYS* | MINGW* ) msys=true ;; #( 111 | NONSTOP* ) nonstop=true ;; 112 | esac 113 | 114 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 115 | 116 | 117 | # Determine the Java command to use to start the JVM. 118 | if [ -n "$JAVA_HOME" ] ; then 119 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 120 | # IBM's JDK on AIX uses strange locations for the executables 121 | JAVACMD=$JAVA_HOME/jre/sh/java 122 | else 123 | JAVACMD=$JAVA_HOME/bin/java 124 | fi 125 | if [ ! -x "$JAVACMD" ] ; then 126 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 127 | 128 | Please set the JAVA_HOME variable in your environment to match the 129 | location of your Java installation." 130 | fi 131 | else 132 | JAVACMD=java 133 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 134 | 135 | Please set the JAVA_HOME variable in your environment to match the 136 | location of your Java installation." 137 | fi 138 | 139 | # Increase the maximum file descriptors if we can. 140 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 141 | case $MAX_FD in #( 142 | max*) 143 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 144 | # shellcheck disable=SC3045 145 | MAX_FD=$( ulimit -H -n ) || 146 | warn "Could not query maximum file descriptor limit" 147 | esac 148 | case $MAX_FD in #( 149 | '' | soft) :;; #( 150 | *) 151 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 152 | # shellcheck disable=SC3045 153 | ulimit -n "$MAX_FD" || 154 | warn "Could not set maximum file descriptor limit to $MAX_FD" 155 | esac 156 | fi 157 | 158 | # Collect all arguments for the java command, stacking in reverse order: 159 | # * args from the command line 160 | # * the main class name 161 | # * -classpath 162 | # * -D...appname settings 163 | # * --module-path (only if needed) 164 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 165 | 166 | # For Cygwin or MSYS, switch paths to Windows format before running java 167 | if "$cygwin" || "$msys" ; then 168 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 169 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 170 | 171 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 172 | 173 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 174 | for arg do 175 | if 176 | case $arg in #( 177 | -*) false ;; # don't mess with options #( 178 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 179 | [ -e "$t" ] ;; #( 180 | *) false ;; 181 | esac 182 | then 183 | arg=$( cygpath --path --ignore --mixed "$arg" ) 184 | fi 185 | # Roll the args list around exactly as many times as the number of 186 | # args, so each arg winds up back in the position where it started, but 187 | # possibly modified. 188 | # 189 | # NB: a `for` loop captures its iteration list before it begins, so 190 | # changing the positional parameters here affects neither the number of 191 | # iterations, nor the values presented in `arg`. 192 | shift # remove old arg 193 | set -- "$@" "$arg" # push replacement arg 194 | done 195 | fi 196 | 197 | 198 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 199 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 200 | 201 | # Collect all arguments for the java command; 202 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 203 | # shell script including quotes and variable substitutions, so put them in 204 | # double quotes to make sure that they get re-expanded; and 205 | # * put everything else in single quotes, so that it's not re-expanded. 206 | 207 | set -- \ 208 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 209 | -classpath "$CLASSPATH" \ 210 | org.gradle.wrapper.GradleWrapperMain \ 211 | "$@" 212 | 213 | # Stop when "xargs" is not available. 214 | if ! command -v xargs >/dev/null 2>&1 215 | then 216 | die "xargs is not available" 217 | fi 218 | 219 | # Use "xargs" to parse quoted args. 220 | # 221 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 222 | # 223 | # In Bash we could simply go: 224 | # 225 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 226 | # set -- "${ARGS[@]}" "$@" 227 | # 228 | # but POSIX shell has neither arrays nor command substitution, so instead we 229 | # post-process each arg (as a line of input to sed) to backslash-escape any 230 | # character that might be a shell metacharacter, then use eval to reverse 231 | # that process (while maintaining the separation between arguments), and wrap 232 | # the whole thing up as a single "set" statement. 233 | # 234 | # This will of course break if any of these variables contains a newline or 235 | # an unmatched quote. 236 | # 237 | 238 | eval "set -- $( 239 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 240 | xargs -n1 | 241 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 242 | tr '\n' ' ' 243 | )" '"$@"' 244 | 245 | exec "$JAVACMD" "$@" 246 | -------------------------------------------------------------------------------- /src/main/kotlin/com/bnorm/robocode/RobocodePlugin.kt: -------------------------------------------------------------------------------- 1 | package com.bnorm.robocode 2 | 3 | import com.github.jengelman.gradle.plugins.shadow.ShadowPlugin 4 | import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar 5 | import org.gradle.api.Plugin 6 | import org.gradle.api.Project 7 | import org.gradle.api.plugins.JavaLibraryPlugin 8 | import org.gradle.api.tasks.JavaExec 9 | import org.gradle.api.tasks.SourceSetContainer 10 | import org.gradle.api.tasks.Sync 11 | import org.gradle.kotlin.dsl.apply 12 | import org.gradle.kotlin.dsl.create 13 | import org.gradle.kotlin.dsl.dependencies 14 | import org.gradle.kotlin.dsl.getValue 15 | import org.gradle.kotlin.dsl.named 16 | import org.gradle.kotlin.dsl.provideDelegate 17 | import org.gradle.kotlin.dsl.register 18 | import org.gradle.kotlin.dsl.registering 19 | import org.gradle.kotlin.dsl.the 20 | 21 | class RobocodePlugin : Plugin { 22 | override fun apply(target: Project) { 23 | with(target) { 24 | apply() 25 | apply() 26 | 27 | val extension = extensions.create("robocode") 28 | val robocodeBuildDir = project.layout.buildDirectory.dir("robocode") 29 | 30 | /* 31 | * Create 2 configurations `robocode` and `robocodeRuntime`. The robocode configuration 32 | * will depend only on the robocode.jar file. This allows bots to be built and for a 33 | * task which can run Robocode from the install directory. The robocodeRuntime 34 | * configuration is available to extend from if needed for running battles from a unit 35 | * or integration test. 36 | */ 37 | val robocode by configurations.registering 38 | val robocodeRuntime by configurations.registering 39 | dependencies { 40 | // Add only the robocode jar for building bots 41 | robocode.get().invoke(files(extension.robocodeDir.dir("libs").file("robocode.jar"))) 42 | // Add the entire libs directory for running battles 43 | robocodeRuntime.get().invoke(extension.robocodeDir.dir("libs").asFileTree) 44 | } 45 | configurations.named("implementation") { extendsFrom(robocode.get()) } 46 | 47 | /* 48 | * Task which downloads and unpacks the specified version (latest by default) of 49 | * Robocode to a project level directory. This bootstraps the project which everything 50 | * required to build a bot in a CI/CD environment. 51 | */ 52 | val robocodeDownload by tasks.registering(RobocodeDownload::class) { 53 | group = "robocode" 54 | 55 | enabled = extension.download 56 | downloadDir = extension.downloadDir.toString() 57 | downloadVersion = extension.downloadVersion 58 | } 59 | 60 | /* 61 | * Make compilation depend on downloading Robocode so the robocode.jar dependency is 62 | * available. 63 | */ 64 | // TODO Is there a better way to do this? Make configuration resolution dependent on the task? 65 | tasks.named("compileJava").configure { dependsOn(robocodeDownload) } 66 | plugins.withId("org.jetbrains.kotlin.jvm") { 67 | tasks.named("compileKotlin").configure { dependsOn(robocodeDownload) } 68 | } 69 | 70 | /* 71 | * Task for running Robocode with Gradle. This will either run the downloaded version 72 | * or the locally installed version depending on what is configured. 73 | */ 74 | tasks.register("robocodeRun") { 75 | group = "robocode" 76 | 77 | dependsOn(robocodeDownload) 78 | 79 | workingDir(extension.robocodeDir) 80 | classpath(robocode.get().files) 81 | mainClass.set("robocode.Robocode") 82 | } 83 | 84 | /* 85 | * ShadowJar for bundling compiled and dependency class files into a single jar file. 86 | * Robocode requires a single jar file contain no other jar files to run a bot. This 87 | * works around the natural inability of Robocode to allow dependencies. 88 | */ 89 | val shadowJar by tasks.named("shadowJar") { 90 | excludeRobocode() // Exclude robocode.jar dependency 91 | } 92 | 93 | /* 94 | * Extract the ShadowJar into a 'bin' directory to be loaded into Robocode for active 95 | * development. Robocode allows a local build directory to be indexed for bots, this 96 | * makes sure all dependency class files are present in the output. 97 | */ 98 | tasks.register("robotBin") { 99 | group = "robocode" 100 | 101 | dependsOn(shadowJar) 102 | from(zipTree(shadowJar.archiveFile)) 103 | into(robocodeBuildDir.map { it.dir("robots/bin") }) 104 | } 105 | 106 | afterEvaluate { 107 | /* 108 | * Convenience task for building all publishable bot jar files. 109 | */ 110 | val robotJars by tasks.registering { 111 | group = "robocode" 112 | } 113 | tasks.named("assemble").configure { dependsOn(robotJars) } 114 | 115 | /* 116 | * Plugin allows multiple bots to be packaged from the same source set. Go through 117 | * each bot specified and create the required tasks. 118 | */ 119 | for (robot in extension.robots) { 120 | val robotBuildDir = robocodeBuildDir.map { it.dir("robots/${robot.name}") } 121 | val robotResDir = robotBuildDir.map { it.dir("res") } 122 | 123 | /* 124 | * Task for creating the properties files required for each bot. This properties 125 | * file is only required when publishing the bot, and isn't required for local 126 | * development. 127 | */ 128 | val createVersion by tasks.register("robot${robot.name}Properties") { 129 | group = "robocode" 130 | 131 | val propertiesFileName = "${robot.classPath.replace('.', '/')}.properties" 132 | val propertiesFile = robotResDir.map { it.file(propertiesFileName) }.get().asFile 133 | val properties = mapOf( 134 | "robocode.version" to "1.9", 135 | "robot.name" to robot.name, 136 | "robot.classname" to robot.classPath, 137 | "robot.version" to robot.version, 138 | "robot.description" to robot.description 139 | ).filterValues { it != null } 140 | 141 | inputs.properties(properties) 142 | outputs.file(propertiesFile) 143 | 144 | doLast { 145 | propertiesFile.parentFile.mkdirs() 146 | propertiesFile.writeText(properties.entries 147 | .joinToString(separator = "\n") { (k, v) -> "$k=$v" }) 148 | } 149 | } 150 | 151 | /* 152 | * Build a publishable jar file for the bot. The jar file will contain the 153 | * generated properties file and all source code. Also use ShadowJar to bundle 154 | * all class files correct, including those from dependencies. 155 | */ 156 | val robotJar by tasks.register("robot${robot.name}Jar") { 157 | group = "robocode" 158 | 159 | dependsOn(createVersion) 160 | 161 | excludeRobocode() // Exclude robocode.jar dependency 162 | 163 | // Configure jar file name and output directory 164 | archiveFileName.set("${robot.classPath}_${robot.version}.jar") 165 | destinationDirectory.set(robotBuildDir) 166 | 167 | // Configure source code, properties file, and all class files 168 | val main by project.the().named("main") 169 | from(main.output) 170 | from(main.allSource) 171 | from(robotResDir) 172 | configurations = listOf(project.configurations.named("runtimeClasspath").get()) 173 | } 174 | robotJars.configure { dependsOn(robotJar) } 175 | } 176 | } 177 | } 178 | } 179 | 180 | /** 181 | * Exclude files which come from the robocode.jar file and other files which Robocode does not 182 | * like to appear in a jar file when importing. 183 | */ 184 | private fun ShadowJar.excludeRobocode() { 185 | exclude("/gl4java/**") 186 | exclude("/net/sf/robocode/**") 187 | exclude("/robocode/**") 188 | 189 | // Filter out other misc files Robocode doesn't like 190 | exclude("/META-INF/**/*.properties") 191 | exclude("/META-INF/**/*.xml") 192 | exclude("/META-INF/**/*.class") 193 | exclude("/META-INF/**/*.kotlin_module") 194 | } 195 | } 196 | --------------------------------------------------------------------------------