forked from openremote/openremote
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.gradle
More file actions
362 lines (307 loc) · 12.7 KB
/
build.gradle
File metadata and controls
362 lines (307 loc) · 12.7 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
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
apply plugin: 'java-base'
apply plugin: 'test-report-aggregation'
apply plugin: 'jacoco'
jacoco {
toolVersion = "0.8.14"
}
subprojects {
if (project.path.startsWith(':ui')) return
pluginManager.withPlugin('java') {
apply plugin: 'jacoco'
jacoco { toolVersion = "0.8.14" }
}
}
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 getBackendProjects = {
subprojects.findAll { !it.path.startsWith(':ui') && it.pluginManager.hasPlugin('java') }
}
def getActiveTestTasks = {
getBackendProjects().collectMany { it.tasks.withType(Test) }.findAll { it.name == 'test' }
}
tasks.register('checkCoverageDataExists') {
group = 'reporting'
mustRunAfter(getBackendProjects().collect { "${it.path}:test" })
doLast {
def testTasks = getActiveTestTasks()
def allJacocoResultsExist = testTasks.every {
it.extensions.findByType(JacocoTaskExtension)?.destinationFile?.exists()
}
// Check if any of the configured execution data files exist on disk
if (!allJacocoResultsExist) {
println "Please run the following tasks to be able to generate a report."
println "Required tasks: ${testTasks.collect { it.path }.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('checkCoverageDataExists')
mustRunAfter(getBackendProjects().collect { "${it.path}:test" })
reports {
xml.required = true
html.required = true
}
executionData.setFrom(project.provider {
getActiveTestTasks().collect {
it.extensions.findByType(JacocoTaskExtension)?.destinationFile
}.findAll { it != null && it.exists() }
})
sourceDirectories.setFrom(project.provider {
getBackendProjects().collectMany { it.sourceSets.main.allJava.srcDirs }
})
classDirectories.setFrom(project.provider {
def dirs = getBackendProjects().collectMany { it.sourceSets.main.output.classesDirs.files }
files(dirs).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
apply plugin: 'pl.allegro.tech.build.axion-release'
scmVersion {
releaseOnlyOnReleaseBranches = true
releaseBranchNames = ['main', 'master']
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: "${findProject(':openremote') != null ? project(':openremote').projectDir : rootDir}/project.gradle"
version = 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
apply plugin: 'io.openremote.com.cherryperry.gradle-file-encrypt'
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()
}
}
apply plugin: 'io.github.gradle-nexus.publish-plugin'
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.getProperties().get('gradleFileEncrypt').plainFiles)
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'
}
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.ow2.asm:asm:9.5'
classpath 'org.ow2.asm:asm-tree:9.5'
}
}
subprojects {
// 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 TestListener() {
@Override
void beforeSuite(TestDescriptor suite) {}
@Override
void afterSuite(TestDescriptor desc, TestResult result) {
if (!desc.parent) { // will match the outermost suite
def output = "Results: ${result.resultType} (${result.testCount} tests, ${result.successfulTestCount} passed, ${result.failedTestCount} failed, ${result.skippedTestCount} skipped)"
def startItem = '| ', endItem = ' |'
def repeatLength = startItem.length() + output.length() + endItem.length()
println('\n' + ('-' * repeatLength) + '\n' + startItem + output + endItem + '\n' + ('-' * repeatLength))
}
}
@Override
void beforeTest(TestDescriptor desc) {}
@Override
void afterTest(TestDescriptor desc, TestResult result) {
logger.lifecycle "${desc.className} > ${desc.name} took: ${(result.endTime - result.startTime)}ms"
}
})
}
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(', ')}"
}
}
}
}
}
}
}
}
}
}