All Downloads are FREE. Search and download functionalities are using the official Maven repository.

application.Watcher.kt Maven / Gradle / Ivy

There is a newer version: 1.3.39
Show newest version
package application

import `in`.specmatic.core.log.consoleLog
import `in`.specmatic.core.CONTRACT_EXTENSIONS
import `in`.specmatic.core.log.StringLog
import java.io.File
import java.nio.file.FileSystems
import java.nio.file.Path
import java.nio.file.StandardWatchEventKinds
import java.nio.file.WatchKey

class Watcher(private val contractPaths: List) {
    fun watchForChanges(restartServer: () -> Unit) {
        FileSystems.getDefault().newWatchService().use { watchService ->
            val paths: List = getPaths(contractPaths).toSet().toList().sorted().map { File(it).toPath() }

            paths.forEach { contractPath ->
                contractPath.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE)
            }

            var key: WatchKey
            while (watchService.take().also { key = it } != null) {
                key.reset()

                val events = key.pollEvents().joinToString(", ") { it.context().toString() }
                consoleLog(StringLog("""Detected event(s) for $events, restarting stub server."""))
                restartServer()
            }
        }
    }

    private fun getPaths(contractPaths: List): List {
        return contractPaths.map { File(it) }.flatMap {
            when {
                it.isFile && it.extension.lowercase() in CONTRACT_EXTENSIONS ->
                    listOf(it.absoluteFile.parentFile.path).plus(getPaths(listOf(dataDirOf(it))))
                it.isFile && it.extension.equals("yaml", ignoreCase = true) ->
                    listOf(it.absolutePath)
                it.isFile && it.extension.equals("json", ignoreCase = true) ->
                    listOf(it.absoluteFile.parentFile.path)
                it.isDirectory ->
                    listOf(it.absolutePath).plus(getPaths(it.listFiles()?.toList()?.map { file -> file.absolutePath } ?: emptyList()))
                else -> emptyList()
            }
        }
    }

    private fun dataDirOf(contractFile: File): String {
        return "${contractFile.absoluteFile.parent}/${contractFile.nameWithoutExtension}_data"
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy