Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

10.8 KB
Raw Blame
import java.nio.file.Paths

import static org.apache.tools.ant.taskdefs.condition.Os.FAMILY_WINDOWS
import static org.apache.tools.ant.taskdefs.condition.Os.isFamily

import org.gradle.api.tasks.testing.logging.TestExceptionFormat
import org.gradle.api.tasks.testing.logging.TestLogEvent

buildscript {
  repositories {
    mavenCentral()
  }
  dependencies {
    classpath libs.asm
    classpath libs.asmTree
  }
}

plugins {
  id 'java-base'
  id 'jacoco'
  id 'test-report-aggregation'
  alias libs.plugins.axionRelease
  alias libs.plugins.fileEncrypt
  alias libs.plugins.nexusPublish
}

def jacocoToolVersion = libs.versions.jacoco.get()

jacoco {
  toolVersion = jacocoToolVersion
}

subprojects {
  if (project.path.startsWith(':ui')) return
    pluginManager.withPlugin('java') {
      pluginManager.apply('jacoco')
      jacoco { toolVersion = jacocoToolVersion }
    }
}

tasks.register('npmTest') {
  group = 'verification'
  description = 'Runs all UI tests sequentially (component then app)'
}

tasks.register('test') {
  group = 'verification'
  description = 'Executes all backend and UI tests in specific order'
  // When './gradlew test' is run, ensure the UI tests are also pulled into the task graph
  dependsOn 'npmTest'
}

// Enforce order in which we run the backend- and frontend tests
// Order: 1. Unit tests
//     -> 2. Integration tests
//     -> 3. UI component tests
//     -> 4. UI app tests
gradle.projectsEvaluated {
  def unitTests = subprojects.findAll { it.path != ':test' }
  .collect { it.tasks.matching { t -> t.name == 'test' } }

  def integrationTests = subprojects.findAll { it.path == ':test' }
  .collect { it.tasks.matching { t -> t.name == 'test' } }

  def uiComponentTests = subprojects.findAll { it.path.startsWith(':ui:component') }
  .collect { it.tasks.matching { t -> t.name == 'npmTest' } }

  def uiAppTests = subprojects.findAll { it.path.startsWith(':ui:app') }
  .collect { it.tasks.matching { t -> t.name == 'npmTest' } }

  tasks.named('npmTest').configure {
    dependsOn(uiComponentTests, uiAppTests)
  }

  def rootTest = tasks.findByName('test') ?: tasks.register('test').get()
  rootTest.configure {
    dependsOn(unitTests, integrationTests, npmTest)
  }

  integrationTests.forEach { group ->
    group.configureEach { it.mustRunAfter(unitTests) }
  }

  uiComponentTests.forEach { group ->
    group.configureEach { it.mustRunAfter(unitTests, integrationTests) }
  }

  uiAppTests.forEach { group ->
    group.configureEach { it.mustRunAfter(unitTests, integrationTests, uiComponentTests) }
  }
}

dependencies {
  subprojects.forEach { subproject ->
    if (subproject.path.startsWith(':ui')) return
      subproject.pluginManager.withPlugin('java') {
        // Aggregate unit test results spread over different projects
        if (subproject.path != ':test') {
          testReportAggregation project(subproject.path)
        }
      }
  }
}

reporting {
  reports {
    // Task which generates an aggregated unit test report
    unitTestReport(AggregateTestReport) {
      testSuiteName = 'test'
    }
  }
}

tasks.named('unitTestReport').configure {
  doLast {
    def htmlIndex = new File(destinationDirectory.get().asFile, "index.html")
    println "Aggregated Unit Test Results: file://${htmlIndex.absolutePath}"
  }
}

def backendProjects = subprojects.findAll {
  !it.path.startsWith(':ui') && it.pluginManager.hasPlugin('java')
}

def backendTestTasks = backendProjects.collectMany { backendProject ->
  backendProject.tasks.withType(Test).matching { it.name == 'test' }.toList()
}

def backendTestTaskPaths = backendTestTasks.collect { it.path }

def jacocoExecutionDataFiles = backendTestTasks.collect { testTask ->
  testTask.extensions.findByType(JacocoTaskExtension)?.destinationFile
}.findAll { it != null }

def backendSourceDirs = backendProjects.collectMany {
  it.sourceSets.main.allJava.srcDirs
}

def backendClassDirs = backendProjects.collectMany {
  it.sourceSets.main.output.classesDirs.files
}

tasks.register('checkCoverageDataExists') {
  group = 'reporting'

  mustRunAfter backendTestTaskPaths

  inputs.files(jacocoExecutionDataFiles).optional()

  doLast {
    def missingJacocoResults = jacocoExecutionDataFiles.findAll {
      !it.exists()
    }

    if (!missingJacocoResults.empty) {
      println "Please run the following tasks to be able to generate a report."
      println "Required tasks: ${backendTestTaskPaths.join(', ')}"
      println "Run: gradle test -x npmTest checkCoverageDataExists"
      throw new StopExecutionException()
    }
  }
}

// We replace the 'jacoco-report-aggregation' plugin with the following task to
// ensure we get a combined coverage report for the unit- and integration tests
tasks.register('combinedCoverageReport', JacocoReport) {
  group = 'reporting'
  description = 'Generates a unified coverage report for all Unit and Integration tests'

  dependsOn tasks.named('checkCoverageDataExists')
  mustRunAfter backendTestTaskPaths

  reports {
    xml.required = true
    html.required = true
  }

  executionData.setFrom(jacocoExecutionDataFiles)

  sourceDirectories.setFrom(backendSourceDirs)

  classDirectories.setFrom(files(backendClassDirs).asFileTree.matching {
    include 'org/openremote/**'
  })

  doLast {
    def htmlIndex = new File(reports.html.outputLocation.get().asFile, "index.html")
    println "Combined Code Coverage: file://${htmlIndex.absolutePath}"
  }
}

// Configure version based on Git tags
scmVersion {
  releaseOnlyOnReleaseBranches = true
  releaseBranchNames = ['main']
  unshallowRepoOnCI.set(true)
  versionCreator('simple')
  versionIncrementer('incrementMinor')
  repository {
    remote.set('origin')
  }
  tag {
    prefix.set('')
    // This deserializer prevents errors when tags exist that cannot be deserialized
    deserializer({config, position, tagName ->
      tagName ==~ /^[0-9]+\.[0-9]+\.[0-9]+$/ ? tagName : "1.1.0"
    })
    initialVersion({config, position -> '1.2.0'})
  }
}

allprojects {
  apply from: "${rootDir}/project.gradle"
  version = rootProject.scmVersion.version
}

// Uncomment the following to configure files to be encrypted/decrypted
// Each file must be explicitly added to .gitignore otherwise git commit will fail
// When using encryption the the GFE_PASSWORD environment variable must be set or the build will fail
// use ./gradlew encryptFiles to encrypt files
gradleFileEncrypt {
  // files to encrypt
  plainFiles.from('deployment/manager/fcm.json')
  // (optional) setup file mapping to store all encrypted files in one place for example
  //mapping = [ 'deployment/mySensitiveFile' : 'secrets/mySensitiveFile' ]
  // Use custom password provider as standard env mechanism doesn't seem to work
  passwordProvider = {
    def password = System.env.GFE_PASSWORD
    return password != null ? password.toCharArray() : ''.toCharArray()
  }
}

nexusPublishing {
  repositories {
    sonatype {
      nexusUrl = uri(findProperty('releasesRepoUrl'))
      snapshotRepositoryUrl = uri(findProperty('snapshotsRepoUrl'))
      username = findProperty('publishUsername')
      password = findProperty('publishPassword')
    }
  }
}
group = 'io.openremote'

tasks.register('checkFilesGitIgnoredNew', Exec) {
  // The provided checkFilesGitIgnored task doesn't work on Windows so here's one that does
  def args = []
  if (isFamily(FAMILY_WINDOWS)) {
    args.add('cmd')
    args.add('/c')
  }
  args.add('git')
  args.add('check-ignore')
  args.add('-q')
  args.addAll(project.extensions.getByName('gradleFileEncrypt').plainFiles.files)

  commandLine args
}
// openremote .git dir doesn't exist when used as a submodule
def gitFile = Paths.get(projectDir.path, '.git').toFile()
checkFilesGitIgnoredNew.enabled = gitFile.exists() && gitFile.isDirectory()

tasks.named('clean') {
  delete 'tmp'
}

subprojects {
  // Search across all java projects for a runtime dependency e.g. ./gradlew insightRuntime --dependency my-dep
  plugins.withId('java') {
    tasks.register("insightRuntime", DependencyInsightReportTask) {
      configuration = configurations.runtimeClasspath
      showingAllVariants = false
    }
  }

  // Apply only if the project has a 'test' task
  tasks.withType(Test).configureEach { testTask ->
    outputs.upToDateWhen { false } // Always invalidate the test cache
    useJUnitPlatform()

    systemProperty "junit.jupiter.execution.parallel.enabled", "true"
    systemProperty "junit.jupiter.execution.parallel.mode.default", "concurrent"
    systemProperty "junit.jupiter.execution.parallel.mode.classes.default", "concurrent"

    testLogging {

      // set options for log level LIFECYCLE
      events = [TestLogEvent.FAILED, TestLogEvent.PASSED, TestLogEvent.SKIPPED]
      exceptionFormat = TestExceptionFormat.FULL
      showExceptions = true
      showCauses = true
      showStackTraces = true

      // set options for log level DEBUG and INFO
      debug {
        events = [
          TestLogEvent.STARTED,
          TestLogEvent.FAILED,
          TestLogEvent.PASSED,
          TestLogEvent.SKIPPED,
          TestLogEvent.STANDARD_OUT,
          TestLogEvent.STANDARD_ERROR
        ]
        exceptionFormat = TestExceptionFormat.FULL
      }
      info.events = debug.events
      info.exceptionFormat = debug.exceptionFormat
    }

    addTestListener(new TestSummaryListener())
  }

  afterEvaluate { proj ->
    tasks.withType(Test).configureEach { testTask ->
      workingDir = findProject(":openremote") != null ? project("").projectDir : rootProject.projectDir
    }

    if (proj.plugins.hasPlugin('java')) {
      def entityAnnotation = 'Ljakarta/persistence/Entity;'

      proj.tasks.register('checkJpaEntitiesEquality') {
        group = 'verification'
        description = 'Ensure all JPA entities implement equals() and hashCode()'
        dependsOn proj.tasks.named('classes')

        doLast {
          proj.sourceSets.main.output.classesDirs.each { dir ->
            if (!dir.exists()) return

              dir.eachFileRecurse { file ->
                if (file.name.endsWith('.class')) {
                  def reader = new org.objectweb.asm.ClassReader(file.bytes)
                  def classNode = new org.objectweb.asm.tree.ClassNode()
                  reader.accept(classNode, 0)

                  def isEntity = classNode.visibleAnnotations?.any {
                    it.desc == entityAnnotation
                  }

                  if (isEntity) {
                    def methodNames = classNode.methods*.name
                    def className = classNode.name.replace('/', '.')

                    def missing = []
                    if (!methodNames.contains('equals')) missing << 'equals()'
                    if (!methodNames.contains('hashCode')) missing << 'hashCode()'

                    if (!missing.isEmpty()) {
                      println "❌ Entity $className is missing: ${missing.join(', ')}"
                    }
                  }
                }
              }
          }
        }
      }
    }
  }
}