forked from uPortal-Project/uPortal
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.gradle
More file actions
863 lines (777 loc) · 31.2 KB
/
build.gradle
File metadata and controls
863 lines (777 loc) · 31.2 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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
plugins {
// Top level plugins
id 'com.github.kt3k.coveralls' version '2.12.2'
id 'com.github.node-gradle.node' version '7.1.0'
id 'net.researchgate.release' version '3.1.0'
// Records all tasks in task graph, generates `build/reports/visteg.dot`
// dot file can be converted to an image using graphviz. `dot -Tsvg -O -v visteg.dot`
// id 'cz.malohlava.visteg' version '1.0.5'
// Sub project plugins
id 'com.github.sherter.google-java-format' version '0.9' apply false
id 'nebula.lint' version '17.8.0' apply false
id 'net.ltgt.errorprone' version '4.4.0' apply false
id 'com.github.spotbugs' version '4.8.0' apply false
}
description = "Apereo uPortal $version"
/*======== Dependency Management ========**/
repositories {
jcenter()
mavenCentral()
mavenLocal()
}
node {
version = nodejsVersion
download = true
}
if (!rootProject.ext.has('testModuleSummaries')) {
rootProject.ext.testModuleSummaries = []
}
allprojects {
apply plugin: 'java'
apply plugin: 'java-library'
apply plugin: 'jacoco'
apply plugin: 'eclipse'
apply plugin: 'com.github.spotbugs'
apply plugin: 'idea'
apply plugin: 'nebula.lint'
apply plugin: 'groovy'
apply plugin: 'codenarc'
apply plugin: 'com.github.sherter.google-java-format'
apply plugin: 'net.ltgt.errorprone'
configurations {
// Banned dependencies
all*.exclude group: 'commons-logging', module: 'commons-logging'
all*.exclude group: 'commons-logging', module: 'commons-logging-api'
all*.exclude group: 'log4j', module: 'log4j'
all*.exclude group: 'org.hamcrest', module: 'hamcrest-core'
}
dependencies {
errorprone 'com.google.errorprone:error_prone_core:2.3.4'
errorproneJavac "com.google.errorprone:javac:9+181-r4173-1"
}
codenarc {
toolVersion = '3.7.0-groovy-4.0'
reportFormat = 'console'
}
// Version has to be set directly here, using a variable does not set Java compatability version
sourceCompatibility = 11
gradleLint.criticalRules = [
'overridden-dependency-version',
'dependency-parentheses',
'dependency-tuple',
'empty-closure',
'duplicate-dependency-class'
]
/*======== Static Analysis ========*/
spotbugs {
toolVersion = '4.9.8'
// allow build to continue to other sub projects
ignoreFailures = true
}
tasks.withType(com.github.spotbugs.snom.SpotBugsTask) {
enabled = gradle.startParameter.taskNames.contains(it.name)
reports {
html {
enabled = true
destination = file("$buildDir/reports/spotbugs/main/spotbugs.html")
stylesheet = 'fancy-hist.xsl'
}
}
}
googleJavaFormat {
toolVersion '1.7'
options style: 'AOSP'
exclude '**/generated-sources'
}
/*======== Aggregate Dependencies Report ========*/
task dependenciesRecursive(type: DependencyReportTask) {
group = 'Help'
description = 'Provides a complete report on project dependencies; use option (e.g.) --configuration compile to narrow'
}
tasks.withType(Test).configureEach { testTask ->
afterSuite { desc, result ->
if (!desc.parent) {
// Store summary; do not print now
rootProject.ext.testModuleSummaries << [
projectPath: project.path,
taskPath : testTask.path,
resultType : result.resultType,
executed : result.testCount,
passed : result.successfulTestCount,
failed : result.failedTestCount,
skipped : result.skippedTestCount,
durationMs : (result.endTime - result.startTime)
]
}
}
}
}
gradle.buildFinished { buildResult ->
def summaries = rootProject.ext.has('testModuleSummaries') ? rootProject.ext.testModuleSummaries : []
if (!summaries || summaries.isEmpty()) {
return
}
println "=== All Module Test Summaries (${buildResult.failure ? 'BUILD FAILURE' : 'BUILD SUCCESS'}) ==="
summaries.sort { it.projectPath }.each { s ->
println "Module ${s.projectPath} (${s.taskPath}): ${s.resultType} - ${s.executed} executed, ${s.passed} passed, ${s.failed} failed, ${s.skipped} skipped in ${s.durationMs} ms"
}
def total = summaries.inject([e:0,p:0,f:0,s:0,d:0]) { acc, m ->
acc.e += m.executed; acc.p += m.passed; acc.f += m.failed; acc.s += m.skipped; acc.d += m.durationMs; acc
}
println "=== Aggregate Test Summary: ${total.e} executed, ${total.p} passed, ${total.f} failed, ${total.s} skipped (sum durations ${total.d} ms) ==="
}
/*======== Child Projects ========*/
subprojects {
/*======== Plugins ========*/
apply plugin: 'maven-publish'
apply plugin: 'maven'
apply plugin: 'signing'
/*======== Dependency Management ========**/
repositories {
mavenLocal()
mavenCentral()
maven { url "https://jitpack.io" }
}
dependencies {
testImplementation "junit:junit:${junitVersion}"
testImplementation "org.easymock:easymock:${easymockVersion}"
testImplementation "org.hamcrest:hamcrest-all:${hamcrestVersion}"
testImplementation "org.mockito:mockito-core:${mockitoVersion}"
testImplementation "org.springframework:spring-test:${springVersion}"
testImplementation "org.xmlunit:xmlunit-legacy:${xmlunitVersion}"
spotbugsPlugins 'com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0'
}
/* Release Management
*
* Based on Sonatype's guide for publishing w/ Gradle: https://central.sonatype.org/publish/publish-portal-ossrh-staging-api/
*
* OSSRH was sunset June 2025. Publishing now goes through the Central Portal's
* OSSRH Staging API compatibility service. Credentials must be Central Portal
* user tokens (generate at https://central.sonatype.com).
*/
ext {
publishingUsername = project.hasProperty('ossrhUsername') ? project.getProperty('ossrhUsername') : ""
publishingPassword = project.hasProperty('ossrhPassword') ? project.getProperty('ossrhPassword') : ""
publishingRepositoryUrl = project.hasProperty('ossrhUrl') ? project.getProperty('ossrhUrl') : "https://ossrh-staging-api.central.sonatype.com/service/local/staging/deploy/maven2/"
publishingRepositoryUrlSnapshot = project.hasProperty('ossrhUrlSnapshot') ? project.getProperty('ossrhUrlSnapshot') : "https://central.sonatype.com/repository/maven-snapshots/"
}
signing {
required { gradle.taskGraph.hasTask('uploadArchives') }
sign configurations.archives
}
tasks.withType(Javadoc).all {
// disable JavaDocs until we start using them again in our website
enabled = false
}
tasks.withType(Jar) {
from(project.projectDir) {
include "${rootDir}/LICENSE"
into 'META-INF'
}
}
task sourcesJar(type: Jar, dependsOn: classes) {
classifier 'sources'
from sourceSets.main.allSource
}
task javadocJar(type: Jar, dependsOn: javadoc) {
classifier = 'javadoc'
from javadoc.destinationDir
}
artifacts {
archives javadocJar, sourcesJar
}
publishing {
publications {
maven(MavenPublication) {
from components.java
}
}
}
uploadArchives {
repositories {
mavenDeployer {
beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }
repository(url: publishingRepositoryUrl) {
authentication(userName: publishingUsername, password: publishingPassword)
}
snapshotRepository(url: publishingRepositoryUrlSnapshot) {
authentication(userName: publishingUsername, password: publishingPassword)
}
pom.project {
name 'uPortal'
packaging project.plugins.hasPlugin('war') ? 'war' : 'jar'
// optionally artifactId can be defined here
description 'Enterprise open source portal built by and for the higher education community.'
url 'https://github.com/uPortal-Project/uPortal'
scm {
connection 'scm:git@github.com:uPortal-Project/uPortal.git'
url 'https://github.com/uPortal-Project/uPortal'
}
licenses {
license {
name 'The Apache License, Version 2.0'
url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
}
}
developers {
developer {
organization 'uPortal Developers'
organizationUrl 'https://github.com/uPortal-Project/uPortal/graphs/contributors'
}
}
}
}
}
}
afterReleaseBuild.dependsOn uploadArchives
def jacocoExecutionDataFiles = fileTree(buildDir).include("/jacoco/*.exec")
jacocoTestReport {
getExecutionData().setFrom(jacocoExecutionDataFiles)
}
}
/*
* Configuration for the 'gradle-release' plugin (https://github.com/researchgate/gradle-release)
*/
release {
tagTemplate = 'v${version}' // Looks like it should be a GString, but not necessary
git {
requireBranch.set('')
}
}
task jacocoAggregateReport(type: org.gradle.testing.jacoco.tasks.JacocoReport) {
dependsOn = subprojects.test
getAdditionalSourceDirs().setFrom(files(subprojects.sourceSets.main.allSource.srcDirs))
getSourceDirectories().setFrom(files(subprojects.sourceSets.main.allSource.srcDirs))
getClassDirectories().setFrom(files(subprojects.sourceSets.main.output))
getExecutionData().setFrom(files(subprojects.jacocoTestReport.executionData))
reports {
xml.enabled = true
html.enabled = true
}
onlyIf = {
true
}
doFirst {
getExecutionData().setFrom(files(getExecutionData().findAll {
it.exists()
}))
}
}
coveralls {
jacocoReportPath = "${buildDir}/reports/jacoco/jacocoAggregateReport/jacocoAggregateReport.xml"
sourceDirs = files(allprojects.sourceSets.main.allSource.srcDirs).files.absolutePath
}
/**
* CRAP Score Analysis Task
* ========================
* Add this to the end of your root build.gradle file
*
* Calculates CRAP (Change Risk Anti-Patterns) score for all methods
* CRAP = complexity² × (1 - coverage)³ + complexity
*
* Methods with CRAP > 30 are considered high-risk and should be:
* - Tested thoroughly before modification, OR
* - Refactored to reduce complexity first
*
* Usage: ./gradlew crapAnalysis
* Output: build/reports/crap-analysis/
*/
task crapAnalysis {
group = 'verification'
description = 'Analyzes code coverage gaps using CRAP score to prioritize testing efforts'
dependsOn jacocoAggregateReport
doLast {
def jacocoXml = file("${buildDir}/reports/jacoco/jacocoAggregateReport/jacocoAggregateReport.xml")
if (!jacocoXml.exists()) {
throw new GradleException("JaCoCo report not found. Run 'jacocoAggregateReport' first.")
}
def outputDir = file("${buildDir}/reports/crap-analysis")
outputDir.mkdirs()
println "Parsing JaCoCo report: ${jacocoXml}"
// Load the Jacoco XML as text and remove any DOCTYPE to avoid parser restrictions
def xmlText = jacocoXml.getText('UTF-8')
xmlText = xmlText.replaceAll(/(?s)<!DOCTYPE.*?>/, '')
def report = new XmlSlurper(false, false).parseText(xmlText)
def methods = []
def packageStats = [:]
// Parse JaCoCo XML structure
report.package.each { pkg ->
def packageName = pkg.@name.text().replace('/', '.')
if (!packageStats[packageName]) {
packageStats[packageName] = [
name: packageName,
totalComplexity: 0,
coveredComplexity: 0,
methodCount: 0,
uncoveredMethods: 0,
files: [] as Set
]
}
pkg.sourcefile.each { srcFile ->
def fileName = srcFile.@name.text()
packageStats[packageName].files.add(fileName)
def className = fileName.replaceAll('\\.java$', '').replaceAll('\\.groovy$', '')
srcFile.line.each { line ->
def lineNum = line.@nr.text()
def missedInstructions = (line.@mi.text() ?: '0') as int
def coveredInstructions = (line.@ci.text() ?: '0') as int
def missedBranches = (line.@mb.text() ?: '0') as int
def coveredBranches = (line.@cb.text() ?: '0') as int
// Estimate complexity from branches (rough approximation)
def totalBranches = missedBranches + coveredBranches
if (totalBranches > 0) {
def complexity = totalBranches + 1
def totalInstructions = missedInstructions + coveredInstructions
def coverage = totalInstructions > 0 ? (coveredInstructions / totalInstructions) : 0.0
def crapScore = calculateCrap(complexity, coverage)
methods.add([
package: packageName,
class: className,
line: lineNum,
complexity: complexity,
coverage: coverage * 100,
coveredBranches: coveredBranches,
missedBranches: missedBranches,
crapScore: crapScore
])
packageStats[packageName].totalComplexity += complexity
packageStats[packageName].coveredComplexity += complexity * coverage
packageStats[packageName].methodCount++
if (coverage < 0.5) {
packageStats[packageName].uncoveredMethods++
}
}
}
}
}
// Sort by CRAP score (highest first)
methods.sort { -it.crapScore }
// Generate reports
generateHtmlReport(methods, packageStats, outputDir)
generateCsvReport(methods, outputDir)
// Print summary
printSummary(methods, packageStats, outputDir)
}
}
def calculateCrap(int complexity, double coverage) {
// CRAP = complexity² × (1 - coverage)³ + complexity
def uncoverage = 1.0 - coverage
return (complexity * complexity * Math.pow(uncoverage, 3)) + complexity
}
def printSummary(methods, packageStats, outputDir) {
println "\n" + "=".multiply(80)
println "CRAP ANALYSIS SUMMARY"
println "=".multiply(80)
println "Total decision points analyzed: ${methods.size()}"
println "High-risk (CRAP > 30): ${methods.count { it.crapScore > 30 }}"
println "Medium-risk (CRAP 10-30): ${methods.count { it.crapScore > 10 && it.crapScore <= 30 }}"
println "Low-risk (CRAP < 10): ${methods.count { it.crapScore <= 10 }}"
println "\n📊 Top 10 highest CRAP scores:"
methods.take(10).eachWithIndex { m, idx ->
println sprintf(" %2d. CRAP: %6.1f | Complexity: %3d | Coverage: %5.1f%% | %s.%s:%s",
idx + 1, m.crapScore, m.complexity, m.coverage, m.package, m.class, m.line)
}
println "\n📦 Packages with most untested complexity:"
packageStats.values()
.sort { -(it.totalComplexity - it.coveredComplexity) }
.take(5).eachWithIndex { pkg, idx ->
def uncoveredComplexity = pkg.totalComplexity - pkg.coveredComplexity
def uncoveredComplexityInt = (uncoveredComplexity as int)
def coveragePercent = pkg.totalComplexity > 0 ?
(pkg.coveredComplexity / (pkg.totalComplexity as double) * 100.0) : 0.0
println sprintf(" %d. %s", idx + 1, pkg.name)
println sprintf(" Uncovered complexity: %d points (%.1f%% coverage, %d decision points)",
uncoveredComplexityInt, coveragePercent, pkg.methodCount)
}
println "\n📄 Reports generated:"
println " HTML: ${outputDir}/crap-report.html"
println " CSV: ${outputDir}/crap-report.csv"
println "\n💡 Next steps:"
println " 1. Open the HTML report in your browser"
println " 2. Focus on methods with CRAP > 30 (high-risk)"
println " 3. Either add tests OR refactor to reduce complexity"
println "=".multiply(80) + "\n"
}
def generateCsvReport(methods, outputDir) {
def csvFile = new File(outputDir, "crap-report.csv")
csvFile.withWriter { writer ->
writer.writeLine("Rank,CRAP Score,Complexity,Coverage %,Covered Branches,Missed Branches,Package,Class,Line")
methods.eachWithIndex { m, idx ->
writer.writeLine("${idx + 1},${String.format('%.2f', m.crapScore)},${m.complexity},${String.format('%.1f', m.coverage)},${m.coveredBranches},${m.missedBranches},\"${m.package}\",\"${m.class}\",${m.line}")
}
}
}
def generateHtmlReport(methods, packageStats, outputDir) {
def htmlFile = new File(outputDir, "crap-report.html")
htmlFile.text = """<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>CRAP Score Analysis Report</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, sans-serif;
margin: 0;
padding: 20px;
background: #f5f5f5;
}
.container {
max-width: 1400px;
margin: 0 auto;
background: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
h1 {
color: #333;
border-bottom: 3px solid #4CAF50;
padding-bottom: 10px;
margin-top: 0;
}
h2 {
color: #555;
margin-top: 30px;
border-bottom: 2px solid #ddd;
padding-bottom: 8px;
}
.summary {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 15px;
margin: 20px 0;
}
.summary-card {
background: #f9f9f9;
padding: 20px;
border-radius: 8px;
border-left: 4px solid #4CAF50;
transition: transform 0.2s;
}
.summary-card:hover {
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
.summary-card.high { border-left-color: #f44336; }
.summary-card.medium { border-left-color: #ff9800; }
.summary-card h3 {
margin: 0 0 8px 0;
font-size: 14px;
color: #666;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.summary-card .value {
font-size: 32px;
font-weight: bold;
color: #333;
}
table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
background: white;
}
th {
background: #4CAF50;
color: white;
padding: 12px;
text-align: left;
font-weight: 600;
position: sticky;
top: 0;
z-index: 10;
}
td {
padding: 10px 12px;
border-bottom: 1px solid #eee;
}
tr:hover {
background: #f5f5f5;
transition: background 0.2s;
}
.crap-high {
color: #f44336;
font-weight: bold;
font-size: 16px;
}
.crap-medium {
color: #ff9800;
font-weight: bold;
}
.crap-low {
color: #4CAF50;
}
.coverage-bad { background: #ffebee; }
.coverage-medium { background: #fff3e0; }
.coverage-good { background: #e8f5e9; }
.pkg-name {
font-family: 'Courier New', monospace;
font-size: 12px;
color: #666;
}
.filter {
margin: 20px 0;
padding: 15px;
background: #f9f9f9;
border-radius: 6px;
}
.filter input {
padding: 10px;
width: 300px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 14px;
}
.filter input:focus {
outline: none;
border-color: #4CAF50;
}
.tabs {
display: flex;
gap: 10px;
margin: 20px 0;
border-bottom: 2px solid #ddd;
}
.tab {
padding: 12px 24px;
cursor: pointer;
background: #f5f5f5;
border: none;
border-radius: 6px 6px 0 0;
font-size: 14px;
font-weight: 500;
transition: all 0.2s;
}
.tab:hover {
background: #e8e8e8;
}
.tab.active {
background: #4CAF50;
color: white;
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
.guide {
background: #f9f9f9;
padding: 20px;
border-radius: 8px;
margin: 20px 0;
border-left: 4px solid #2196F3;
}
.guide h3 {
margin-top: 0;
color: #333;
}
.guide ul {
margin: 10px 0;
}
.guide li {
margin: 5px 0;
}
.formula {
background: #e3f2fd;
padding: 15px;
border-radius: 6px;
font-family: 'Courier New', monospace;
margin: 15px 0;
border-left: 4px solid #2196F3;
}
@media (max-width: 768px) {
.container {
padding: 15px;
}
.summary {
grid-template-columns: 1fr;
}
table {
font-size: 12px;
}
th, td {
padding: 8px;
}
}
</style>
<script>
function filterTable() {
const input = document.getElementById('searchInput');
const filter = input.value.toUpperCase();
const table = document.getElementById('methodsTable');
const tr = table.getElementsByTagName('tr');
for (let i = 1; i < tr.length; i++) {
const row = tr[i];
const text = row.textContent || row.innerText;
row.style.display = text.toUpperCase().indexOf(filter) > -1 ? '' : 'none';
}
}
function showTab(tabName) {
const tabs = document.querySelectorAll('.tab');
const contents = document.querySelectorAll('.tab-content');
tabs.forEach(t => t.classList.remove('active'));
contents.forEach(c => c.classList.remove('active'));
const btn = document.querySelector('.tab[data-tab="' + tabName + '"]');
if (btn) btn.classList.add('active');
const content = document.getElementById(tabName);
if (content) content.classList.add('active');
}
document.addEventListener('DOMContentLoaded', function () {
document.querySelectorAll('.tab[data-tab]').forEach(function (b) {
b.addEventListener('click', function () { showTab(b.getAttribute('data-tab')); });
});
});
</script>
</head>
<body>
<div class="container">
<h1>🎯 CRAP Score Analysis Report</h1>
<p><strong>Generated:</strong> ${new Date().format('yyyy-MM-dd HH:mm:ss')}</p>
<div class="formula">
<strong>CRAP Formula:</strong> complexity² × (1 - coverage)³ + complexity
</div>
<div class="summary">
<div class="summary-card high">
<h3>High Risk</h3>
<div class="value">${methods.count { it.crapScore > 30 }}</div>
<div style="font-size: 12px; color: #666; margin-top: 5px;">CRAP > 30</div>
</div>
<div class="summary-card medium">
<h3>Medium Risk</h3>
<div class="value">${methods.count { it.crapScore > 10 && it.crapScore <= 30 }}</div>
<div style="font-size: 12px; color: #666; margin-top: 5px;">CRAP 10-30</div>
</div>
<div class="summary-card">
<h3>Low Risk</h3>
<div class="value">${methods.count { it.crapScore <= 10 }}</div>
<div style="font-size: 12px; color: #666; margin-top: 5px;">CRAP < 10</div>
</div>
<div class="summary-card">
<h3>Total Analyzed</h3>
<div class="value">${methods.size()}</div>
<div style="font-size: 12px; color: #666; margin-top: 5px;">Decision points</div>
</div>
</div>
<div class="tabs">
<button class="tab active" data-tab="methods">Methods by CRAP Score</button>
<button class="tab" data-tab="packages">Packages Overview</button>
<button class="tab" data-tab="guide">How to Use</button>
</div>
<div id="methods" class="tab-content active">
<h2>Methods Ranked by CRAP Score</h2>
<div class="filter">
<input type="text" id="searchInput" onkeyup="filterTable()"
placeholder="🔍 Filter by package, class, or line number...">
</div>
<table id="methodsTable">
<thead>
<tr>
<th>Rank</th>
<th>CRAP Score</th>
<th>Complexity</th>
<th>Coverage %</th>
<th>Branches (✓/✗)</th>
<th>Package</th>
<th>Class</th>
<th>Line</th>
</tr>
</thead>
<tbody>
${methods.take(500).withIndex().collect { m, idx ->
def crapClass = m.crapScore > 30 ? 'crap-high' : (m.crapScore > 10 ? 'crap-medium' : 'crap-low')
def coverageClass = m.coverage < 30 ? 'coverage-bad' : (m.coverage < 70 ? 'coverage-medium' : 'coverage-good')
""" <tr>
<td>${idx + 1}</td>
<td class="${crapClass}">${String.format('%.2f', m.crapScore)}</td>
<td>${m.complexity}</td>
<td class="${coverageClass}">${String.format('%.1f', m.coverage)}%</td>
<td>${m.coveredBranches}/${m.missedBranches}</td>
<td class="pkg-name">${m.package}</td>
<td>${m.class}</td>
<td>${m.line}</td>
</tr>"""
}.join('\n')}
</tbody>
</table>
${methods.size() > 500 ? "<p><em>Showing top 500 of ${methods.size()} decision points. See CSV for complete data.</em></p>" : ""}
</div>
<div id="packages" class="tab-content">
<h2>Package-Level Coverage Overview</h2>
<p>Packages sorted by uncovered complexity (best opportunities for broad coverage expansion)</p>
<table>
<thead>
<tr>
<th>Package</th>
<th>Files</th>
<th>Decision Points</th>
<th>Total Complexity</th>
<th>Coverage %</th>
<th>Uncovered Complexity</th>
<th>Methods < 50% Coverage</th>
</tr>
</thead>
<tbody>
${packageStats.values().sort { -(it.totalComplexity - it.coveredComplexity) }.collect { pkg ->
def coveragePercent = pkg.totalComplexity > 0 ? (pkg.coveredComplexity / (pkg.totalComplexity as double) * 100.0) : 0.0
def uncoveredComplexity = pkg.totalComplexity - pkg.coveredComplexity
def coverageClass = coveragePercent < 30 ? 'coverage-bad' : (coveragePercent < 70 ? 'coverage-medium' : 'coverage-good')
""" <tr>
<td class="pkg-name">${pkg.name}</td>
<td>${pkg.files.size()}</td>
<td>${pkg.methodCount}</td>
<td>${Math.round(pkg.totalComplexity)}</td>
<td class="${coverageClass}">${String.format('%.1f', coveragePercent)}%</td>
<td><strong>${Math.round(uncoveredComplexity)}</strong></td>
<td>${pkg.uncoveredMethods}</td>
</tr>"""
}.join('\n')}
</tbody>
</table>
</div>
<div id="guide" class="tab-content">
<h2>📖 How to Use This Report</h2>
<div class="guide">
<h3>🔴 Priority 1: CRAP > 30 (High Risk)</h3>
<p>These methods are <strong>dangerous to modify</strong>. Before touching them:</p>
<ul>
<li><strong>Option A:</strong> Add comprehensive tests to bring CRAP below 30</li>
<li><strong>Option B:</strong> Refactor to reduce complexity (break into smaller methods)</li>
<li><strong>Don't:</strong> Modify without doing A or B first</li>
</ul>
<p><em>Even 100% test coverage won't eliminate risk if complexity stays above 30</em></p>
</div>
<div class="guide">
<h3>🟠 Priority 2: CRAP 10-30 (Medium Risk)</h3>
<p>These methods need attention before major changes:</p>
<ul>
<li>Add tests to cover the most critical paths</li>
<li>Consider refactoring if complexity is particularly high</li>
<li>Safe for minor bug fixes, risky for major refactoring</li>
</ul>
</div>
<div class="guide">
<h3>🟢 Priority 3: CRAP < 10 (Low Risk)</h3>
<p>These methods are relatively safe:</p>
<ul>
<li>Can be modified with reasonable confidence</li>
<li>More tests are always beneficial but not urgent</li>
</ul>
</div>
<div class="guide">
<h3>📦 For Broad Coverage Expansion</h3>
<p>Use the "Packages Overview" tab to:</p>
<ul>
<li>Identify entire packages with high uncovered complexity</li>
<li>Focus testing efforts on packages with the most uncovered decision points</li>
<li>Track progress by monitoring "Uncovered Complexity" decreasing over time</li>
</ul>
<p><strong>Strategy:</strong> Pick packages with high uncovered complexity and work through their high-CRAP methods systematically</p>
</div>
</div>
</div>
</body>
</html>"""
}