Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

71.7 KB
Raw Blame
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
import com.github.gradle.node.NodeExtension
import com.github.gradle.node.NodePlugin
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import com.github.jengelman.gradle.plugins.shadow.transformers.CacheableTransformer
import com.github.jengelman.gradle.plugins.shadow.transformers.Transformer
import com.github.jengelman.gradle.plugins.shadow.transformers.TransformerContext
import com.github.jk1.license.filter.DependencyFilter
import com.github.jk1.license.filter.LicenseBundleNormalizer
import com.github.jk1.license.render.InventoryHtmlReportRenderer
import com.github.jk1.license.render.ReportRenderer
import com.github.vlsi.gradle.dsl.configureEach
import groovy.json.JsonSlurper
import net.ltgt.gradle.errorprone.errorprone
import org.apache.tools.zip.ZipEntry
import org.apache.tools.zip.ZipOutputStream
import org.gradle.api.attributes.java.TargetJvmVersion
import org.gradle.api.publish.maven.tasks.GenerateMavenPom
import org.gradle.api.publish.tasks.GenerateModuleMetadata
import org.gradle.api.services.BuildService
import org.gradle.api.services.BuildServiceParameters
import org.gradle.api.tasks.testing.logging.TestExceptionFormat
import org.gradle.internal.hash.ChecksumService
import org.gradle.internal.os.OperatingSystem
import org.gradle.kotlin.dsl.support.serviceOf
import org.w3c.dom.Element
import org.w3c.dom.Node
import java.io.IOException
import java.nio.ByteBuffer
import java.util.Locale
import java.util.zip.ZipFile
import javax.xml.parsers.DocumentBuilderFactory

Locale.setDefault(Locale.US)

abstract class SharedTestEnvironmentLock : BuildService<BuildServiceParameters.None>

plugins {
  `maven-publish`
  id("java")
  id("idea")
  id("jacoco")
  alias(libs.plugins.gradle.extensions)
  alias(libs.plugins.node) apply false
  alias(libs.plugins.shadow) apply false

  // Spotless version < 6.19.0 (https://github.com/diffplug/spotless/issues/1819) has an issue running against JDK21.
  if (JavaVersion.current() == JavaVersion.VERSION_17) {
    alias(libs.plugins.spotless)
  } else {
    throw GradleException(
      "The Gravitino Gradle toolchain currently does not support " +
        "Java version ${JavaVersion.current()}. Please use JDK version 17."
    )
  }

  alias(libs.plugins.publish)
  // Apply one top level rat plugin to perform any required license enforcement analysis
  alias(libs.plugins.rat)
  alias(libs.plugins.bom)
  alias(libs.plugins.dependencyLicenseReport)
  alias(libs.plugins.tasktree)
  alias(libs.plugins.errorprone)
}

val sharedTestEnvironmentLock = gradle.sharedServices.registerIfAbsent(
  "sharedTestEnvironmentLock",
  SharedTestEnvironmentLock::class
) {
  maxParallelUsages.set(1)
}

/** Packages the legal documents for one Maven artifact, retaining dependency provenance. */
@CacheableTask
abstract class GenerateJarLegalFiles : DefaultTask() {
  companion object {
    private const val LICENSE_INVENTORY = "\nBundled component licensing:\n"
    private const val NOTICE_INVENTORY = "\nBundled component notices:\n"
    private val noticeFileName = Regex("(?i)([A-Za-z0-9_]+-)*NOTICES?([.-].*)?")
    private val legalFileName = Regex(
      "(?i)([A-Za-z0-9_]+-)*(LICENSE|LICENCE|NOTICES?|COPYING|COPYRIGHT)(-[A-Za-z0-9_-]+)?(\\.(txt|md|markdown|adoc))?"
    )

    /** Selects legal resources without mistaking SDK models such as license-manager.json for licenses. */
    fun isLegalResource(path: String): Boolean =
      path == "about.html" || path.startsWith("about_files/") ||
        path.startsWith("licenses/") || path.startsWith("license/") ||
        path.startsWith("META-INF/licenses/") || path.startsWith("META-INF/license/") ||
        path.startsWith("META-INF/licenses-binary/") ||
        legalFileName.matches(path.substringAfterLast('/'))
  }

  @get:Internal
  abstract val templates: DirectoryProperty

  @get:InputFiles
  @get:PathSensitive(PathSensitivity.RELATIVE)
  val templateFiles: FileTree
    get() = templates.get().asFileTree

  @get:Input
  abstract val sourceNotices: ListProperty<String>

  @get:InputFiles
  @get:PathSensitive(PathSensitivity.NONE)
  abstract val dependencyJars: ConfigurableFileCollection

  @get:Input
  abstract val dependencyIds: MapProperty<String, String>

  @get:Input
  abstract val excludedGroups: SetProperty<String>

  @get:InputFiles
  @get:PathSensitive(PathSensitivity.RELATIVE)
  abstract val javadocFiles: ConfigurableFileCollection

  @get:OutputFile
  abstract val outputArchive: RegularFileProperty

  init {
    sourceNotices.convention(emptyList())
    dependencyIds.convention(emptyMap())
    excludedGroups.convention(emptySet())
  }

  @TaskAction
  fun generate() {
    val directory = templates.get().asFile
    val ids = dependencyIds.get()
    val excluded = excludedGroups.get()
    // ByteBuffer compares byte contents, so identical documents are retained only once.
    val documents = sortedMapOf<String, LinkedHashSet<ByteBuffer>>()
    fun add(path: String, bytes: ByteArray) {
      require(!path.startsWith('/') && path.split('/').none { it == ".." }) {
        "Invalid legal resource path: $path"
      }
      val group = path.removePrefix("META-INF/licenses/").substringBefore('/')
      if (path.startsWith("META-INF/licenses/") && group in excluded) return
      documents.getOrPut(path) { linkedSetOf() }.add(ByteBuffer.wrap(bytes))
    }
    val overrides = mutableMapOf<String, String>()
    directory.resolve("dependencies.txt").readLines()
      .filter { it.isNotBlank() && !it.startsWith('#') }
      .forEach { line ->
        val fields = line.split('=', limit = 2)
        require(fields.size == 2) { "Invalid Maven legal supplement: $line" }
        require(overrides.put(fields[0], fields[1]) == null) { "Duplicate Maven legal supplement: ${fields[0]}" }
      }
    fun supplement(id: String): String {
      val parts = id.split('/')
      val coordinate = "${parts[0]}:${parts[1]}"
      val selected = overrides["$coordinate:${parts[2]}"] ?: overrides[coordinate]
      require(selected != null || overrides.keys.none { it.startsWith("$coordinate:") }) {
        "Unaudited Maven legal supplement version: $coordinate:${parts[2]} in $path. Review dependencies.txt and upstream legal documents."
      }
      return selected ?: overrides["${parts[0]}:*"] ?: ""
    }
    val dependencies = dependencyJars.files.map { jar ->
      val id = requireNotNull(ids[jar.name]) { "Missing Maven coordinate for bundled artifact: $jar" }
      id to jar
    }
    dependencies.sortedBy { it.first }.forEach { (id, jar) ->
      val coordinate = id.split('/').take(2).joinToString(":")
      val group = id.substringBefore('/')
      if (group in excluded) return@forEach
      val prefix = "META-INF/licenses/$id/"
      var hasContent = false
      ZipFile(jar).use { archive ->
        hasContent = archive.entries().asSequence().any {
          !it.isDirectory && (
            (!it.name.startsWith("META-INF/") && !GenerateJarLegalFiles.isLegalResource(it.name)) ||
              it.name.startsWith("META-INF/native/") || it.name.startsWith("META-INF/versions/")
            )
        }
        archive.entries().asSequence().filter { !it.isDirectory && GenerateJarLegalFiles.isLegalResource(it.name) }
          .sortedBy { it.name }.forEach { entry ->
            // Do not nest documents again when shading an already assembled Gravitino runtime.
            val path = if (group == "org.apache.gravitino" && entry.name.startsWith("META-INF/licenses/")) {
              entry.name
            } else {
              prefix + entry.name
            }
            archive.getInputStream(entry).use { input ->
              val bytes = input.readBytes()
              // Regenerate nested inventories after exclusions instead of propagating stale entries.
              val content = when {
                group == "org.apache.gravitino" && entry.name == "META-INF/LICENSE" ->
                  bytes.toString(Charsets.UTF_8).substringBefore(LICENSE_INVENTORY).toByteArray(Charsets.UTF_8)
                group == "org.apache.gravitino" && entry.name == "META-INF/NOTICE" ->
                  bytes.toString(Charsets.UTF_8).substringBefore(NOTICE_INVENTORY).toByteArray(Charsets.UTF_8)
                else -> bytes
              }
              add(path, content)
            }
          }
      }
      if (hasContent) {
        val selected = supplement(id)
        selected.substringBefore('|').split(',').map { it.trim() }.filter { it.isNotEmpty() }.forEach { name ->
          val supplement = directory.resolve(name)
          require(supplement.isFile) { "Missing Maven legal supplement for $coordinate: $name" }
          add(prefix + name, supplement.readBytes())
        }
        require(selected.isEmpty() || documents.keys.any { it.startsWith(prefix) }) {
          "No legal documents for mapped bundled component $coordinate:${id.split('/')[2]}. " +
            "Supply the required upstream texts in dependencies.txt; a license label alone is insufficient."
        }
      }
    }
    var license = directory.resolve("LICENSE").readText()
    var notice = directory.resolve("NOTICE").readText()
    sourceNotices.get().forEach { name -> notice += "\n" + directory.resolve("NOTICE.$name").readText() }
    // Each entry names the bundled component/version and its exact license locations.
    val components = documents.keys.groupBy { it.split('/').take(5).joinToString("/") }
    if (components.isNotEmpty()) {
      license += LICENSE_INVENTORY
      components.forEach { (prefix, paths) ->
        val parts = prefix.split('/')
        val coordinate = "${parts[2]}:${parts[3]}"
        val selected = supplement(parts.drop(2).joinToString("/"))
        val label = selected.substringAfter('|', "").trim()
        license += "\n$coordinate:${parts[4]}" + if (label.isEmpty()) "\n" else " - $label\n"
        license += "Licensing and attribution documents:\n" + paths.joinToString("\n") { "  $it" } + "\n"
      }
    }
    // Preserve leaf notices once; a nested runtime's generated inventory was stripped above.
    val dependencyNotices = linkedMapOf<String, MutableList<String>>()
    documents.forEach { (path, contents) ->
      if (noticeFileName.matches(path.substringAfterLast('/'))) {
        contents.forEach {
          dependencyNotices.getOrPut(it.array().toString(Charsets.UTF_8).trim()) { mutableListOf() }.add(path)
        }
      }
    }
    if (dependencyNotices.isNotEmpty()) {
      notice += NOTICE_INVENTORY + "\n" + dependencyNotices.entries.joinToString("\n\n-----\n\n") { (text, paths) ->
        "From: " + paths.joinToString("\n      ") +
          "\nRelative file references below refer to the original document's directory.\n\n$text"
      } + "\n"
    }
    // The JDK doclet supplies its own legal/ directory alongside the generated JavaScript/CSS.
    if (javadocFiles.files.any { it.name == "jquery.md" || it.name == "jqueryUI.md" }) {
      license += "\nLicense texts for generated Javadoc assets are in the legal/ directory at the root of this JAR.\n"
    }
    add("META-INF/LICENSE", license.toByteArray(Charsets.UTF_8))
    add("META-INF/NOTICE", notice.toByteArray(Charsets.UTF_8))
    val output = outputArchive.get().asFile
    output.parentFile.mkdirs()
    // ZIP paths remain case-sensitive even on hosts where LICENSE and license/ would collide.
    ZipOutputStream(output).use { stream ->
      documents.forEach { (path, contents) ->
        val entry = ZipEntry(path)
        entry.time = 0L
        stream.putNextEntry(entry)
        contents.forEachIndexed { index, content ->
          if (index > 0) stream.write('\n'.code)
          stream.write(content.array())
        }
        stream.closeEntry()
      }
    }
  }
}

/** Replaces dependency legal resources with the artifact-specific documents generated above. */
@CacheableTransformer
class LegalFilesTransformer(
  @get:InputFile
  @get:PathSensitive(PathSensitivity.NONE)
  val legalArchive: File
) : Transformer {
  @Internal
  override fun getName(): String = javaClass.simpleName

  override fun canTransformResource(element: FileTreeElement): Boolean = GenerateJarLegalFiles.isLegalResource(element.relativePath.pathString)

  override fun transform(context: TransformerContext) {
    context.`is`.close()
  }

  override fun hasTransformedResource(): Boolean = true

  override fun modifyOutputStream(output: ZipOutputStream, preserveFileTimestamps: Boolean) {
    ZipFile(legalArchive).use { archive ->
      archive.entries().asSequence().forEach { resource ->
        val entry = ZipEntry(resource.name)
        entry.time = TransformerContext.getEntryTimestamp(preserveFileTimestamps, resource.time)
        output.putNextEntry(entry)
        archive.getInputStream(resource).use { it.copyTo(output) }
        output.closeEntry()
      }
    }
  }
}

val snappyJavaVersion: String = libs.versions.snappy.java.get()

val scalaVersion: String = project.properties["scalaVersion"] as? String ?: extra["defaultScalaVersion"].toString()
if (scalaVersion !in listOf("2.12", "2.13")) {
  throw GradleException("Scala version $scalaVersion is not supported.")
}

val skipWeb: Boolean = (project.findProperty("skipWeb") as? String)?.toBoolean() ?: false
val distributionPackageDir = layout.projectDirectory.dir("distribution/package")
val distributionPackageAllDir = layout.projectDirectory.dir("distribution/package-all")
val subprojectJarOutputDirs = subprojects.map { it.layout.buildDirectory.dir("libs") }

project.extra["extraJvmArgs"] =
  listOf(
    "-XX:+IgnoreUnrecognizedVMOptions",
    "--add-opens", "java.base/java.io=ALL-UNNAMED",
    "--add-opens", "java.base/java.lang=ALL-UNNAMED",
    "--add-opens", "java.base/java.lang.invoke=ALL-UNNAMED",
    "--add-opens", "java.base/java.lang.reflect=ALL-UNNAMED",
    "--add-opens", "java.base/java.math=ALL-UNNAMED",
    "--add-opens", "java.base/java.net=ALL-UNNAMED",
    "--add-opens", "java.base/java.nio=ALL-UNNAMED",
    "--add-opens", "java.base/java.text=ALL-UNNAMED",
    "--add-opens", "java.base/java.time=ALL-UNNAMED",
    "--add-opens", "java.base/java.util.concurrent.atomic=ALL-UNNAMED",
    "--add-opens", "java.base/java.util.concurrent=ALL-UNNAMED",
    "--add-opens", "java.base/java.util=ALL-UNNAMED",
    "--add-opens", "java.base/java.util.regex=ALL-UNNAMED",
    "--add-opens", "java.base/jdk.internal.ref=ALL-UNNAMED",
    "--add-opens", "java.base/jdk.internal.reflect=ALL-UNNAMED",
    "--add-opens", "java.sql/java.sql=ALL-UNNAMED",
    "--add-opens", "java.base/sun.nio.ch=ALL-UNNAMED",
    "--add-opens", "java.base/sun.nio.cs=ALL-UNNAMED",
    "--add-opens", "java.base/sun.security.action=ALL-UNNAMED",
    "--add-opens", "java.base/sun.util.calendar=ALL-UNNAMED",
    "--add-opens", "java.security.jgss/sun.security.krb5=ALL-UNNAMED"
  )

val pythonVersion: String = project.properties["pythonVersion"] as? String ?: project.extra["pythonVersion"].toString()
project.extra["pythonVersion"] = pythonVersion

licenseReport {
  renderers = arrayOf<ReportRenderer>(InventoryHtmlReportRenderer("report.html", "Backend"))
  filters = arrayOf<DependencyFilter>(LicenseBundleNormalizer())
}
repositories { mavenCentral() }

allprojects {
  // Gravitino Python client project didn't need to apply the Spotless plugin
  if (project.name == "client-python") {
    return@allprojects
  }

  apply(plugin = "com.diffplug.spotless")
  repositories {
    mavenCentral()
    mavenLocal()
  }

  plugins.withType<com.diffplug.gradle.spotless.SpotlessPlugin>().configureEach {
    configure<com.diffplug.gradle.spotless.SpotlessExtension> {
      java {
        // 1.15.0 supports both JDK8 and JDK17.
        googleJavaFormat("1.15.0")
        removeUnusedImports()
        trimTrailingWhitespace()
        replaceRegex(
          "Remove wildcard imports",
          "import\\s+[^\\*\\s]+\\*;(\\r\\n|\\r|\\n)",
          "$1"
        )
        replaceRegex(
          "Remove static wildcard imports",
          "import\\s+(?:static\\s+)?[^*\\s]+\\*;(\\r\\n|\\r|\\n)",
          "$1"
        )
        replaceRegex(
          "Use Guava classes from collect/base packages instead of any shadowed versions (including Jersey)",
          "import\\s+(?:.*\\.com\\.google\\.common\\.(collect|base)|org\\.glassfish\\.jersey\\.internal\\.guava)\\.([A-Z][a-zA-Z0-9_]*);",
          "import com.google.common.${'$'}1.${'$'}2;"
        )
        replaceRegex(
          "Use Guava classes from all other packages instead of any shadowed versions",
          "import\\s+.*\\.com\\.google\\.common\\.(io|util\\.concurrent|annotations|cache|primitives|hash|net|reflect)\\.([A-Z][a-zA-Z0-9_]*);",
          "import com.google.common.${'$'}1.${'$'}2;"
        )
        replaceRegex(
          "Use Apache Commons Lang3 instead of shadowed versions",
          "import\\s+.*\\.org\\.apache\\.commons\\.lang3\\.([A-Z][a-zA-Z0-9_]*);",
          "import org.apache.commons.lang3.${'$'}1;"
        )
        replaceRegex(
          "Use Apache Commons IO instead of shadowed versions",
          "import\\s+.*\\.org\\.apache\\.commons\\.io\\.([A-Z][a-zA-Z0-9_]*);",
          "import org.apache.commons.io.${'$'}1;"
        )
        // The trino-connector module logs via io.airlift.log.Logger to match Trino's own
        // logging so plugin log output routes into Trino's unified log, instead of SLF4J.
        // integration-test is intentionally excluded from this carve-out: it runs outside
        // Trino's isolated plugin classloader, so it should keep using SLF4J as normal.
        // The :trino-connector project itself formats the shared common-* source trees.
        val isTrinoPluginSource =
          project.path == ":trino-connector" ||
            project.path.startsWith(":trino-connector:trino-connector")
        if (!isTrinoPluginSource) {
          replaceRegex(
            "Use SLF4J Logger instead of other logging frameworks",
            "import\\s+.*\\.(Logger|LoggerFactory);",
            "import org.slf4j.${'$'}1;"
          )
        }
        replaceRegex(
          "Remove Testcontainers shading",
          "import\\s+org\\.testcontainers\\.shaded\\.([^;]+);",
          "import $1;"
        )

        targetExclude("**/build/**", "**/.pnpm/***")
      }

      kotlinGradle {
        target("*.gradle.kts")
        ktlint().editorConfigOverride(mapOf("indent_size" to 2))
      }
    }
  }

  val setTestEnvironment: (Test) -> Unit = { param ->
    param.doFirst {
      param.jvmArgs(project.property("extraJvmArgs") as List<*>)

      // Default use MiniGravitino to run integration tests
      param.environment("GRAVITINO_ROOT_DIR", project.rootDir.path)
      param.environment("IT_PROJECT_DIR", project.buildDir.path)
      // If the environment variable `HADOOP_USER_NAME` is not customized in submodule,
      // then set it to "anonymous"
      if (param.environment["HADOOP_USER_NAME"] == null) {
        param.environment("HADOOP_USER_NAME", "anonymous")
      }
      param.environment("HADOOP_HOME", "/tmp")
      param.environment("PROJECT_VERSION", project.version)

      // Gravitino CI Docker image
      param.environment("GRAVITINO_CI_HIVE_DOCKER_IMAGE", "apache/gravitino-ci:hive-0.1.20")
      param.environment("GRAVITINO_CI_KERBEROS_HIVE_DOCKER_IMAGE", "apache/gravitino-ci:kerberos-hive-0.1.7")
      param.environment("GRAVITINO_CI_DORIS_DOCKER_IMAGE", "apache/gravitino-ci:doris-0.1.5")
      param.environment("GRAVITINO_CI_DORIS_FE_IMAGE", System.getenv("GRAVITINO_CI_DORIS_FE_IMAGE") ?: "")
      param.environment("GRAVITINO_CI_DORIS_BE_IMAGE", System.getenv("GRAVITINO_CI_DORIS_BE_IMAGE") ?: "")
      param.environment("GRAVITINO_CI_TRINO_DOCKER_IMAGE", "apache/gravitino-ci:trino-0.1.6")
      param.environment("GRAVITINO_CI_RANGER_DOCKER_IMAGE", "apache/gravitino-ci:ranger-0.1.2")
      param.environment("GRAVITINO_CI_KAFKA_DOCKER_IMAGE", "apache/kafka:3.7.0")
      param.environment("GRAVITINO_CI_LOCALSTACK_DOCKER_IMAGE", "localstack/localstack:4.14.0")

      // Disable Ryuk for integration tests
      // Ryuk need privileged mode, if we want to rootless or run non-privileged mode, we need to disable it.
      param.environment("TESTCONTAINERS_RYUK_DISABLED", "true")

      val dockerRunning = project.rootProject.extra["dockerRunning"] as? Boolean ?: false
      val macDockerConnector = project.rootProject.extra["macDockerConnector"] as? Boolean ?: false
      if (OperatingSystem.current().isMacOsX() &&
        dockerRunning &&
        macDockerConnector
      ) {
        param.environment("NEED_CREATE_DOCKER_NETWORK", "true")
      }

      val icebergVersion: String = libs.versions.iceberg.get()
      param.systemProperty("ICEBERG_VERSION", icebergVersion)

      // Change poll image pause time from 30s to 60s
      param.environment("TESTCONTAINERS_PULL_PAUSE_TIMEOUT", "60")
      val jdbcDatabase = project.properties["jdbcBackend"] as? String ?: "h2"
      param.environment("jdbcBackend", jdbcDatabase)

      val testMode = project.properties["testMode"] as? String ?: "embedded"
      param.systemProperty("gravitino.log.path", "build/${project.name}-integration-test.log")
      project.delete("build/${project.name}-integration-test.log")
      if (testMode == "deploy") {
        param.environment("GRAVITINO_HOME", project.rootDir.path + "/distribution/package-all")
        val useWebV2 = System.getenv("GRAVITINO_USE_WEB_V2")?.toBoolean() == true
        val webWarPath = if (useWebV2) {
          project.rootDir.path + "/distribution/package/web-v2/gravitino-web-${project.version}.war"
        } else {
          project.rootDir.path + "/distribution/package/web/gravitino-web-${project.version}.war"
        }
        param.environment("GRAVITINO_WAR", webWarPath)
        param.systemProperty("testMode", "deploy")
      } else if (testMode == "embedded") {
        param.environment("GRAVITINO_HOME", project.rootDir.path)
        param.environment("GRAVITINO_TEST", "true")
        val useWebV2 = System.getenv("GRAVITINO_USE_WEB_V2")?.toBoolean() == true
        val webWarPath = if (useWebV2) {
          project.rootDir.path + "/web-v2/web/dist/"
        } else {
          project.rootDir.path + "/web/web/dist/"
        }
        param.environment("GRAVITINO_WAR", webWarPath)
        param.systemProperty("testMode", "embedded")
      } else {
        throw GradleException(
          "Gravitino integration tests are only compatible with the modes " +
            "[-PtestMode=embedded] or [-PtestMode=deploy]."
        )
      }
      param.useJUnitPlatform()
      val skipUTs = project.hasProperty("skipTests")
      if (skipUTs) {
        // Only run integration tests
        param.include("**/integration/test/**")
      }

      val dockerTest = project.rootProject.extra["dockerTest"] as? Boolean ?: false
      param.environment("dockerTest", dockerTest.toString())
      // Must stay inside doFirst: tasks such as :core's database lanes set this flag in their own
      // configuration action, which may run after this configureEach action registers.
      val includeDockerTaggedTests =
        param.extensions.extraProperties.properties["includeDockerTaggedTests"] as? Boolean
          ?: dockerTest
      val dorisMultiVersion = project.hasProperty("dorisMultiVersionTest")
      param.useJUnitPlatform {
        if (!includeDockerTaggedTests) {
          excludeTags("gravitino-docker-test")
        }
        if (!dorisMultiVersion) {
          // Running multiple Doris versions in one CI runner exhausts memory.
          // CI runs only the default 1.2.x suite; run all versions locally with
          // -PdorisMultiVersionTest.
          excludeTags("doris-multi-version")
        }
      }
    }
  }

  extra["initTestParam"] = setTestEnvironment
}

nexusPublishing {
  repositories {
    sonatype {
      nexusUrl.set(uri("https://s01.oss.sonatype.org/service/local/"))
      snapshotRepositoryUrl.set(uri("https://s01.oss.sonatype.org/content/repositories/snapshots/"))

      val sonatypeUser =
        System.getenv("SONATYPE_USER").takeUnless { it.isNullOrEmpty() }
          ?: extra["SONATYPE_USER"].toString()
      val sonatypePassword =
        System.getenv("SONATYPE_PASSWORD").takeUnless { it.isNullOrEmpty() }
          ?: extra["SONATYPE_PASSWORD"].toString()

      username.set(sonatypeUser)
      password.set(sonatypePassword)
    }
  }

  packageGroup.set("org.apache.gravitino")
}

fun excludePackagesForSparkConnector(project: Project) {
  project.afterEvaluate {
    if (scalaVersion != "2.12") {
      val excludedPackages = listOf(
        "org/apache/gravitino/spark/connector/paimon/**",
        "org/apache/gravitino/spark/connector/integration/test/paimon/**"
      )

      sourceSets {
        main {
          java {
            exclude(excludedPackages)
          }
        }
        test {
          java {
            exclude(excludedPackages)
          }
        }
      }
    }
  }
}

val commonsBeanutilsVersion: String = libs.versions.commons.beanutils.get()
val httpcore5Version: String = libs.versions.httpcore5.get()
val jsr305Dependency = libs.jsr305

subprojects {
  // Gravitino Python client project didn't need to apply the java plugin
  if (project.name == "client-python") {
    return@subprojects
  }

  val isHiveMetastoreLib = project.path in setOf(
    ":catalogs:hive-metastore2-libs",
    ":catalogs:hive-metastore3-libs"
  )

  apply(plugin = "jacoco")
  apply(plugin = "java")
  if (!isHiveMetastoreLib) {
    apply(plugin = "maven-publish")
  }

  // Force upgrade commons-beanutils/snappy-java for all subprojects to resolve outdated transitive versions
  // commons-beanutils: pulled by Hadoop, Hive, Spark, Flink, etc.
  // snappy-java: pulled by Hadoop, Kafka, Iceberg, etc.
  // httpcore5/httpcore5-h2: pulled by httpclient5 (directly and via Iceberg), whose POM still
  // manages them on the 5.3/5.4.0 line; force the 5.4.4 patch so every module uses the same,
  // latest 5.4 patch. It stays API-compatible with the httpclient5 versions on the classpath.
  configurations.all {
    resolutionStrategy.force("commons-beanutils:commons-beanutils:$commonsBeanutilsVersion")
    resolutionStrategy.force("org.xerial.snappy:snappy-java:$snappyJavaVersion")
    resolutionStrategy.force("org.apache.httpcomponents.core5:httpcore5:$httpcore5Version")
    resolutionStrategy.force("org.apache.httpcomponents.core5:httpcore5-h2:$httpcore5Version")

    // Exclude log4j 1.x (CVE-2020-9493, CVSS 9.8) pulled transitively by Hive and Hadoop.
    // The safe log4j-1.2-api bridge from Log4j 2.x is already included in the log4j bundle.
    exclude(group = "log4j", module = "log4j")
  }
  repositories {
    mavenCentral()
    mavenLocal()
  }

  // Guava no longer brings jsr305 transitively since 33.5.0, but the sources use
  // javax.annotation.Nullable and friends. Keep them on the compile classpath only.
  dependencies {
    compileOnly(jsr305Dependency)
    testCompileOnly(jsr305Dependency)
  }
  val jdk8CompatibleProjectPathPrefixes = setOf(
    ":api",
    ":common",
    ":catalogs:catalog-common",
    ":catalogs:hadoop-auth",
    ":catalogs:hadoop-common",
    ":maintenance:jobs",
    ":maintenance:maintenance-common",
    ":maintenance:optimizer-api",
    ":maintenance:updaters",
    ":clients",
    ":bundles",
    ":spark-connector",
    ":flink-connector"
  )

  // Spark 4 requires JDK 17, so the Spark 4 connector modules opt out of the JDK 8 target even
  // though the rest of :spark-connector (3.x) stays on Java 8.
  val jdk17OnlyProjectPaths = setOf(
    ":spark-connector:spark-4.0",
    ":spark-connector:spark-runtime-4.0",
    ":spark-connector:spark-4.1",
    ":spark-connector:spark-runtime-4.1"
  )

  fun compatibleWithJDK8(project: Project): Boolean {
    val path = project.path.lowercase()
    if (jdk17OnlyProjectPaths.any { path == it.lowercase() }) {
      return false
    }
    return jdk8CompatibleProjectPathPrefixes.any { path.startsWith(it) }
  }
  extensions.extraProperties.set("excludePackagesForSparkConnector", ::excludePackagesForSparkConnector)

  tasks.register("printJvm") {
    group = "help"
    description = "print JVM information"

    doLast {
      val compileJvmVersion = tasks.withType<JavaCompile>().firstOrNull()?.javaCompiler?.get()
        ?.metadata?.languageVersion?.asInt() ?: "undefined"

      val testJvmVersion = tasks.withType<Test>().firstOrNull()?.javaLauncher?.get()
        ?.metadata?.languageVersion?.asInt() ?: "undefined"

      val testJvmArgs = tasks.withType<Test>().firstOrNull()?.jvmArgs ?: listOf()

      val targetJvmVersion = (java.targetCompatibility?.majorVersion ?: "undefined")

      val sourceJvmVersion = (java.sourceCompatibility?.majorVersion ?: "undefined")

      println(
        """
              |=== ${project.name} JVM information===
              | project path: ${project.path}
              | JVM for compile: $compileJvmVersion
              | JVM for test: $testJvmVersion
              | JVM test args: $testJvmArgs
              | target JVM version: $targetJvmVersion
              | source JVM version: $sourceJvmVersion
              |==================================
        """.trimMargin()
      )
    }
  }

  java {
    toolchain {
      if (compatibleWithJDK8(project)) {
        languageVersion.set(JavaLanguageVersion.of(17))
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
      } else {
        languageVersion.set(JavaLanguageVersion.of(17))
      }
    }
  }

  if (compatibleWithJDK8(project)) {
    // Keep published/main classes Java 8-compatible for the selected modules.
    tasks.named<JavaCompile>("compileJava") {
      options.release.set(8)
    }

    // Tests still need Java 17 to compile against dependencies that only publish Java 17 variants.
    tasks.named<JavaCompile>("compileTestJava") {
      options.release.set(17)
    }

    val targetJvmVersionAttribute = TargetJvmVersion.TARGET_JVM_VERSION_ATTRIBUTE
    configurations.matching { it.name in setOf("testCompileClasspath", "testRuntimeClasspath") }
      .configureEach {
        attributes.attribute(targetJvmVersionAttribute, 17)
      }
  }

  gradle.projectsEvaluated {
    tasks.withType<JavaCompile> {
      options.compilerArgs.addAll(
        arrayOf(
          "-Xlint:cast",
          "-Xlint:deprecation",
          "-Xlint:divzero",
          "-Xlint:empty",
          "-Xlint:fallthrough",
          "-Xlint:finally",
          "-Xlint:overrides",
          "-Xlint:static",
          "-Werror"
        )
      )
    }
  }

  apply(plugin = "net.ltgt.errorprone")
  dependencies {
    errorprone("com.google.errorprone:error_prone_core:2.10.0")
  }

  tasks.withType<JavaCompile>().configureEach {
    // Keep Java compilation independent of the host's default charset.
    options.encoding = "UTF-8"
    options.errorprone.isEnabled.set(true)
    options.errorprone.disableWarningsInGeneratedCode.set(true)
    options.errorprone.disable(
      "AlmostJavadoc",
      "CanonicalDuration",
      "CheckReturnValue",
      "ComparableType",
      "ConstantOverflow",
      "DoubleBraceInitialization",
      "EqualsUnsafeCast",
      "EmptyBlockTag",
      "FutureReturnValueIgnored",
      "InconsistentCapitalization",
      "InconsistentHashCode",
      "JavaTimeDefaultTimeZone",
      "JdkObsolete",
      "LockNotBeforeTry",
      "MissingOverride",
      "MissingSummary",
      "MutableConstantField",
      "NonOverridingEquals",
      "ObjectEqualsForPrimitives",
      "OperatorPrecedence",
      "ReturnValueIgnored",
      "SameNameButDifferent",
      "StaticAssignmentInConstructor",
      "StringSplitter",
      "ThreadPriorityCheck",
      "ThrowIfUncheckedKnownChecked",
      "TypeParameterUnusedInFormals",
      "UnicodeEscape",
      "UnnecessaryParentheses",
      "UnsafeReflectiveConstructionCast",
      "UnusedMethod",
      "VariableNameSameAsType",
      "WaitNotInLoop"
    )
  }

  tasks.withType<Javadoc> {
    options.encoding = "UTF-8"
    options.locale = "en_US"

    val projectName = project.name
    if (projectName == "api" ||
      projectName == "client-java" ||
      projectName == "client-cli" ||
      projectName == "common" ||
      projectName == "filesystem-hadoop3"
    ) {
      options {
        (this as CoreJavadocOptions).addStringOption("Xwerror", "-quiet")
        isFailOnError = true
      }
    }
  }

  val sourcesJar by tasks.registering(Jar::class) {
    from(sourceSets.named("main").get().allSource)
    archiveClassifier.set("sources")
  }

  val javadocJar by tasks.registering(Jar::class) {
    archiveClassifier.set("javadoc")
    from(tasks["javadoc"])
  }

  // These notices cover copied production sources, not dependencies declared only in the POM.
  val sourceNoticeNames = mapOf(
    ":api" to listOf("spark", "iceberg"),
    ":common" to listOf("iceberg", "hadoop", "ossie"),
    ":core" to listOf("spark", "iceberg", "kafka", "aws"),
    ":clients:client-java" to listOf("iceberg"),
    ":bundles:aws" to listOf("doris"),
    ":catalogs:hive-metastore-common" to listOf("iceberg"),
    ":catalogs:catalog-lakehouse-iceberg" to listOf("iceberg"),
    ":catalogs:catalog-lakehouse-paimon" to listOf("paimon"),
    ":spark-connector:spark-3.5" to listOf("iceberg"),
    ":spark-connector:spark-4.0" to listOf("iceberg"),
    ":spark-connector:spark-4.1" to listOf("iceberg"),
    ":server-common" to listOf("hadoop"),
    ":iceberg:iceberg-common" to listOf("iceberg"),
    ":iceberg:iceberg-rest-server" to listOf("iceberg"),
    ":authorizations:authorization-ranger" to listOf("ranger")
  )[project.path].orEmpty()

  val mavenLegalFiles = tasks.register<GenerateJarLegalFiles>("generateMavenLegalFiles") {
    templates.set(rootProject.layout.projectDirectory.dir("dev/release/maven"))
    sourceNotices.set(sourceNoticeNames)
    outputArchive.set(layout.buildDirectory.file("generated/maven-legal/main.zip"))
  }
  val javadocLegalFiles = tasks.register<GenerateJarLegalFiles>("generateJavadocLegalFiles") {
    templates.set(rootProject.layout.projectDirectory.dir("dev/release/maven"))
    // SparkTransformConverter's Iceberg-derived findWidth method is private and absent from Javadoc.
    sourceNotices.set(
      when (project.path) {
        ":spark-connector:spark-3.5", ":spark-connector:spark-4.0", ":spark-connector:spark-4.1" ->
          sourceNoticeNames.filterNot { it == "iceberg" }
        else -> sourceNoticeNames
      }
    )
    javadocFiles.from(tasks.named<Javadoc>("javadoc").map { it.outputs.files.asFileTree.matching { include("legal/**") } })
    outputArchive.set(layout.buildDirectory.file("generated/maven-legal/javadoc.zip"))
  }
  val bundledLegalFiles = tasks.register<GenerateJarLegalFiles>("generateBundledLegalFiles") {
    templates.set(rootProject.layout.projectDirectory.dir("dev/release/maven"))
    sourceNotices.set(sourceNoticeNames)
    outputArchive.set(layout.buildDirectory.file("generated/maven-legal/bundled.zip"))
  }

  fun configureBundledLegalFiles(configurations: Provider<List<Configuration>>, jars: Provider<FileCollection>) {
    bundledLegalFiles.configure {
      dependencyJars.from(jars)
      dependencyJars.builtBy(configurations)
      dependencyIds.set(
        configurations.map { configs ->
          val artifacts = configs.flatMap { it.resolvedConfiguration.resolvedArtifacts }.groupBy { it.file.name }
          artifacts.mapValues { (name, entries) ->
            val coordinates = entries.map { artifact ->
              val id = artifact.moduleVersion.id
              "${id.group}/${id.name}/${id.version}${artifact.classifier?.let { "/$it" } ?: ""}"
            }.distinct()
            require(coordinates.size == 1) { "Ambiguous Maven artifact filename $name: $coordinates" }
            coordinates.single()
          }
        }
      )
    }
  }

  plugins.withId("com.github.johnrengelman.shadow") {
    val shadowJar = tasks.named<ShadowJar>("shadowJar")
    configureBundledLegalFiles(
      provider { shadowJar.get().configurations.map { it as Configuration } },
      provider { shadowJar.get().includedDependencies }
    )
    bundledLegalFiles.configure {
      // Connector runtimes strip the unrelocated SLF4J classes from client-java-runtime.
      excludedGroups.set(provider { if ("org/slf4j/**" in shadowJar.get().excludes) setOf("org.slf4j") else emptySet() })
    }
    shadowJar.configure {
      dependsOn(bundledLegalFiles)
      transform(LegalFilesTransformer(bundledLegalFiles.get().outputArchive.get().asFile))
    }

    // A module that declares a `shadedDependencies` configuration packages those inputs into its
    // shaded jar, so they must not be republished as dependencies: consumers resolving the
    // coordinate would otherwise download unshaded copies of the classes the jar already contains.
    // See https://github.com/apache/gravitino/issues/13171
    afterEvaluate {
      if (configurations.findByName("shadedDependencies") == null) {
        return@afterEvaluate
      }
      // The plain `jar` is an empty placeholder (classifier `empty`); the actual content lives in
      // the shaded jar. Point the ordinary Java variants at the shaded jar so consumers resolving
      // through Gradle module metadata get the implementation classes. Otherwise `runtimeElements`
      // selects the empty jar and, with the bundled inputs no longer published as dependencies,
      // consumers receive neither the classes nor the transitive dependencies.
      listOf("apiElements", "runtimeElements").forEach { variantName ->
        configurations.named(variantName) {
          outgoing.artifacts.clear()
          outgoing.artifact(tasks.named("shadowJar"))
        }
      }
      val generatePom = tasks.named<GenerateMavenPom>("generatePomFileForMavenJavaPublication")
      val verifyShadedRuntimePom = tasks.register("verifyShadedRuntimePom") {
        group = "verification"
        description = "Fails when a self-contained shaded artifact republishes bundled inputs."
        val pom = generatePom.map { it.destination }
        dependsOn(generatePom)
        doLast {
          val document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(pom.get())
          val published = document.getElementsByTagName("dependency")
          check(published.length == 0) {
            val coordinates =
              (0 until published.length).joinToString { index ->
                val element = published.item(index) as Element
                val children = (0 until element.childNodes.length).map { element.childNodes.item(it) }
                fun childText(name: String) =
                  children
                    .firstOrNull { it.nodeType == Node.ELEMENT_NODE && it.nodeName == name }
                    ?.textContent
                "${childText("groupId")}:${childText("artifactId")}"
              }
            "${project.path} publishes dependencies its jar already contains: $coordinates"
          }
        }
      }
      val generateMetadata =
        tasks.named<GenerateModuleMetadata>("generateMetadataFileForMavenJavaPublication")
      val shadedJarName = tasks.named<ShadowJar>("shadowJar").flatMap { it.archiveFileName }
      val verifyShadedRuntimeModuleMetadata =
        tasks.register("verifyShadedRuntimeModuleMetadata") {
          group = "verification"
          description =
            "Fails when the ordinary Java variants do not expose the shaded jar, or republish bundled dependencies."
          dependsOn(generateMetadata)
          val metadataFile = generateMetadata.flatMap { it.outputFile }
          doLast {
            @Suppress("UNCHECKED_CAST")
            val variants =
              (JsonSlurper().parse(metadataFile.get().asFile) as Map<String, Any>)["variants"]
                as List<Map<String, Any>>
            listOf("apiElements", "runtimeElements").forEach { variantName ->
              val variant = variants.first { it["name"] == variantName }

              @Suppress("UNCHECKED_CAST")
              val files = (variant["files"] as List<Map<String, String>>).map { it["name"] }
              check(files == listOf(shadedJarName.get())) {
                "${project.path} variant $variantName publishes $files instead of the shaded jar ${shadedJarName.get()}"
              }
              check((variant["dependencies"] as? List<*>).orEmpty().isEmpty()) {
                "${project.path} variant $variantName republishes dependencies its jar already contains"
              }
            }
          }
        }
      tasks.named("check") {
        dependsOn(verifyShadedRuntimePom)
        dependsOn(verifyShadedRuntimeModuleMetadata)
      }
    }
  }
  if (project.path == ":clients:cli") {
    configureBundledLegalFiles(provider { listOf(configurations.runtimeClasspath.get()) }, provider { configurations.runtimeClasspath.get() })
    tasks.named<Jar>("jar") {
      from(provider { configurations.runtimeClasspath.get().map { zipTree(it) } }) {
        exclude { GenerateJarLegalFiles.isLegalResource(it.relativePath.pathString) }
      }
    }
  }

  tasks.withType<Jar> {
    if (this is ShadowJar) return@withType
    if (this is War && project.path in listOf(":web:web", ":web-v2:web")) {
      // Web archives contain npm dependencies, not the Maven module inventory.
      from(project.layout.projectDirectory) {
        include("LICENSE.bin", "NOTICE.bin")
        into("META-INF")
        rename { it.removeSuffix(".bin") }
      }
      return@withType
    }
    val legalFiles = when {
      name == "javadocJar" -> javadocLegalFiles
      name == "jar" && project.path == ":clients:cli" -> bundledLegalFiles
      else -> mavenLegalFiles
    }
    dependsOn(legalFiles)
    from(provider { zipTree(legalFiles.get().outputArchive.get().asFile) })
  }

  if (project.name in listOf("web", "web-v2", "docs")) {
    plugins.apply(NodePlugin::class)
    configure<NodeExtension> {
      version.set("20.19.0")
      pnpmVersion.set("9.x")
      nodeProjectDir.set(file("$rootDir/.node"))
      download.set(true)
    }
  }

  if (!isHiveMetastoreLib) {
    apply(plugin = "signing")
    publishing {
      publications {
        create<MavenPublication>("MavenJava") {
          if (project.name == "docs" ||
            project.name == "integration-test" ||
            project.name == "integration-test-common" ||
            project.name == "web"
          ) {
            setArtifacts(emptyList<Any>())
          } else {
            from(components["java"])
            artifact(sourcesJar)
            artifact(javadocJar)
          }

          artifactId = "${rootProject.name.lowercase()}-${project.name}"

          pom {
            name.set("Gravitino")
            description.set("Gravitino is a high-performance, geo-distributed and federated metadata lake.")
            url.set("https://gravitino.apache.org")
            licenses {
              license {
                name.set("The Apache Software License, Version 2.0")
                url.set("http://www.apache.org/licenses/LICENSE-2.0.txt")
              }
            }
            developers {
              developer {
                id.set("The Gravitino community")
                name.set("support")
                email.set("[email protected]")
              }
            }
            scm {
              url.set("https://github.com/apache/gravitino")
              connection.set("scm:git:git://github.com/apache/gravitino.git")
            }
          }
        }
      }
    }

    configure<SigningExtension> {
      val taskNames = gradle.getStartParameter().getTaskNames()
      taskNames.forEach() {
        if (it.contains("publishToMavenLocal")) setRequired(false)
      }

      val gpgId = System.getenv("GPG_ID")
      val gpgSecretKey = System.getenv("GPG_PRIVATE_KEY")
      val gpgKeyPassword = System.getenv("GPG_PASSPHRASE")
      useInMemoryPgpKeys(gpgId, gpgSecretKey, gpgKeyPassword)
      sign(publishing.publications)
    }
  }

  tasks.configureEach<Test> {
    if (project.name != "server-common") {
      val initTest = project.extra.get("initTestParam") as (Test) -> Unit
      initTest(this)
    }

    val testTaskStartTimeMsKey = "testTaskStartTimeMs"
    doFirst {
      extensions.extraProperties[testTaskStartTimeMsKey] = System.currentTimeMillis()
      logger.lifecycle(
        "[TEST-TIMING] START module={} task={} at={}",
        project.path,
        path,
        extensions.extraProperties[testTaskStartTimeMsKey]
      )
    }

    doLast {
      val endTimeMs = System.currentTimeMillis()
      val startTimeMs = extensions.extraProperties[testTaskStartTimeMsKey] as? Long ?: endTimeMs
      logger.lifecycle(
        "[TEST-TIMING] END module={} task={} startMs={} endMs={} durationMs={}",
        project.path,
        path,
        startTimeMs,
        endTimeMs,
        endTimeMs - startTimeMs
      )
    }

    testLogging {
      exceptionFormat = TestExceptionFormat.FULL
      showExceptions = true
      showCauses = true
      showStackTraces = true
    }
    // Distinct outputs let Gradle execute independent test tasks in parallel.
    val testReportPath = path.removePrefix(":").replace(':', '/')
    reports.html.outputLocation.set(
      rootProject.layout.buildDirectory.dir("reports/tests/$testReportPath")
    )
    val skipTests = project.hasProperty("skipTests")
    if (!skipTests) {
      val extraArgs = project.property("extraJvmArgs") as List<String>
      jvmArgs = listOf("-Xmx4G") + extraArgs
      useJUnitPlatform()
      val isCoreSuiteTask =
        project.path == ":core" &&
          name in setOf(
          "coreUnitTest",
          "coreH2Test",
          "coreMySQLTest",
          "corePostgreSQLTest"
        )
      if (!isCoreSuiteTask) {
        finalizedBy(tasks.getByName("jacocoTestReport"))
      }
    }
  }

  tasks.withType<JacocoReport> {
    reports {
      csv.required.set(true)
      xml.required.set(true)
      html.required.set(true)
    }
  }

  tasks.register("allDeps", DependencyReportTask::class)

  group = "org.apache.gravitino"
  version = "$version"

  tasks.withType<Jar> {
    archiveBaseName.set("${rootProject.name.lowercase()}-${project.name}")
    if (project.name == "server") {
      from(sourceSets.main.get().resources)
      setDuplicatesStrategy(DuplicatesStrategy.INCLUDE)
    }

    if (project.name != "integration-test") {
      exclude("log4j2.properties")
      exclude("test/**")
    }
  }
  tasks.named("compileJava").configure {
    dependsOn("spotlessCheck")
  }
}

tasks.rat {
  approvedLicense("Apache License Version 2.0")

  // Set input directory to that of the root project instead of the CWD. This
  // makes .gitignore rules (added below) work properly.
  inputDir.set(project.rootDir)

  val exclusions = mutableListOf(
    // Ignore files we track but do not need full headers
    "**/.github/**/*",
    "**/*.log",
    "**/*.out",
    "**/*.venv",
    "**/*.egg-info",
    "**/.pytest_cache",
    "**/.python-version",
    "**/.uv",
    "**/__pycache__",
    "**/uv.lock",
    "**/licenses/*.txt",
    "**/licenses/*.md",
    "**/LICENSE.*",
    "**/NOTICE.*",
    "**/trino-ci-testset",
    "ROADMAP.md",
    "GETTING_STARTED.md",
    "clients/cli/src/main/resources/*.txt",
    "clients/client-python/venv/*",
    "clients/client-python/docs/build",
    "clients/client-python/docs/source/generated",
    "clients/client-python/gravitino/utils/http_client.py",
    "clients/client-python/tests/unittests/htmlcov/*",
    "clients/client-python/tests/integration/htmlcov/*",
    "clients/filesystem-fuse/Cargo.lock",
    "dev/charts/gravitino/README.md",
    "dev/charts/gravitino-iceberg-rest-server/README.md",
    "dev/charts/gravitino-lance-rest-server/README.md",
    "dev/docker/**/*.xml",
    "dev/docker/**/*.conf",
    "dev/docker/kerberos-hive/kadm5.acl",
    "docs/**/*.md",
    ".claude/**",
    "gradle/wrapper/gradle-wrapper.properties",
    "lineage/src/test/java/org/apache/gravitino/lineage/source/TestLineageOperations.java",
    "spark-connector/spark-common/src/test/resources/**",
    "web/web/.**",
    "web/web/dist/**/*",
    "web/web/next-env.d.ts",
    "web/web/node_modules/**/*",
    "web/web/package-lock.json",
    "web/web/pnpm-lock.yaml",
    "web/web/src/lib/enums/httpEnum.js",
    "web/web/src/lib/icons/svg/**/*.svg",
    "web/web/src/lib/utils/axios/**/*",
    "web/web/src/types/axios.d.ts",
    "web/web/yarn.lock",
    "web-v2/web/.**",
    "web-v2/web/dist/**/*",
    "web-v2/web/next-env.d.ts",
    "web-v2/web/node_modules/**/*",
    "web-v2/web/package-lock.json",
    "web-v2/web/pnpm-lock.yaml",
    "web-v2/web/src/lib/enums/httpEnum.js",
    "web-v2/web/src/lib/icons/svg/**/*.svg",
    "web-v2/web/src/lib/utils/axios/**/*",
    "web-v2/web/src/types/axios.d.ts",
    "web-v2/web/yarn.lock"
  )

  // Add .gitignore excludes to the Apache Rat exclusion list.
  val gitIgnore = project(":").file(".gitignore")
  if (gitIgnore.exists()) {
    val gitIgnoreExcludes = gitIgnore.readLines().filter {
      it.isNotEmpty() && !it.startsWith("#")
    }
    exclusions.addAll(gitIgnoreExcludes)
  }

  verbose.set(true)
  failOnError.set(true)
  setExcludes(exclusions)
}

tasks.check.get().dependsOn(tasks.rat)

apply(from = "dev/release/maven/test-legal-files.gradle")

tasks.cyclonedxBom {
  setIncludeConfigs(listOf("runtimeClasspath"))
}

jacoco {
  toolVersion = "0.8.10"
  reportsDirectory.set(layout.buildDirectory.dir("JacocoReport"))
}

tasks {
  val projectDir = layout.projectDirectory
  val outputDir = projectDir.dir("distribution")
  val cleanDistributionPackage by registering(Delete::class) {
    group = "gravitino distribution"
    delete(distributionPackageDir, distributionPackageAllDir)
    delete(subprojectJarOutputDirs)
  }

  val compileDistribution by registering {
    val dependencies =
      mutableListOf(
        "copyCatalogLibAndConfigs",
        "copySubprojectDependencies",
        "copySubprojectLib",
        "copyCliLib",
        "copyJobsLib",
        ":authorizations:copyLibAndConfig",
        ":iceberg:iceberg-rest-server:copyLibAndConfigs",
        ":iceberg:iceberg-rest-server-experiment:copyLibAndConfigs",
        ":lance:lance-rest-server:copyLibAndConfigs",
        ":maintenance:optimizer:copyLibAndConfigs",
        ":plugins:idp-basic:copyLibAndConfigs",
        ":plugins:maintenance:copyLibAndConfigs",
        ":plugins:k8s-job-executor:copyLibAndConfigs"
      )
    if (!skipWeb) {
      dependencies.add(":web:web:build")
      dependencies.add(":web-v2:web:build")
    }
    dependsOn(cleanDistributionPackage)
    dependsOn(dependencies)

    group = "gravitino distribution"
    outputs.dir(distributionPackageDir)
    outputs.dir(distributionPackageAllDir)
    doLast {
      copy {
        from(projectDir.dir("conf")) { into("package/conf") }
        from(projectDir.dir("bin")) { into("package/bin") }
        if (!skipWeb) {
          from(projectDir.dir("web/web/build/libs/${rootProject.name}-web-$version.war")) {
            into("package/web")
          }
          from(projectDir.dir("web-v2/web/build/libs/${rootProject.name}-web-$version.war")) {
            into("package/web-v2")
          }
        }
        from(projectDir.dir("scripts")) { into("package/scripts") }
        into(outputDir)
        rename { fileName ->
          fileName.replace(".template", "")
        }
        eachFile {
          if (name == "gravitino-env.sh") {
            filter { line ->
              line.replace("GRAVITINO_VERSION_PLACEHOLDER", "$version")
            }
          }
        }
        fileMode = 0b111101101
      }
      copy {
        from(projectDir.dir("licenses")) { into("package/licenses") }
        from(projectDir.file("LICENSE.bin")) { into("package") }
        from(projectDir.file("NOTICE.bin")) { into("package") }
        from(projectDir.file("README.md")) { into("package") }
        if (!skipWeb) {
          from(projectDir.dir("web/web/licenses")) { into("package/web/licenses") }
          from(projectDir.dir("web/web/LICENSE.bin")) { into("package/web") }
          from(projectDir.dir("web/web/NOTICE.bin")) { into("package/web") }
          from(projectDir.dir("web-v2/web/licenses")) { into("package/web-v2/licenses") }
          from(projectDir.dir("web-v2/web/LICENSE.bin")) { into("package/web-v2") }
          from(projectDir.dir("web-v2/web/NOTICE.bin")) { into("package/web-v2") }
        }
        into(outputDir)
        rename { fileName ->
          fileName.replace(".bin", "")
        }
      }

      if (skipWeb) {
        delete(projectDir.dir("distribution/package/web"), projectDir.dir("distribution/package/web-v2"))
      }

      // Create the directory 'data' for storage.
      val directory = File("distribution/package/data")
      directory.mkdirs()

      // Copy the all directory distribution/package to distribution/package-all
      copy {
        from(distributionPackageDir)
        into(distributionPackageAllDir)
      }

      // remove catalogs-contrib modules from distribution/package
      project.file("catalogs-contrib").listFiles()?.forEach { file ->
        if (file.isDirectory) {
          val catalogName = file.name.replace("catalog-", "")
          delete(projectDir.dir("distribution/package/catalogs/$catalogName"))
        }
      }
    }
  }

  val compileIcebergRESTServer by registering {
    dependsOn("iceberg:iceberg-rest-server:copyLibAndConfigsToStandalonePackage")
    group = "gravitino distribution"
    outputs.dir(projectDir.dir("distribution/${rootProject.name}-iceberg-rest-server"))
    doLast {
      copy {
        from(projectDir.dir("conf")) {
          include(
            "${rootProject.name}-iceberg-rest-server.conf.template",
            "${rootProject.name}-env.sh.template",
            "${rootProject.name}-iceberg-rest-log4j2.properties.template"
          )
          into("${rootProject.name}-iceberg-rest-server/conf")
        }
        from(projectDir.dir("bin")) {
          include("common.sh.template", "${rootProject.name}-iceberg-rest-server.sh.template")
          into("${rootProject.name}-iceberg-rest-server/bin")
        }
        into(outputDir)
        rename { fileName ->
          fileName.replace(".template", "")
        }
        eachFile {
          if (name == "gravitino-env.sh") {
            filter { line ->
              line.replace("GRAVITINO_VERSION_PLACEHOLDER", "$version")
            }
          }
        }
        fileMode = 0b111101101
      }

      copy {
        from(projectDir.dir("scripts")) {
          include("**/iceberg-*.sql")
          into("${rootProject.name}-iceberg-rest-server/scripts")
        }
        into(outputDir)
      }

      copy {
        from(projectDir.dir("licenses")) { into("${rootProject.name}-iceberg-rest-server/licenses") }
        from(projectDir.file("LICENSE.iceberg")) { into("${rootProject.name}-iceberg-rest-server") }
        from(projectDir.file("NOTICE.iceberg")) { into("${rootProject.name}-iceberg-rest-server") }
        from(projectDir.file("README.md")) { into("${rootProject.name}-iceberg-rest-server") }
        into(outputDir)
        rename { fileName ->
          fileName.replace(".iceberg", "")
        }
      }
    }
  }

  val compileLanceRESTServer by registering {
    dependsOn("lance:lance-rest-server:copyLibAndConfigsToStandalonePackage")
    group = "gravitino distribution"
    outputs.dir(projectDir.dir("distribution/${rootProject.name}-lance-rest-server"))
    doLast {
      copy {
        from(projectDir.dir("conf")) {
          include(
            "${rootProject.name}-lance-rest-server.conf.template",
            "${rootProject.name}-env.sh.template",
            "${rootProject.name}-lance-rest-log4j2.properties.template"
          )
          into("${rootProject.name}-lance-rest-server/conf")
        }
        from(projectDir.dir("bin")) {
          include("common.sh.template", "${rootProject.name}-lance-rest-server.sh.template")
          into("${rootProject.name}-lance-rest-server/bin")
        }
        into(outputDir)
        rename { fileName ->
          fileName.replace(".template", "")
        }
        eachFile {
          if (name == "gravitino-env.sh") {
            filter { line ->
              line.replace("GRAVITINO_VERSION_PLACEHOLDER", "$version")
            }
          }
        }
        fileMode = 0b111101101
      }

      copy {
        from(projectDir.dir("licenses")) { into("${rootProject.name}-lance-rest-server/licenses") }
        from(projectDir.file("LICENSE.lance")) { into("${rootProject.name}-lance-rest-server") }
        from(projectDir.file("NOTICE.lance")) { into("${rootProject.name}-lance-rest-server") }
        from(projectDir.file("README.md")) { into("${rootProject.name}-lance-rest-server") }
        into(outputDir)
        rename { fileName ->
          fileName.replace(".lance", "")
        }
      }
    }
  }

  val compileTrinoConnector by registering {
    dependsOn("trino-connector:trino-connector-482-483:copyLibs")
    group = "gravitino distribution"
  }

  val assembleDistribution by registering(Tar::class) {
    dependsOn(
      compileDistribution,
      ":trino-connector:trino-connector-469-472:assembleTrinoConnector",
      ":trino-connector:trino-connector-473-477:assembleTrinoConnector",
      ":trino-connector:trino-connector-478-479:assembleTrinoConnector",
      ":trino-connector:trino-connector-480:assembleTrinoConnector",
      ":trino-connector:trino-connector-481:assembleTrinoConnector",
      ":trino-connector:trino-connector-482-483:assembleTrinoConnector",
      "assembleIcebergRESTServer",
      "assembleLanceRESTServer"
    )
    group = "gravitino distribution"
    finalizedBy("checksumDistribution")
    into("${rootProject.name}-$version-bin")
    from(distributionPackageDir)
    compression = Compression.GZIP
    archiveFileName.set("${rootProject.name}-$version-bin.tar.gz")
    destinationDirectory.set(projectDir.dir("distribution"))
  }

  val assembleDistributionAll by registering(Tar::class) {
    dependsOn(compileDistribution)
    group = "gravitino distribution"
    finalizedBy("checksumDistributionAll")
    into("${rootProject.name}-$version-bin-all")
    from(projectDir.dir("distribution/package-all"))
    compression = Compression.GZIP
    archiveFileName.set("${rootProject.name}-$version-bin-all.tar.gz")
    destinationDirectory.set(projectDir.dir("distribution"))
  }

  register("checksumDistributionAll") {
    group = "gravitino distribution"
    dependsOn(assembleDistributionAll)
    val archiveFile = assembleDistributionAll.flatMap { it.archiveFile }
    val checksumFile = archiveFile.map { archive ->
      archive.asFile.let { it.resolveSibling("${it.name}.sha256") }
    }
    inputs.file(archiveFile)
    outputs.file(checksumFile)
    doLast {
      checksumFile.get().writeText(
        serviceOf<ChecksumService>().sha256(archiveFile.get().asFile).toString()
      )
    }
  }

  val assembleLanceRESTServer by registering(Tar::class) {
    dependsOn("compileLanceRESTServer")
    group = "gravitino distribution"
    finalizedBy("checksumLanceRESTServerDistribution")
    into("${rootProject.name}-lance-rest-server-$version-bin")
    from(compileLanceRESTServer.map { it.outputs.files.single() })
    compression = Compression.GZIP
    archiveFileName.set("${rootProject.name}-lance-rest-server-$version-bin.tar.gz")
    destinationDirectory.set(projectDir.dir("distribution"))
  }

  val assembleIcebergRESTServer by registering(Tar::class) {
    dependsOn("compileIcebergRESTServer")
    group = "gravitino distribution"
    finalizedBy("checksumIcebergRESTServerDistribution")
    into("${rootProject.name}-iceberg-rest-server-$version-bin")
    from(compileIcebergRESTServer.map { it.outputs.files.single() })
    compression = Compression.GZIP
    archiveFileName.set("${rootProject.name}-iceberg-rest-server-$version-bin.tar.gz")
    destinationDirectory.set(projectDir.dir("distribution"))
  }

  register("checksumIcebergRESTServerDistribution") {
    group = "gravitino distribution"
    dependsOn(assembleIcebergRESTServer)
    val archiveFile = assembleIcebergRESTServer.flatMap { it.archiveFile }
    val checksumFile = archiveFile.map { archive ->
      archive.asFile.let { it.resolveSibling("${it.name}.sha256") }
    }
    inputs.file(archiveFile)
    outputs.file(checksumFile)
    doLast {
      checksumFile.get().writeText(
        serviceOf<ChecksumService>().sha256(archiveFile.get().asFile).toString()
      )
    }
  }

  register("checksumLanceRESTServerDistribution") {
    group = "gravitino distribution"
    dependsOn(assembleLanceRESTServer)
    val archiveFile = assembleLanceRESTServer.flatMap { it.archiveFile }
    val checksumFile = archiveFile.map { archive ->
      archive.asFile.let { it.resolveSibling("${it.name}.sha256") }
    }
    inputs.file(archiveFile)
    outputs.file(checksumFile)
    doLast {
      checksumFile.get().writeText(
        serviceOf<ChecksumService>().sha256(archiveFile.get().asFile).toString()
      )
    }
  }

  register("checksumDistribution") {
    group = "gravitino distribution"
    dependsOn(assembleDistribution, "checksumIcebergRESTServerDistribution", "checksumLanceRESTServerDistribution")
    val archiveFile = assembleDistribution.flatMap { it.archiveFile }
    val checksumFile = archiveFile.map { archive ->
      archive.asFile.let { it.resolveSibling("${it.name}.sha256") }
    }
    inputs.file(archiveFile)
    outputs.file(checksumFile)
    doLast {
      checksumFile.get().writeText(
        serviceOf<ChecksumService>().sha256(archiveFile.get().asFile).toString()
      )
    }
  }

  val cleanDistribution by registering(Delete::class) {
    group = "gravitino distribution"
    delete(outputDir)
  }

  register("copySubprojectDependencies", Copy::class) {
    subprojects.forEach() {
      if (!it.name.startsWith("authorization") &&
        !it.name.startsWith("catalog") &&
        !it.name.startsWith("cli") &&
        !it.name.startsWith("client") &&
        !it.name.startsWith("filesystem") &&
        !it.name.startsWith("flink") &&
        !it.name.startsWith("iceberg") &&
        !it.name.startsWith("lance") &&
        !it.name.startsWith("optimizer") &&
        !it.name.startsWith("spark") &&
        !it.name.startsWith("hive-metastore") &&
        !it.name.startsWith("trino-connector") &&
        it.name != "hadoop-common" &&
        it.name != "integration-test" &&
        it.parent?.name != "bundles" &&
        it.parent?.name != "maintenance" &&
        it.parent?.name != "plugins" &&
        it.name != "mcp-server"
      ) {
        from(it.configurations.runtimeClasspath) {
          exclude("error_prone_annotations-*.jar")
        }
        into("distribution/package/libs")
      }
    }
    setDuplicatesStrategy(DuplicatesStrategy.EXCLUDE)
  }

  register("copyCliLib", Copy::class) {
    dependsOn("clients:cli:build")
    from("clients/cli/build/libs")
    into("distribution/package/auxlib")
    include("gravitino-cli-*.jar")
    setDuplicatesStrategy(DuplicatesStrategy.EXCLUDE)
  }

  register("copyJobsLib", Copy::class) {
    dependsOn(":maintenance:jobs:build")
    from("maintenance/jobs/build/libs")
    into("distribution/package/auxlib")
    include("gravitino-jobs-*.jar")
    exclude("*-empty.jar")
    setDuplicatesStrategy(DuplicatesStrategy.EXCLUDE)
  }

  register("copySubprojectLib", Copy::class) {
    subprojects.forEach() {
      if (!it.name.startsWith("authorization") &&
        !it.name.startsWith("catalog") &&
        !it.name.startsWith("cli") &&
        !it.name.startsWith("client") &&
        !it.name.startsWith("filesystem") &&
        !it.name.startsWith("flink") &&
        !it.name.startsWith("iceberg") &&
        !it.name.startsWith("lance") &&
        !it.name.startsWith("integration-test") &&
        !it.name.startsWith("spark") &&
        !it.name.startsWith("trino-connector") &&
        it.name != "hive-metastore2-libs" &&
        it.name != "hive-metastore3-libs" &&
        !it.name.startsWith("optimizer") &&
        it.name != "hive-metastore-common" &&
        it.name != "docs" &&
        it.name != "hadoop-auth" &&
        it.name != "hadoop-common" &&
        it.name != "web" &&
        it.name != "web-v2" &&
        it.parent?.name != "bundles" &&
        it.parent?.name != "plugins" &&
        it.parent?.name != "maintenance" &&
        it.name != "mcp-server"
      ) {
        dependsOn("${it.name}:build")
        from("${it.name}/build/libs") {
          include("*.jar")
          exclude("*-jcstress.jar", "*-jmh.jar", "error_prone_annotations-*.jar")
        }
        into("distribution/package/libs")
        setDuplicatesStrategy(DuplicatesStrategy.INCLUDE)
      }
    }
  }

  register("copyCatalogLibAndConfigs", Copy::class) {
    dependsOn(
      ":catalogs:catalog-fileset:copyLibAndConfig",
      ":catalogs:catalog-glue:copyLibAndConfig",
      ":catalogs:catalog-hive:copyLibAndConfig",
      ":catalogs:catalog-jdbc-doris:copyLibAndConfig",
      ":catalogs:catalog-jdbc-mysql:copyLibAndConfig",
      ":catalogs:catalog-jdbc-postgresql:copyLibAndConfig",
      ":catalogs:catalog-jdbc-starrocks:copyLibAndConfig",
      ":catalogs:catalog-kafka:copyLibAndConfig",
      ":catalogs:catalog-lakehouse-hudi:copyLibAndConfig",
      ":catalogs:catalog-lakehouse-iceberg:copyLibAndConfig",
      ":catalogs:catalog-lakehouse-paimon:copyLibAndConfig",
      ":catalogs:catalog-model:copyLibAndConfig",
      ":catalogs:hive-metastore2-libs:copyLibs",
      ":catalogs:hive-metastore3-libs:copyLibs",
      ":catalogs:catalog-lakehouse-generic:copyLibAndConfig",
      ":catalogs-contrib:catalog-jdbc-hologres:copyLibAndConfig",
      ":catalogs-contrib:catalog-jdbc-oceanbase:copyLibAndConfig",
      ":catalogs-contrib:catalog-jdbc-clickhouse:copyLibAndConfig"
    )
  }

  clean {
    dependsOn(cleanDistribution)
  }
}

gradle.projectsEvaluated {
  val cleanDistributionPackageTask = rootProject.tasks.named("cleanDistributionPackage")
  val distributionPackagePaths =
    listOf(distributionPackageDir, distributionPackageAllDir)
      .map { it.asFile.toPath().toAbsolutePath().normalize() }
  val subprojectJarOutputPaths =
    subprojectJarOutputDirs.map { it.get().asFile.toPath().toAbsolutePath().normalize() }

  allprojects {
    val runsIntegrationTestsOnly = rootProject.hasProperty("skipTests")
    val hasDockerTests =
      rootProject.extra["dockerTest"] == true && fileTree("src/test") {
        include("**/*.java", "**/*.kt")
      }.any { it.readText().contains("gravitino-docker-test") }

    // Integration tests in different projects share the same Gravitino server, database,
    // containers, and configuration files. Running them together lets one test stop or reset
    // resources while another test is still using them. Normal builds keep independent unit tests
    // parallel and serialize only projects that contain Docker-tagged tests.
    if (runsIntegrationTestsOnly || hasDockerTests) {
      tasks.withType<Test>().configureEach {
        usesService(sharedTestEnvironmentLock)
      }
    }

    tasks.withType<Jar>().configureEach {
      mustRunAfter(cleanDistributionPackageTask)
    }

    tasks.withType<Copy>().configureEach {
      val copyDestinationDir = destinationDir ?: return@configureEach
      val destinationPath = copyDestinationDir.toPath().toAbsolutePath().normalize()
      if (distributionPackagePaths.any { destinationPath.startsWith(it) }) {
        dependsOn(cleanDistributionPackageTask)
      }
      if (subprojectJarOutputPaths.any { destinationPath.startsWith(it) }) {
        mustRunAfter(cleanDistributionPackageTask)
      }
    }
  }
}

apply(plugin = "com.dorongold.task-tree")

project.extra["dockerTest"] = false
project.extra["dockerRunning"] = false
project.extra["macDockerConnector"] = false
project.extra["isOrbStack"] = false

// The following is to check the docker status and print the tip message
fun printDockerCheckInfo() {
  checkMacDockerConnector()
  checkDockerStatus()
  checkOrbStackStatus()

  val testMode = project.properties["testMode"] as? String ?: "embedded"
  if (testMode != "deploy" && testMode != "embedded") {
    return
  }
  val dockerRunning = project.extra["dockerRunning"] as? Boolean ?: false
  val macDockerConnector = project.extra["macDockerConnector"] as? Boolean ?: false
  val isOrbStack = project.extra["isOrbStack"] as? Boolean ?: false
  val skipDockerTests = if (extra["skipDockerTests"].toString().toBoolean()) {
    // Read the environment variable (SKIP_DOCKER_TESTS) when skipDockerTests is true
    // which means users can enable the docker tests by setting the gradle properties or the environment variable.
    System.getenv("SKIP_DOCKER_TESTS")?.toBoolean() ?: true
  } else {
    false
  }
  if (skipDockerTests) {
    project.extra["dockerTest"] = false
  } else if (OperatingSystem.current().isMacOsX() &&
    dockerRunning &&
    (macDockerConnector || isOrbStack)
  ) {
    project.extra["dockerTest"] = true
  } else if (OperatingSystem.current().isLinux() && dockerRunning) {
    project.extra["dockerTest"] = true
  }

  println("------------------ Check Docker environment ---------------------")
  println("Docker server status ............................................ [${if (dockerRunning) "running" else "\u001B[31mstop\u001B[0m"}]")
  if (OperatingSystem.current().isMacOsX()) {
    println("mac-docker-connector status ..................................... [${if (macDockerConnector) "running" else "\u001B[31mstop\u001B[0m"}]")
    println("OrbStack status ................................................. [${if (dockerRunning && isOrbStack) "yes" else "\u001B[31mno\u001B[0m"}]")
  }

  val dockerTest = project.extra["dockerTest"] as? Boolean ?: false
  if (dockerTest) {
    println("Using Docker container to run all tests ......................... [$testMode test]")
  } else {
    println("Run test cases without `gravitino-docker-test` tag .............. [$testMode test]")
  }
  println("-----------------------------------------------------------------")

  // Print help message if Docker server or mac-docker-connector is not running
  printDockerServerTip()
  printMacDockerTip()
}

fun printDockerServerTip() {
  val dockerRunning = project.extra["dockerRunning"] as? Boolean ?: false
  if (!dockerRunning) {
    val redColor = "\u001B[31m"
    val resetColor = "\u001B[0m"
    println("Tip: Please make sure to start the ${redColor}Docker server$resetColor before running the integration tests.")
  }
}

fun printMacDockerTip() {
  val macDockerConnector = project.extra["macDockerConnector"] as? Boolean ?: false
  val isOrbStack = project.extra["isOrbStack"] as? Boolean ?: false
  if (OperatingSystem.current().isMacOsX() && !macDockerConnector && !isOrbStack) {
    val redColor = "\u001B[31m"
    val resetColor = "\u001B[0m"
    println(
      "Tip: Please make sure to use ${redColor}OrbStack$resetColor or execute the " +
        "$redColor`dev/docker/tools/mac-docker-connector.sh`$resetColor script before running" +
        " the integration test on macOS."
    )
  }
}

fun checkMacDockerConnector() {
  if (!OperatingSystem.current().isMacOsX()) {
    // Only macOS requires the use of `docker-connector`
    return
  }

  try {
    val processName = "docker-connector"
    val command = "pgrep -x -q $processName"

    val execResult = project.exec {
      commandLine("bash", "-c", command)
    }
    if (execResult.exitValue == 0) {
      project.extra["macDockerConnector"] = true
    }
  } catch (e: Exception) {
    println("checkContainerRunning failed: ${e.message}")
  }
}

fun checkDockerStatus() {
  try {
    val process = ProcessBuilder("docker", "info").start()
    val exitCode = process.waitFor()

    if (exitCode == 0) {
      project.extra["dockerRunning"] = true
    } else {
      println("checkDockerStatus failed with exit code $exitCode")
    }
  } catch (e: IOException) {
    println("checkDockerStatus failed: ${e.message}")
  }
}

fun checkOrbStackStatus() {
  if (!OperatingSystem.current().isMacOsX()) {
    return
  }

  try {
    val process = ProcessBuilder("docker", "context", "show").start()
    val exitCode = process.waitFor()
    if (exitCode == 0) {
      val currentContext = process.inputStream.bufferedReader().readText()
      println("Current docker context is: $currentContext")
      project.extra["isOrbStack"] = currentContext.lowercase().contains("orbstack")
    } else {
      println("checkOrbStackStatus failed with exit code $exitCode")
    }
  } catch (e: IOException) {
    println("checkOrbStackStatus failed: ${e.message}")
  }
}

printDockerCheckInfo()