summaryrefslogtreecommitdiff
path: root/plugins/kotlin/jps/jps-plugin/tests/test/org/jetbrains/kotlin/jps/build/testingUtils.kt
blob: dd2d86dc42c63fa7b6e76127e0c34f72fc8d4e57 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.

package org.jetbrains.kotlin.jps.build

import com.intellij.openapi.util.io.FileUtil
import org.jetbrains.kotlin.cli.common.CompilerSystemProperties
import org.jetbrains.kotlin.compilerRunner.JpsKotlinCompilerRunner

inline fun withSystemProperty(property: String, newValue: String?, fn: ()->Unit) {
    val backup = System.getProperty(property)
    setOrClearSysProperty(property, newValue)

    try {
        fn()
    }
    finally {
        setOrClearSysProperty(property, backup)
    }
}


@Suppress("NOTHING_TO_INLINE")
inline fun setOrClearSysProperty(property: String, newValue: String?) {
    if (newValue != null) {
        System.setProperty(property, newValue)
    }
    else {
        System.clearProperty(property)
    }
}

fun withDaemon(fn: () -> Unit) {
    val daemonHome = FileUtil.createTempDirectory("daemon-home", "testJpsDaemonIC")

    withSystemProperty(CompilerSystemProperties.COMPILE_DAEMON_CUSTOM_RUN_FILES_PATH_FOR_TESTS.property, daemonHome.absolutePath) {
        withSystemProperty(CompilerSystemProperties.COMPILE_DAEMON_ENABLED_PROPERTY.property, "true") {
            try {
                fn()
            } finally {
                JpsKotlinCompilerRunner.shutdownDaemon()

                // Try to force directory deletion to prevent test failure later in tearDown().
                // Working Daemon can prevent folder deletion on Windows, because Daemon shutdown
                // is asynchronous.
                var attempts = 0
                daemonHome.deleteRecursively()
                while (daemonHome.exists() && attempts < 100) {
                    daemonHome.deleteRecursively()
                    attempts++
                    Thread.sleep(50)
                }

                if (daemonHome.exists()) {
                    error("Couldn't delete Daemon home directory")
                }
            }
        }
    }
}