-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.gradle
More file actions
818 lines (704 loc) · 34 KB
/
build.gradle
File metadata and controls
818 lines (704 loc) · 34 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
plugins {
id "java"
id "edu.wpi.first.GradleRIO" version "2026.2.1"
id "com.diffplug.spotless" version "8.4.0"
id "jacoco"
id "pmd"
id "checkstyle"
id "net.ltgt.errorprone" version "5.1.0"
id "com.adarshr.test-logger" version "4.0.0"
id "com.github.ben-manes.versions" version "0.53.0"
id "maven-publish"
}
testlogger {
theme = 'mocha'
showExceptions = true
showStackTraces = true
showFullStackTraces = false
showCauses = true
slowThreshold = 2000
showSummary = true
showSimpleNames = false
showPassed = true
showSkipped = true
showFailed = true
}
java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
def ROBOT_MAIN_CLASS = "frc.robot.Main"
// Define my targets (RoboRIO) and artifacts (deployable files)
// This is added by GradleRIO's backing project DeployUtils.
deploy {
targets {
roborio(getTargetTypeClass('RoboRIO')) {
// Team number is loaded either from the .wpilib/wpilib_preferences.json
// or from command line. If not found an exception will be thrown.
// You can use getTeamOrDefault(team) instead of getTeamNumber if you
// want to store a team number in this file.
team = project.frc.getTeamNumber()
debug = project.frc.getDebugOrDefault(false)
artifacts {
// First part is artifact name, 2nd is artifact type
// getTargetTypeClass is a shortcut to get the class type using a string
frcJava(getArtifactTypeClass('FRCJavaArtifact')) {
jvmArgs.add("-XX:+UnlockExperimentalVMOptions")
jvmArgs.add("-XX:GCTimeRatio=5")
jvmArgs.add("-XX:+UseSerialGC")
jvmArgs.add("-XX:MaxGCPauseMillis=50")
// The options below may improve performance, but should only be enabled on the RIO 2
//
// final MAX_JAVA_HEAP_SIZE_MB = 100;
// jvmArgs.add("-Xmx" + MAX_JAVA_HEAP_SIZE_MB + "M")
// jvmArgs.add("-Xms" + MAX_JAVA_HEAP_SIZE_MB + "M")
// jvmArgs.add("-XX:+AlwaysPreTouch")
}
// Static files artifact
frcStaticFileDeploy(getArtifactTypeClass('FileTreeArtifact')) {
files = project.fileTree('src/main/deploy')
directory = '/home/lvuser/deploy'
// Change to true to delete files on roboRIO that no
// longer exist in deploy directory on roboRIO
deleteOldFiles = false
}
}
}
}
}
def deployArtifact = deploy.targets.roborio.artifacts.frcJava
// Set to true to use debug for all targets including JNI, which will drastically impact
// performance.
wpi.java.debugJni = false
// Set this to true to enable desktop support.
def includeDesktopSupport = true
// Configuration for AdvantageKit
task(replayWatch, type: JavaExec) {
mainClass = "org.littletonrobotics.junction.ReplayWatch"
classpath = sourceSets.main.runtimeClasspath
}
// Defining my dependencies. In this case, WPILib (+ friends), and vendor libraries.
// Also defines JUnit 4.
configurations.all {
resolutionStrategy {
force 'com.fasterxml.jackson.core:jackson-annotations:2.15.2'
force 'com.fasterxml.jackson.core:jackson-core:2.15.2'
force 'com.fasterxml.jackson.core:jackson-databind:2.15.2'
}
}
dependencies {
annotationProcessor wpi.java.deps.wpilibAnnotations()
implementation wpi.java.deps.wpilib()
implementation wpi.java.vendor.java()
roborioDebug wpi.java.deps.wpilibJniDebug(wpi.platforms.roborio)
roborioDebug wpi.java.vendor.jniDebug(wpi.platforms.roborio)
roborioRelease wpi.java.deps.wpilibJniRelease(wpi.platforms.roborio)
roborioRelease wpi.java.vendor.jniRelease(wpi.platforms.roborio)
nativeDebug wpi.java.deps.wpilibJniDebug(wpi.platforms.desktop)
nativeDebug wpi.java.vendor.jniRelease(wpi.platforms.desktop)
simulationDebug wpi.sim.enableDebug()
nativeRelease wpi.java.deps.wpilibJniRelease(wpi.platforms.desktop)
nativeRelease wpi.java.vendor.jniRelease(wpi.platforms.desktop)
simulationRelease wpi.sim.enableRelease()
testImplementation 'org.junit.jupiter:junit-jupiter:6.0.3'
testImplementation 'org.mockito:mockito-core:5.11.0'
testImplementation 'org.mockito:mockito-junit-jupiter:5.11.0'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
implementation 'org.dyn4j:dyn4j:4.2.2'
def akitJson = new groovy.json.JsonSlurper().parseText(new File(projectDir.getAbsolutePath() + "/vendordeps/AdvantageKit.json").text)
annotationProcessor "org.littletonrobotics.akit:akit-autolog:$akitJson.version"
errorprone "com.google.errorprone:error_prone_core:2.26.1"
}
test {
useJUnitPlatform()
systemProperty 'junit.jupiter.extensions.autodetection.enabled', 'true'
}
test.finalizedBy jacocoTestReport
jacoco {
toolVersion = "0.8.12"
}
jacocoTestReport {
dependsOn test
reports {
xml.required = true
csv.required = true
html.required = true
}
afterEvaluate {
classDirectories.setFrom(files(classDirectories.files.collect {
fileTree(dir: it, exclude: [
'frc/robot/**',
'**/*IO*.class',
'**/*AutoLogged*.class',
'**/LimelightHelpers*.class',
'gg/questnav/**',
'com/marslib/diagnostics/**',
'com/marslib/hmi/**',
'com/marslib/vision/**',
'com/marslib/util/LogUploader*.class',
'com/marslib/util/LoggedTunableNumber*.class',
'com/marslib/util/SimSysIdTuner*.class',
'com/marslib/testing/**'
])
}))
}
}
pmd {
consoleOutput = true
toolVersion = "6.55.0"
ignoreFailures = false
ruleSets = []
ruleSetFiles = files("config/pmd/ruleset.xml")
}
checkstyle {
toolVersion = "10.12.5"
configFile = file("config/checkstyle/checkstyle.xml")
ignoreFailures = false
showViolations = true
}
tasks.withType(Javadoc) {
options.addBooleanOption('Werror', true)
options.addStringOption('Xdoclint:all,-missing', '-quiet')
// MARSLib branded dark theme
def themeCss = file("${projectDir}/src/main/javadoc/marslib-theme.css")
if (themeCss.exists()) {
options.addStringOption('-add-stylesheet', themeCss.absolutePath)
}
options.windowTitle = 'MARSLib API - FRC Team 2614'
options.docTitle = 'MARSLib API Reference'
options.header = '<a href="../index.html" style="color:#ff6b35;text-decoration:none;font-weight:700;">MARSLib</a> - FRC 2614'
}
// Generate docs site: landing page + themed javadoc
task generateDocs {
description = 'Generates the full MARSLib documentation site into docs/'
dependsOn javadoc, jacocoTestReport
notCompatibleWithConfigurationCache("Uses project copy at execution time")
def docsDir = file("docs")
def javadocDir = layout.buildDirectory.dir("docs/javadoc")
inputs.dir(javadocDir)
outputs.dir("${docsDir}/javadoc")
doLast {
// Copy javadoc output into docs/javadoc
copy {
from javadocDir
into "${docsDir}/javadoc"
}
// Copy controller mappings html
def mappings = file("CONTROLLER_MAPPINGS.html")
if (mappings.exists()) {
copy {
from mappings
into docsDir
}
}
// Dynamic Stats Generation
println "Calculating documentation statistics..."
// 1. Source Files Count
def sourceFiles = 0
def mainSrcDirVar = new File(projectDir, "src/main/java")
if (mainSrcDirVar.exists()) mainSrcDirVar.eachFileRecurse(groovy.io.FileType.FILES) { if (it.name.endsWith('.java')) sourceFiles++ }
// 2. Unit Test Count (Parsing JUnit XML results)
def testCount = 0
def testResultsDir = file("build/test-results/test")
if (testResultsDir.exists()) {
testResultsDir.listFiles().each { f ->
if (f.name.endsWith(".xml")) {
def matcher = f.text =~ /tests="(\d+)"/
if (matcher.find()) {
testCount += matcher.group(1).toInteger()
}
}
}
}
// 3. Line Coverage (Parsing JaCoCo CSV)
def coveragePercent = "0%"
def csvFile = file("build/reports/jacoco/test/jacocoTestReport.csv")
if (csvFile.exists()) {
def linesMissed = 0
def linesCovered = 0
csvFile.eachLine { line, index ->
if (index > 1) { // Skip header
def parts = line.split(',')
if (parts.length >= 9) {
try {
linesMissed += parts[7].toInteger()
linesCovered += parts[8].toInteger()
} catch (Exception e) {}
}
}
}
if (linesCovered + linesMissed > 0) {
coveragePercent = "${Math.round(linesCovered * 100.0 / (linesCovered + linesMissed))}%"
}
}
println "Stats: ${sourceFiles} files, ${testCount} tests, ${coveragePercent} coverage"
// Inject into index.html
def indexFile = file("${docsDir}/index.html")
if (indexFile.exists()) {
def content = indexFile.getText('UTF-8')
content = content.replace('${SOURCE_FILES}', sourceFiles.toString())
content = content.replace('${UNIT_TESTS}', testCount.toString())
content = content.replace('${TOTAL_COVERAGE}', coveragePercent)
indexFile.setText(content, 'UTF-8')
println "Successfully injected stats into index.html"
}
println "Documentation site generated at: ${docsDir.absolutePath}"
println "Open docs/index.html in your browser to preview."
}
}
// 2. Automated vendordeps/ JSON Validation
task validateVendordeps {
description = "Validates the syntax of all JSON files in the vendordeps directory"
def vendordepsDirCaptured = file("vendordeps")
doLast {
if (vendordepsDirCaptured.exists()) {
def slurper = new groovy.json.JsonSlurper()
vendordepsDirCaptured.listFiles().each { f ->
if (f.name.endsWith(".json")) {
try {
slurper.parseText(f.text)
} catch (Exception e) {
throw new GradleException("Found invalid JSON syntax in vendordep: ${f.name}\\n${e.getMessage()}")
}
}
}
}
}
}
compileJava.dependsOn validateVendordeps
task installGitHooks {
description = "Installs a pre-commit git hook to run spotlessApply and tests"
def rootDirString = rootProject.rootDir.absolutePath
doLast {
def hookDir = new File(rootDirString, '.git/hooks')
if (!hookDir.exists()) return
def hookFile = new File(hookDir, 'pre-commit')
hookFile.text = '''#!/bin/sh
echo "Running spotlessApply and tests on staged files before commit..."
# Get list of staged files
staged_files=$(git diff --cached --name-only --diff-filter=ACM | grep '\\.java$')
# If no java files are staged, just exit and allow commit
if [ -z "$staged_files" ]; then
exit 0
fi
# Apply spotless and run tests
./gradlew spotlessApply test
if [ $? -ne 0 ]; then
echo "Tests or formatting failed. Please fix before committing."
exit 1
fi
# Re-stage only the files that were originally staged, in case spotless modified them
for file in $staged_files; do
if [ -f "$file" ]; then
git add "$file"
fi
done
'''
if (!System.getProperty("os.name").toLowerCase().contains("windows")) {
[
'chmod',
'+x',
hookFile.absolutePath
].execute()
}
}
}
// Simulation configuration (e.g. environment variables).
//
// The sim GUI is *disabled* by default to support running
// AdvantageKit log replay, which requires that all HAL
// sim extensions be disabled.
wpi.sim.addGui().defaultEnabled = true
wpi.sim.addDriverstation()
// Setting up my Jar File. In this case, adding all libraries into the main jar ('fat jar')
// in order to make them all available at runtime. Also adding the manifest so WPILib
// knows where to look for our Robot Class.
jar {
from { configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } }
from sourceSets.main.allSource
manifest edu.wpi.first.gradlerio.GradleRIOPlugin.javaManifest(ROBOT_MAIN_CLASS)
duplicatesStrategy = DuplicatesStrategy.INCLUDE
}
// Configure jar and deploy tasks
deployArtifact.jarTask = jar
wpi.java.configureExecutableTasks(jar)
wpi.java.configureTestTasks(test)
// Configure string concat to always inline compile
tasks.withType(JavaCompile) {
options.compilerArgs.addAll([
'-XDstringConcat=inline',
'-Xlint:all,-processing,-serial,-path,-classfile'
])
options.errorprone.disableWarningsInGeneratedCode = true
options.errorprone.errorproneArgs.addAll([
'-XepAllErrorsAsWarnings',
'-XepDisableWarningsInGeneratedCode',
'-Xep:MissingOverride:OFF'
])
}
// Custom task to generate BuildConstants.java
abstract class GenerateVersionFile extends DefaultTask {
@OutputDirectory
abstract DirectoryProperty getOutputDir()
@Input
abstract Property<String> getProjectName()
@javax.inject.Inject
abstract org.gradle.process.ExecOperations getExecOperations()
@TaskAction
void generate() {
def baseDir = getOutputDir().get().asFile
def outputDir = new File(baseDir, "frc/robot")
outputDir.mkdirs()
def outputFile = new File(outputDir, "BuildConstants.java")
def gitHash = execute("git rev-parse HEAD")
def gitBranch = execute("git rev-parse --abbrev-ref HEAD")
def gitRevision = execute("git rev-list --count HEAD")
def gitDate = execute("git log -1 --format=%cd --date=format:'%Y-%m-%d %H:%M:%S %Z'")
def now = java.time.ZonedDateTime.now()
def buildDate = now.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z"))
def buildUnixTime = now.toInstant().toEpochMilli()
def dirty = execute("git status --porcelain").isEmpty() ? 0 : 1
outputFile.text = """package frc.robot;
/** Automatically generated file containing build version information. */
public final class BuildConstants {
public static final String MAVEN_GROUP = "";
public static final String MAVEN_NAME = "${getProjectName().get()}";
public static final String VERSION = "unspecified";
public static final int GIT_REVISION = ${gitRevision == "unknown" ? 0 : gitRevision};
public static final String GIT_SHA = "${gitHash}";
public static final String GIT_DATE = "${gitDate}";
public static final String GIT_BRANCH = "${gitBranch}";
public static final String BUILD_DATE = "${buildDate}";
public static final long BUILD_UNIX_TIME = ${buildUnixTime}L;
public static final int DIRTY = ${dirty};
private BuildConstants() {}
}
"""
}
private String execute(String cmd) {
try {
def out = new java.io.ByteArrayOutputStream()
// For Windows/Linux split commands
def argsList = cmd.tokenize(' ') as List
// Handle quoted arguments gracefully for git date formats
if (cmd.contains("format:'")) {
argsList = ["git", "log", "-1", "--format=%cd", "--date=format:%Y-%m-%d %H:%M:%S %Z"]
}
getExecOperations().exec {
commandLine argsList
standardOutput = out
ignoreExitValue = true
}
return out.toString().trim()
} catch (Exception e) {
return "unknown"
}
}
}
def generateVersionFile = tasks.register("generateVersionFile", GenerateVersionFile) {
outputDir = layout.buildDirectory.dir("generated/source/version/main/java")
projectName = project.name
}
sourceSets.main.java.srcDir(generateVersionFile.map { it.outputDir })
project.compileJava.dependsOn(generateVersionFile)
task generateControllerMappings {
description = "Automatically generates CONTROLLER_MAPPINGS.md from RobotBindings.java"
def inputFile = file("src/main/java/frc/robot/RobotBindings.java")
def outputFileHtml = file("CONTROLLER_MAPPINGS.html")
def outputFileMd = file("CONTROLLER_MAPPINGS.md")
inputs.file(inputFile)
outputs.files(outputFileHtml, outputFileMd)
doLast {
if (!inputFile.exists()) return
String content = inputFile.text
// Initialize both builders
StringBuilder html = new StringBuilder()
StringBuilder md = new StringBuilder()
// HTML Header
html.append("<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"UTF-8\">")
html.append("<title>MARSLib Controller Mappings</title>")
html.append("<style>")
html.append("body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; padding: 2rem; max-width: 800px; margin: 0 auto; line-height: 1.6; color: #24292e; background-color: #ffffff; }")
html.append("h1 { border-bottom: 2px solid #eaecef; padding-bottom: 8px; margin-bottom: 20px; }")
html.append("h2 { margin-top: 30px; border-bottom: 1px solid #eaecef; padding-bottom: 8px; }")
html.append("table { border-collapse: collapse; width: 100%; margin-top: 15px; }")
html.append("th, td { border: 1px solid #dfe2e5; padding: 10px 15px; text-align: left; }")
html.append("th { background-color: #f6f8fa; font-weight: 600; }")
html.append("tr:nth-child(even) { background-color: #f8f9fa; }")
html.append("kbd { background-color: #fafbfc; border: 1px solid #c6cbd1; border-bottom-color: #959da5; border-radius: 4px; box-shadow: inset 0 -1px 0 #959da5; color: #444d56; display: inline-block; font-size: 13px; line-height: 20px; padding: 4px 7px; font-family: ui-monospace, SFMono-Regular, monospace; }")
html.append(".note { background-color: #ddf4ff; border-left: 4px solid #0969da; padding: 15px; margin-top: 30px; border-radius: 4px; color: #24292f; }")
html.append(".subtitle { color: #57606a; font-style: italic; }")
html.append("</style></head><body>")
html.append("<h1>MARSLib Controller Mappings</h1>")
html.append("<p class=\"subtitle\">This document is automatically generated during compilation from <code>RobotBindings.java</code>.</p>")
// MD Header
md.append("# MARSLib Controller Mappings\n\n")
md.append("This document is automatically generated during compilation from `RobotBindings.java`.\n\n")
def pattern = java.util.regex.Pattern.compile("(?s)(controller|coPilot)\\s*\\.bind(?:On|While)(?:True|False)\\(\\s*[^,]+,\\s*\"([^\"]+)\"\\s*,\\s*\"([^\"]+)\"")
def matcher = pattern.matcher(content)
def pilotHtml = []
def pilotMd = []
def copilotHtml = []
def copilotMd = []
while (matcher.find()) {
def target = matcher.group(1)
def trigger = matcher.group(2)
def action = matcher.group(3)
def rowHtml = "<tr><td><kbd>${trigger}</kbd></td><td><b>${action}</b></td></tr>"
def rowMd = "| <kbd>${trigger}</kbd> | **${action}** |"
if (target == "controller") {
pilotHtml.add(rowHtml)
pilotMd.add(rowMd)
} else if (target == "coPilot") {
copilotHtml.add(rowHtml)
copilotMd.add(rowMd)
}
}
// HTML & MD Pilot Append
html.append("<h2>\uD83C\uDFAE Pilot (Driver) - Controller 0</h2>")
html.append("<p class=\"subtitle\">Primary drive controls and high-level macro sequences.</p>")
html.append("<table><tr><th>Controller Input</th><th>Mapped Action</th></tr>")
html.append("<tr><td><kbd>Left Joystick</kbd></td><td><b>Holonomic Translation (X/Y)</b></td></tr>")
html.append("<tr><td><kbd>Right Joystick</kbd></td><td><b>Holonomic Rotation</b></td></tr>")
pilotHtml.each { html.append(it) }
html.append("</table>")
md.append("## \uD83C\uDFAE Pilot (Driver) - Controller 0\n\n")
md.append("> **Primary drive controls and high-level macro sequences.**\n\n")
md.append("| Controller Input | Mapped Action |\n| :--- | :--- |\n")
md.append("| <kbd>Left Joystick</kbd> | **Holonomic Translation (X/Y)** |\n")
md.append("| <kbd>Right Joystick</kbd> | **Holonomic Rotation** |\n")
pilotMd.each { md.append(it).append('\n') }
md.append("\n---\n\n")
// HTML & MD CoPilot Append
html.append("<h2>\uD83D\uDD79\uFE0F CoPilot (Operator) - Controller 1</h2>")
html.append("<p class=\"subtitle\">Manual overrides, sub-mechanism control, and fault resets.</p>")
html.append("<table><tr><th>Controller Input</th><th>Mapped Action</th></tr>")
copilotHtml.each { html.append(it) }
html.append("</table>")
html.append("<div class=\"note\"><strong>Note:</strong> All automated scoring sequences natively return the superstructure to the safe <code>STOWED</code> state immediately upon release of the binding.</div>")
html.append("</body></html>")
md.append("## \uD83D\uDD79\uFE0F CoPilot (Operator) - Controller 1\n\n")
md.append("> **Manual overrides, sub-mechanism control, and fault resets.**\n\n")
md.append("| Controller Input | Mapped Action |\n| :--- | :--- |\n")
copilotMd.each { md.append(it).append('\n') }
md.append("\n---\n> [!NOTE]\n> All automated scoring sequences natively return the superstructure to the \n> safe `STOWED` state immediately upon release of the binding.\n")
outputFileHtml.setText(html.toString(), 'UTF-8')
outputFileMd.setText(md.toString(), 'UTF-8')
println "Successfully generated CONTROLLER_MAPPINGS documents."
}
}
project.compileJava.dependsOn(generateControllerMappings)
// Create commit with working changes on deploy
def isDeployTask = gradle.startParameter.taskNames.any({ it.toLowerCase().contains("deploy") })
def projectDirFile = projectDir
task(deployCommit) {
doLast {
if (isDeployTask) {
def commitMessage = "Deploy commit at '${new Date().toString()}'"
exec {
workingDir(projectDirFile)
executable 'git'
args 'add', '-A', ':(exclude)third_party/maple-sim-upstream'
}
exec {
workingDir(projectDirFile)
executable 'git'
args 'commit', '-m', commitMessage
ignoreExitValue = true
}
println "Auto-committed working changes before deploy."
println "Commit message: '$commitMessage'"
} else {
println "Not running deploy task, skipping auto-commit"
}
}
}
generateVersionFile.configure {
dependsOn(deployCommit)
}
// Spotless formatting
spotless {
java {
target fileTree(".") {
include "**/*.java"
exclude "**/build/**", "**/build-*/**", "third_party/**"
}
toggleOffOn()
googleJavaFormat()
removeUnusedImports()
trimTrailingWhitespace()
endWithNewline()
}
groovyGradle {
target fileTree(".") {
include "**/*.gradle"
exclude "**/build/**", "**/build-*/**"
}
// greclipse() // Removed due to P2 provisioning errors
leadingTabsToSpaces(4)
trimTrailingWhitespace()
endWithNewline()
}
json {
target fileTree(".") {
include "**/*.json"
exclude "**/build/**", "**/build-*/**", ".wpilib/**", "**/vendordeps/**", "third_party/**", "website/node_modules/**", "docs/**"
}
gson().indentWithSpaces(2)
}
format "misc", {
target fileTree(".") {
include "**/*.md", "**/.gitignore"
exclude "**/build/**", "**/build-*/**", "CONTROLLER_MAPPINGS.md", "website/**", "docs/**"
}
trimTrailingWhitespace()
leadingTabsToSpaces(2)
endWithNewline()
}
}
tasks.named('pmdTest') { enabled = false }
tasks.named('checkstyleTest') { enabled = false }
task updateDocsCoverage {
description = "Updates the docs/index.html file with freshly generated JaCoCo coverage metrics"
dependsOn jacocoTestReport
def projectDirCaptured = projectDir
doLast {
def csvFile = new File(projectDirCaptured, "build/reports/jacoco/test/jacocoTestReport.csv")
if (!csvFile.exists()) {
println "No jacocoTestReport.csv found, skipping documentation update."
return
}
def sourceFiles = 0
def srcDirVar = new File(projectDirCaptured, "src/main/java")
if (srcDirVar.exists()) srcDirVar.eachFileRecurse(groovy.io.FileType.FILES) { if (it.name.endsWith('.java')) sourceFiles++ }
def testFiles = 0
def testDirVar = new File(projectDirCaptured, "src/test/java")
if (testDirVar.exists()) testDirVar.eachFileRecurse(groovy.io.FileType.FILES) { if (it.name.endsWith('.java')) testFiles++ }
def testCount = 0
def testResultsDir = new File(projectDirCaptured, "build/test-results/test")
if (testResultsDir.exists()) {
testResultsDir.listFiles().each { f ->
if (f.name.endsWith(".xml")) {
def matcher = f.text =~ /tests="(\d+)"/
if (matcher.find()) {
testCount += matcher.group(1).toInteger()
}
}
}
}
def instrMissed = 0
def instrCovered = 0
def branchMissed = 0
def branchCovered = 0
def lineMissed = 0
def lineCovered = 0
def classMissed = 0
def classCovered = 0
csvFile.eachLine { line, index ->
if (index > 0) { // skip header
def parts = line.split(',')
if (parts.length >= 9) {
try {
def im = parts[3].toInteger()
def ic = parts[4].toInteger()
def bm = parts[5].toInteger()
def bc = parts[6].toInteger()
def lm = parts[7].toInteger()
def lc = parts[8].toInteger()
instrMissed += im
instrCovered += ic
branchMissed += bm
branchCovered += bc
lineMissed += lm
lineCovered += lc
if (ic > 0) {
classCovered++
} else {
classMissed++
}
} catch (Exception e) {}
}
}
}
def instrTotal = instrCovered + instrMissed
def branchTotal = branchCovered + branchMissed
def lineTotal = lineCovered + lineMissed
def classTotal = classCovered + classMissed
def instrPct = instrTotal > 0 ? Math.round((float)instrCovered * 100.0f / instrTotal) : 0
def branchPct = branchTotal > 0 ? Math.round((float)branchCovered * 100.0f / branchTotal) : 0
def linePct = lineTotal > 0 ? Math.round((float)lineCovered * 100.0f / lineTotal) : 0
def classPct = classTotal > 0 ? Math.round((float)classCovered * 100.0f / classTotal) : 0
def fmt = java.text.NumberFormat.getNumberInstance(java.util.Locale.US)
def indexFile = new File(projectDirCaptured, "docs/index.html")
if (indexFile.exists()) {
def content = indexFile.getText('UTF-8')
// 1. Top Section - Source Files
content = content.replaceAll(
/(?s)<div class="stat-value">\d+<\/div>\s*<div class="stat-label">Source Files<\/div>/,
"<div class=\"stat-value\">${sourceFiles}</div>\n <div class=\"stat-label\">Source Files</div>"
)
// 2. Top Section - Unit Tests
content = content.replaceAll(
/(?s)<div class="stat-value">\d+<\/div>\s*<div class="stat-label">Unit Tests<\/div>/,
"<div class=\"stat-value\">${testCount}</div>\n <div class=\"stat-label\">Unit Tests</div>"
)
// 3. Top Section - Instruction Coverage
content = content.replaceAll(
/(?s)<div class="percentage">\d+%<\/div>\s*<div class="stat-label">Instruction Coverage<\/div>\s*<div class="instruction-count">[\d,]+ \/ [\d,]+ instructions covered<\/div>/,
"<div class=\"percentage\">${instrPct}%</div>\n <div class=\"stat-label\">Instruction Coverage</div>\n <div class=\"instruction-count\">${fmt.format(instrCovered)} / ${fmt.format(instrTotal)} instructions covered</div>"
)
// 4. Bottom Section - Header
content = content.replaceAll(
/<p>JaCoCo-measured coverage across \d+ test files and \d+ test cases\.<\/p>/,
"<p>JaCoCo-measured coverage across ${testFiles} test files and ${testCount} test cases.</p>"
)
// 5. Bottom Section - Line Coverage
content = content.replaceAll(
/(?s)<h4>\uD83D\uDCCF Line Coverage<\/h4>\s*<div class="progress-bar">\s*<div class="progress-fill" style="width: \d+%; background: linear-gradient\(90deg, var\(--mars-red\), var\(--yellow\)\);"><\/div>\s*<\/div>\s*<div class="coverage-meta">[\d,]+ \/ [\d,]+ lines covered \(\d+%\)<\/div>/,
"<h4>\uD83D\uDCCF Line Coverage</h4>\n <div class=\"progress-bar\">\n <div class=\"progress-fill\" style=\"width: ${linePct}%; background: linear-gradient(90deg, var(--mars-red), var(--yellow));\"></div>\n </div>\n <div class=\"coverage-meta\">${fmt.format(lineCovered)} / ${fmt.format(lineTotal)} lines covered (${linePct}%)</div>"
)
// 6. Bottom Section - Branch Coverage
content = content.replaceAll(
/(?s)<h4>\uD83C\uDF3F Branch Coverage<\/h4>\s*<div class="progress-bar">\s*<div class="progress-fill" style="width: \d+%; background: linear-gradient\(90deg, var\(--green\), var\(--blue\)\);"><\/div>\s*<\/div>\s*<div class="coverage-meta">[\d,]+ \/ [\d,]+ branches covered \(\d+%\)<\/div>/,
"<h4>\uD83C\uDF3F Branch Coverage</h4>\n <div class=\"progress-bar\">\n <div class=\"progress-fill\" style=\"width: ${branchPct}%; background: linear-gradient(90deg, var(--green), var(--blue));\"></div>\n </div>\n <div class=\"coverage-meta\">${fmt.format(branchCovered)} / ${fmt.format(branchTotal)} branches covered (${branchPct}%)</div>"
)
// 7. Bottom Section - Instruction Coverage
content = content.replaceAll(
/(?s)<h4>⚙️ Instruction Coverage<\/h4>\s*<div class="progress-bar">\s*<div class="progress-fill" style="width: \d+%; background: linear-gradient\(90deg, var\(--purple\), var\(--blue\)\);"><\/div>\s*<\/div>\s*<div class="coverage-meta">[\d,]+ \/ [\d,]+ instructions covered \(\d+%\)<\/div>/,
"<h4>⚙️ Instruction Coverage</h4>\n <div class=\"progress-bar\">\n <div class=\"progress-fill\" style=\"width: ${instrPct}%; background: linear-gradient(90deg, var(--purple), var(--blue));\"></div>\n </div>\n <div class=\"coverage-meta\">${fmt.format(instrCovered)} / ${fmt.format(instrTotal)} instructions covered (${instrPct}%)</div>"
)
// 8. Bottom Section - Class Coverage
content = content.replaceAll(
/(?s)<h4>\uD83C\uDFD7️ Class Coverage<\/h4>\s*<div class="progress-bar">\s*<div class="progress-fill" style="width: \d+%; background: linear-gradient\(90deg, var\(--green\), var\(--mars-red\)\);"><\/div>\s*<\/div>\s*<div class="coverage-meta">[\d,]+ \/ [\d,]+ classes covered \(\d+%\)<\/div>/,
"<h4>\uD83C\uDFD7️ Class Coverage</h4>\n <div class=\"progress-bar\">\n <div class=\"progress-fill\" style=\"width: ${classPct}%; background: linear-gradient(90deg, var(--green), var(--mars-red));\"></div>\n </div>\n <div class=\"coverage-meta\">${fmt.format(classCovered)} / ${fmt.format(classTotal)} classes covered (${classPct}%)</div>"
)
indexFile.setText(content, 'UTF-8')
println "Successfully updated docs/index.html with Jacoco Coverage: Instr ${instrPct}%, Branch ${branchPct}%, Line ${linePct}%, Class ${classPct}%"
println "Source Files: ${sourceFiles}, Test Files: ${testFiles}, Unit Tests: ${testCount}"
}
}
}
jacocoTestReport.finalizedBy updateDocsCoverage
java {
withSourcesJar()
}
publishing {
repositories {
maven {
name = "GitHubPagesRepo"
url = "${projectDir}/website/static/maven"
}
}
publications {
mavenJava(MavenPublication) {
from components.java
groupId = 'com.marslib'
artifactId = 'MARSLib'
version = '1.0.0'
pom {
name = 'MARSLib'
description = 'Zero-allocation FRC framework with dyn4j and AdvantageKit'
}
}
}
}