-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathbuild.gradle
More file actions
296 lines (248 loc) · 10.2 KB
/
build.gradle
File metadata and controls
296 lines (248 loc) · 10.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
import java.util.regex.Pattern
import java.util.regex.Matcher
plugins {
id 'com.diffplug.spotless' version '8.4.0'
}
group = 'com.toedter'
version = '3.1.1-SNAPSHOT'
// Apply Spotless to all subprojects
subprojects {
apply plugin: 'com.diffplug.spotless'
spotless {
java {
target 'src/**/*.java'
googleJavaFormat('1.17.0').reflowLongStrings()
removeUnusedImports()
endWithNewline()
trimTrailingWhitespace()
licenseHeaderFile rootProject.file('license-header.txt'), 'package '
}
}
// Run spotless check before build
tasks.named('check') {
dependsOn 'spotlessCheck'
}
}
// Root-level misc formatting
spotless {
format 'misc', {
target '*.gradle', '*.md', '.gitignore'
trimTrailingWhitespace()
leadingTabsToSpaces(2)
endWithNewline()
}
}
// Task to install git hooks
tasks.register('installGitHooks') {
description = 'Install Git hooks for pre-commit formatting'
group = 'git hooks'
doLast {
def hooksDir = file("${rootProject.rootDir}/.git/hooks")
if (!hooksDir.exists()) {
hooksDir.mkdirs()
}
// Pre-commit hook
def preCommitHook = file("${hooksDir}/pre-commit")
preCommitHook.text = """#!/bin/sh
# Auto-format code before commit
echo "Running Spotless code formatter..."
./gradlew spotlessApply --quiet
# Add all formatted files back to staging (not just Java)
# Add all formatted files back to staging (not just Java)
git diff --name-only | xargs -r git add
echo "Code formatting complete!"
"""
preCommitHook.setExecutable(true)
// Commit-msg hook for commit message validation
def commitMsgHook = file("${hooksDir}/commit-msg")
commitMsgHook.text = '''#!/bin/sh
# Validate commit message format
# Expected format: type(scope): subject
# Example: feat(api): add new endpoint
commit_msg=$(cat "$1")
# Regex for conventional commits
pattern="^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(\\([a-z0-9-]+\\))?!?: [a-z].{2,72}$"
if ! echo "$commit_msg" | grep -qE "$pattern"; then
echo "ERROR: Invalid commit message format!"
echo ""
echo "Commit message must follow Conventional Commits format:"
echo " type(scope): subject"
echo ""
echo "Types: feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert"
echo ""
echo "Example: feat(api): add new JSON:API endpoint"
echo "Example: fix(serializer): resolve null pointer exception"
exit 1
fi
'''
commitMsgHook.setExecutable(true)
println "Git hooks installed successfully!"
println " - pre-commit: Auto-format code with Spotless"
println " - commit-msg: Validate conventional commit messages"
}
}
// Run installGitHooks after project evaluation
afterEvaluate {
// Skip git hooks warning in GitHub Actions
def isGitHubActions = System.getenv('GITHUB_ACTIONS') != null
if (!isGitHubActions) {
def hooksDir = file("${rootProject.rootDir}/.git/hooks")
def preCommitHook = file("${hooksDir}/pre-commit")
if (!preCommitHook.exists()) {
println ""
println "⚠️ Git hooks not installed!"
println " Run './gradlew installGitHooks' to set up automatic code formatting and commit linting"
println ""
}
}
}
// Extension to store computed version information
class VersionInfo {
String currentVersion
String previousRelease
String nextRelease
String nextSnapshot
String bump
int commitCount
String lastTag
}
ext.versionInfo = null
// Helper method to compute version information
def computeVersionInfo() {
if (ext.versionInfo == null) {
def info = new VersionInfo()
info.currentVersion = project.version.toString()
def (major, minor, patch) = info.currentVersion.replaceAll('-SNAPSHOT', '').tokenize('.').collect { it.toInteger() }
// Get the last version tag (this is the previous release)
info.lastTag = "git describe --tags --abbrev=0".execute().text.trim()
info.previousRelease = info.lastTag.replaceAll('^v', '')
// Analyze git commits since last tag
def commits = "git log ${info.lastTag}..HEAD --pretty=format:%s".execute().text.split('\n').findAll { it.trim() }
info.commitCount = commits.size()
// Determine version bump based on commits since last tag
info.bump = 'patch'
if (commits.any { it =~ /^[^:]+!:|\bBREAKING CHANGE\b/ }) {
info.bump = 'major'
} else if (commits.any { it =~ /^feat[:(]/ }) {
info.bump = 'minor'
}
// Apply the version bump
switch (info.bump) {
case 'major':
major++
minor = 0
patch = 0
break
case 'minor':
minor++
patch = 0
break
case 'patch':
patch++
break
}
info.nextRelease = "${major}.${minor}.${patch}"
info.nextSnapshot = "${major}.${minor}.${patch + 1}-SNAPSHOT"
ext.versionInfo = info
}
return ext.versionInfo
}
tasks.register('showVersions') {
description = 'Show current and next versions based on conventional commits'
group = 'versioning'
doLast {
def info = computeVersionInfo()
println """
╔════════════════════════════════════════════════════════════════
║ VERSION INFORMATION
╠════════════════════════════════════════════════════════════════
║ Previous Release: ${info.previousRelease}
║ Current Snapshot: ${info.currentVersion}
║ Next Release: ${info.nextRelease}
║ Next Snapshot: ${info.nextSnapshot}
║
║ Version Bump: ${info.bump.toUpperCase()} (${info.commitCount} commits since ${info.lastTag})
╚════════════════════════════════════════════════════════════════
"""
}
}
tasks.register('prepareRelease') {
description = 'Prepare for a new release by updating all version references'
group = 'versioning'
dependsOn 'showVersions'
doLast {
def info = computeVersionInfo()
println """
╔════════════════════════════════════════════════════════════════
║ PREPARING RELEASE
╠════════════════════════════════════════════════════════════════
║ Previous Release: ${info.previousRelease}
║ Current Snapshot: ${info.currentVersion}
║ → Next Release: ${info.nextRelease}
║ → Next Snapshot: ${info.nextSnapshot}
╠════════════════════════════════════════════════════════════════
"""
def filesUpdated = 0
def replacements = 0
// Define files to update with version references
def filesToUpdate = [
'README.adoc',
'build.gradle',
'lib/build.gradle',
'lib/src/main/asciidoc/setup.adoc',
'lib/src/main/asciidoc/migration.adoc',
'lib/src/main/asciidoc/configuration.adoc',
'example/build.gradle'
]
filesToUpdate.each { relativePath ->
def file = rootProject.file(relativePath)
if (!file.exists()) {
println " ║ ⚠️ File not found: ${relativePath}"
return
}
def originalContent = file.text
def updatedContent = originalContent
// Replace current snapshot with next snapshot
updatedContent = updatedContent.replaceAll(
Pattern.quote(info.currentVersion),
Matcher.quoteReplacement(info.nextSnapshot)
)
// Replace previous release with next release
updatedContent = updatedContent.replaceAll(
Pattern.quote(info.previousRelease),
Matcher.quoteReplacement(info.nextRelease)
)
if (updatedContent != originalContent) {
file.text = updatedContent
filesUpdated++
println " ║ ✓ Updated: ${relativePath}"
}
}
// Now update version in build.gradle files to next release (not snapshot)
['build.gradle', 'lib/build.gradle', 'example/build.gradle'].each { relativePath ->
def file = rootProject.file(relativePath)
if (!file.exists()) {
println " ║ ⚠️ File not found: ${relativePath}"
return
}
def originalContent = file.text
def updatedContent = originalContent
// Replace version = '<next snapshot>' with version = '<next release>'
updatedContent = updatedContent.replaceAll(
~/version = ['"]${Pattern.quote(info.nextSnapshot)}['"]/,
"version = '${info.nextRelease}'"
)
if (updatedContent != originalContent) {
file.text = updatedContent
replacements++
println " ║ ✓ Set release version in: ${relativePath}"
}
}
println """
╠════════════════════════════════════════════════════════════════
║ ✓ Updated ${filesUpdated} file(s)
║ ✓ Set release version in ${replacements} build.gradle file(s)
╚════════════════════════════════════════════════════════════════
"""
}
}