LocalProperties.kt 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. * Copyright 2019-2022 Mamoe Technologies and contributors.
  3. *
  4. * 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
  5. * Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
  6. *
  7. * https://github.com/mamoe/mirai/blob/dev/LICENSE
  8. */
  9. import org.gradle.api.Project
  10. import java.util.*
  11. /*
  12. * Copyright 2019-2022 Mamoe Technologies and contributors.
  13. *
  14. * 此源代码的使用受 GNU AFFERO GENERAL PUBLIC LICENSE version 3 许可证的约束, 可以在以下链接找到该许可证.
  15. * Use of this source code is governed by the GNU AGPLv3 license that can be found through the following link.
  16. *
  17. * https://github.com/mamoe/mirai/blob/dev/LICENSE
  18. */
  19. object BuildSrcRootProjectHolder {
  20. lateinit var value: Project
  21. var lastUpdateTime: Long = 0
  22. }
  23. val rootProject: Project get() = BuildSrcRootProjectHolder.value
  24. fun <T> projectLazy(action: () -> T): Lazy<T> {
  25. val projLazy = object : Lazy<T> {
  26. private lateinit var delegate: Lazy<T>
  27. private var holdTime: Long = -1
  28. override val value: T
  29. get() {
  30. if (holdTime != BuildSrcRootProjectHolder.lastUpdateTime) {
  31. synchronized(this) {
  32. if (holdTime != BuildSrcRootProjectHolder.lastUpdateTime) {
  33. delegate = lazy(action)
  34. holdTime = BuildSrcRootProjectHolder.lastUpdateTime
  35. }
  36. }
  37. }
  38. return delegate.value
  39. }
  40. override fun isInitialized(): Boolean {
  41. if (!::delegate.isInitialized) return false
  42. if (holdTime == BuildSrcRootProjectHolder.lastUpdateTime) {
  43. return delegate.isInitialized()
  44. }
  45. return false
  46. }
  47. }
  48. return projLazy
  49. }
  50. private lateinit var localProperties: Properties
  51. private fun Project.loadLocalPropertiesIfAbsent() {
  52. if (::localProperties.isInitialized) return
  53. localProperties = Properties().apply {
  54. rootProject.projectDir.resolve("local.properties").takeIf { it.exists() }?.bufferedReader()?.use {
  55. load(it)
  56. }
  57. }
  58. }
  59. fun Project.getLocalProperty(name: String): String? {
  60. loadLocalPropertiesIfAbsent()
  61. return localProperties.getProperty(name)
  62. }
  63. fun Project.getLocalProperty(name: String, default: String): String {
  64. return getLocalProperty(name) ?: default
  65. }
  66. fun Project.getLocalProperty(name: String, default: Int): Int {
  67. return getLocalProperty(name)?.toInt() ?: default
  68. }
  69. fun Project.getLocalProperty(name: String, default: Boolean): Boolean {
  70. return getLocalProperty(name)?.toBoolean() ?: default
  71. }