|
| 1 | +package mill.javalib.pmd |
| 2 | + |
| 3 | +import mill.* |
| 4 | +import mill.api.{Discover, ExternalModule, TaskCtx} |
| 5 | +import mill.jvmlib.api.Versions |
| 6 | +import mill.scalalib.scalafmt.ScalafmtModule.sources |
| 7 | +import mill.scalalib.{CoursierModule, Dep, DepSyntax, OfflineSupportModule} |
| 8 | +import mill.util.Jvm |
| 9 | + |
| 10 | +/** |
| 11 | + * Checks Java source files with PMD static code analyzer [[https://pmd.github.io/]]. |
| 12 | + */ |
| 13 | +trait PmdModule extends CoursierModule, OfflineSupportModule { |
| 14 | + |
| 15 | + /** |
| 16 | + * Runs PMD and returns the number of violations found (exit code). |
| 17 | + * |
| 18 | + * @note [[sources]] are processed when no [[PmdArgs.sources]] are specified. |
| 19 | + */ |
| 20 | + def pmd(@mainargs.arg pmdArgs: PmdArgs): Command[(exitCode: Int, outputPath: PathRef)] = |
| 21 | + Task.Command { |
| 22 | + val (outputPath, exitCode) = pmd0(pmdArgs.format, pmdArgs.sources)() |
| 23 | + pmdHandleExitCode( |
| 24 | + pmdArgs.stdout, |
| 25 | + pmdArgs.failOnViolation, |
| 26 | + exitCode, |
| 27 | + outputPath, |
| 28 | + pmdArgs.format |
| 29 | + ) |
| 30 | + (exitCode, outputPath) |
| 31 | + } |
| 32 | + |
| 33 | + protected def pmd0(format: String, leftover: mainargs.Leftover[String]) = |
| 34 | + Task.Anon { |
| 35 | + val output = Task.dest / s"pmd-output.$format" |
| 36 | + os.makeDir.all(output / os.up) |
| 37 | + val baseArgs = Seq( |
| 38 | + "-d", |
| 39 | + if (leftover.value.nonEmpty) leftover.value.mkString(",") |
| 40 | + else sources().map(_.path.toString()).mkString(","), |
| 41 | + "-R", |
| 42 | + pmdRulesets().map(_.path.toString).mkString(","), |
| 43 | + "-f", |
| 44 | + format, |
| 45 | + "-r", |
| 46 | + output.toString |
| 47 | + ) |
| 48 | + |
| 49 | + val args = |
| 50 | + if (isPmd6OrOlder(this.pmdVersion())) pmdOptions() ++ baseArgs |
| 51 | + else pmdOptions() ++ (Seq("check") ++ baseArgs) |
| 52 | + val mainCls = |
| 53 | + if (isPmd6OrOlder(this.pmdVersion())) "net.sourceforge.pmd.PMD" |
| 54 | + else "net.sourceforge.pmd.cli.PmdCli" |
| 55 | + val jvmArgs = pmdLanguage().map(lang => s"-Duser.language=$lang").toSeq |
| 56 | + |
| 57 | + Task.log.info("Running PMD...") |
| 58 | + Task.log.debug(s"with $args") |
| 59 | + Task.log.info(s"Writing PMD output to: $output...") |
| 60 | + |
| 61 | + val exitCode = Jvm.callProcess( |
| 62 | + mainCls, |
| 63 | + classPath = pmdClasspath().map(_.path).toVector, |
| 64 | + mainArgs = args, |
| 65 | + cwd = moduleDir, |
| 66 | + stdin = os.Inherit, |
| 67 | + stdout = os.Inherit, |
| 68 | + check = false, |
| 69 | + jvmArgs = jvmArgs |
| 70 | + ).exitCode |
| 71 | + |
| 72 | + (PathRef(output), exitCode) |
| 73 | + } |
| 74 | + |
| 75 | + private def pmdHandleExitCode( |
| 76 | + stdout: Boolean, |
| 77 | + failOnViolation: Boolean, |
| 78 | + exitCode: Int, |
| 79 | + output: PathRef, |
| 80 | + format: String |
| 81 | + )(implicit ctx: TaskCtx): Int = { |
| 82 | + exitCode match |
| 83 | + case 0 => Task.log.info("No violations found and no recoverable error occurred.") |
| 84 | + case 1 => Task.log.error("PMD finished with an exception.") |
| 85 | + case 2 => Task.log.error("PMD command-line parameters are invalid or missing.") |
| 86 | + case 4 => |
| 87 | + reportViolations(failOnViolation, countViolations(output, format, stdout)) |
| 88 | + case 5 => |
| 89 | + reportViolations(failOnViolation, countViolations(output, format, stdout)) |
| 90 | + throw new RuntimeException("At least one recoverable PMD error has occurred.") |
| 91 | + case x => Task.log.error(s"Unsupported PMD exit code: $x") |
| 92 | + exitCode |
| 93 | + } |
| 94 | + |
| 95 | + private def countViolations( |
| 96 | + output: PathRef, |
| 97 | + format: String, |
| 98 | + stdout: Boolean |
| 99 | + )(implicit ctx: TaskCtx): Option[Int] = { |
| 100 | + var violationCount: Option[Int] = None |
| 101 | + val lines = os.read.lines(output.path) |
| 102 | + if (lines.nonEmpty) { |
| 103 | + if (stdout) { |
| 104 | + Task.log.info("PMD violations:") |
| 105 | + lines.foreach(line => Task.log.info(line)) |
| 106 | + } |
| 107 | + // For "text" format: each line is a violation |
| 108 | + if (format == "text") { |
| 109 | + violationCount = Some(lines.size) |
| 110 | + } |
| 111 | + // For "xml" format: count <violation ...> tags |
| 112 | + else if (format == "xml") { |
| 113 | + violationCount = Some(lines.count(_.trim.startsWith("<violation"))) |
| 114 | + } |
| 115 | + // For "html" format: count lines with <tr but skip the header row |
| 116 | + else if (format == "html") { |
| 117 | + violationCount = |
| 118 | + Some(lines.count(line => line.trim.startsWith("<tr") && !line.contains("<th"))) |
| 119 | + } |
| 120 | + } else { |
| 121 | + violationCount = Some(0) |
| 122 | + } |
| 123 | + violationCount |
| 124 | + } |
| 125 | + |
| 126 | + private def reportViolations( |
| 127 | + failOnViolation: Boolean, |
| 128 | + violationCount: Option[Int] |
| 129 | + )(implicit ctx: TaskCtx): Unit = { |
| 130 | + if (failOnViolation) |
| 131 | + throw new RuntimeException(s"PMD found ${violationCount.getOrElse("some")} violation(s)") |
| 132 | + else |
| 133 | + Task.log.error(s"PMD found ${violationCount.getOrElse("some")} violation(s)") |
| 134 | + } |
| 135 | + |
| 136 | + /** |
| 137 | + * Classpath for running PMD. |
| 138 | + */ |
| 139 | + def pmdClasspath: T[Seq[PathRef]] = Task { |
| 140 | + val version = pmdVersion() |
| 141 | + defaultResolver().classpath(Seq(mvn"net.sourceforge.pmd:pmd-dist:$version")) |
| 142 | + } |
| 143 | + |
| 144 | + /** PMD rulesets files. Defaults to `pmd-ruleset.xml`. */ |
| 145 | + def pmdRulesets: Sources = Task.Sources(moduleDir / "pmd-ruleset.xml") |
| 146 | + |
| 147 | + /** Additional arguments for PMD. */ |
| 148 | + def pmdOptions: T[Seq[String]] = Task { |
| 149 | + Seq.empty[String] |
| 150 | + } |
| 151 | + |
| 152 | + /** User language of the JVM running PMD. */ |
| 153 | + def pmdLanguage: T[Option[String]] = Task.Input { |
| 154 | + sys.props.get("user.language") |
| 155 | + } |
| 156 | + |
| 157 | + /** Helper to check if the version is <= 6. False by default. */ |
| 158 | + private def isPmd6OrOlder(version: String): Boolean = { |
| 159 | + version |
| 160 | + .split(":").lastOption |
| 161 | + .flatMap(_.takeWhile(_ != '.').toIntOption) |
| 162 | + .exists(_ < 7) |
| 163 | + } |
| 164 | + |
| 165 | + /** PMD version. */ |
| 166 | + def pmdVersion: T[String] = Task { Versions.pmdVersion } |
| 167 | +} |
| 168 | + |
| 169 | +/** |
| 170 | + * External module for PMD integration. |
| 171 | + * Allows usage via `import mill.javalib.pmd.PmdModule` in build.sc. |
| 172 | + */ |
| 173 | +object PmdModule extends ExternalModule, PmdModule { |
| 174 | + lazy val millDiscover: Discover = Discover[this.type] |
| 175 | + def defaultCommandName() = "pmd" |
| 176 | +} |
0 commit comments