|
| 1 | +/* |
| 2 | + * Copyright The OpenTelemetry Authors |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | + |
| 6 | +package io.opentelemetry.instrumentation.gradle |
| 7 | + |
| 8 | +import com.diffplug.spotless.FormatterFunc |
| 9 | +import java.io.Serializable |
| 10 | + |
| 11 | +/** |
| 12 | + * Spotless custom step that rewrites qualified references (e.g. {@code Objects.requireNonNull}) |
| 13 | + * into unqualified references and adds the corresponding static import. Runs before |
| 14 | + * googleJavaFormat so that imports are sorted and any newly-unused regular imports are removed. |
| 15 | + */ |
| 16 | +class StaticImportFormatter : FormatterFunc, Serializable { |
| 17 | + |
| 18 | + override fun apply(input: String): String { |
| 19 | + // (className, fullyQualifiedName, memberPattern) |
| 20 | + val rules = listOf( |
| 21 | + Triple("Objects", "java.util.Objects", "requireNonNull"), |
| 22 | + Triple( |
| 23 | + "ElementMatchers", |
| 24 | + "net.bytebuddy.matcher.ElementMatchers", |
| 25 | + "[a-z][a-zA-Z0-9]*" |
| 26 | + ), |
| 27 | + Triple( |
| 28 | + "AgentElementMatchers", |
| 29 | + "io.opentelemetry.javaagent.extension.matcher.AgentElementMatchers", |
| 30 | + "[a-z][a-zA-Z0-9]*" |
| 31 | + ), |
| 32 | + Triple("TimeUnit", "java.util.concurrent.TimeUnit", "[A-Z][A-Z_0-9]*"), |
| 33 | + Triple( |
| 34 | + "StandardCharsets", |
| 35 | + "java.nio.charset.StandardCharsets", |
| 36 | + "[A-Z][A-Z_0-9]*" |
| 37 | + ), |
| 38 | + ) |
| 39 | + |
| 40 | + var content = input |
| 41 | + val importsToAdd = mutableSetOf<String>() |
| 42 | + |
| 43 | + for ((className, pkg, memberPattern) in rules) { |
| 44 | + val regex = Regex("\\b${className}\\.(${memberPattern})\\b") |
| 45 | + val lines = content.lines().toMutableList() |
| 46 | + for (i in lines.indices) { |
| 47 | + if (lines[i].trimStart().startsWith("import ")) continue |
| 48 | + for (match in regex.findAll(lines[i])) { |
| 49 | + importsToAdd.add("import static ${pkg}.${match.groupValues[1]};") |
| 50 | + } |
| 51 | + lines[i] = regex.replace(lines[i], "$1") |
| 52 | + } |
| 53 | + content = lines.joinToString("\n") |
| 54 | + } |
| 55 | + |
| 56 | + if (importsToAdd.isNotEmpty()) { |
| 57 | + val lines = content.lines().toMutableList() |
| 58 | + val firstImportIndex = lines.indexOfFirst { it.trimStart().startsWith("import ") } |
| 59 | + if (firstImportIndex >= 0) { |
| 60 | + for ((offset, imp) in importsToAdd.sorted().withIndex()) { |
| 61 | + lines.add(firstImportIndex + offset, imp) |
| 62 | + } |
| 63 | + content = lines.joinToString("\n") |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + return content |
| 68 | + } |
| 69 | + |
| 70 | + companion object { |
| 71 | + private const val serialVersionUID = 1L |
| 72 | + } |
| 73 | +} |
0 commit comments