@@ -9,8 +9,10 @@ import com.amazonaws.services.dynamodbv2.local.server.DynamoDBProxyServer
99import com.google.devtools.ksp.gradle.KspTaskJvm
1010import com.google.devtools.ksp.gradle.KspTaskMetadata
1111import org.jetbrains.kotlin.gradle.tasks.KotlinCompilationTask
12+ import java.net.ServerSocket
1213import java.nio.file.Files
1314import java.nio.file.StandardCopyOption
15+ import kotlin.properties.Delegates
1416
1517description = " High level DynamoDbMapper client"
1618extra[" displayName" ] = " AWS :: SDK :: Kotlin :: HLL :: DynamoDbMapper"
@@ -128,29 +130,41 @@ if (project.NATIVE_ENABLED) {
128130}
129131
130132open class DynamoDbLocalInstance : DefaultTask () {
131- private val port = 44212 // Keep in sync with DdbLocalTest.kt
133+ private var port: Int by Delegates .notNull()
134+
135+ @OutputFile
136+ val portFile = project.objects.fileProperty()
132137
133138 @Internal
134139 var runner: DynamoDBProxyServer ? = null
135140 private set
136141
137142 @TaskAction
138143 fun exec () {
139- println (" Running DynamoDB local instance on port $port " )
144+ port = ServerSocket (0 ).use { it.localPort }
145+
146+ println (" Starting DynamoDB local instance on port $port " )
140147 runner = ServerRunner
141148 .createServerFromCommandLineArgs(arrayOf(" -inMemory" , " -port" , port.toString(), " -disableTelemetry" ))
142149 .also { it.start() }
150+
151+ portFile.asFile.get().writeText(port.toString())
143152 }
144153
145154 fun stop () {
155+ runCatching { portFile.asFile.get().delete() }.onFailure { t -> println (" Failed to delete $portFile : $t " ) }
156+
146157 runner?.let {
147158 println (" Stopping DynamoDB local instance on port $port " )
148159 it.stop()
149160 }
150161 }
151162}
152163
153- val startDdbLocal = task<DynamoDbLocalInstance >(" startDdbLocal" )
164+ val startDdbLocal = task<DynamoDbLocalInstance >(" startDdbLocal" ) {
165+ portFile.set(file(" build/ddblocal/port.info" )) // Keep in sync with DdbLocalTest.kt
166+ outputs.upToDateWhen { false } // Always run this task even if a portFile already exists
167+ }
154168
155169tasks.withType<Test > {
156170 dependsOn(startDdbLocal)
0 commit comments