3

I have a Java program that creates a list of filepaths I want to run checkstyle on. I was curious if there is a way to directly run checkstyle from within my program or whether I will need to shell out to the CLI.

Andrew
  • 5,368
  • 8
  • 48
  • 86
  • heres a link that might help you : https://www.baeldung.com/checkstyle-java – Mustahsan May 01 '19 at 16:54
  • @Mustahsan that appears to be about setting it up inside of an IDE or as part of a Maven build - I am interested in running it directly from within a Java program – Andrew May 01 '19 at 18:05
  • you can run terminal commands from java as well. – Mustahsan May 02 '19 at 03:07
  • If you ask how to simply run a process with checkstyle, see https://stackoverflow.com/questions/792024/how-to-execute-system-commands-linux-bsd-using-java for example. If you are asking whether checkstyle has an API so you can run it programmatically, well, that would be off topic here. – GhostCat May 02 '19 at 07:06

2 Answers2

4

Yes, that is possible, although it's not so much a documented API, but rather a set of calls that works, and that's kept reasonably stable. In fact, IDE plugins go that way.

For example, the Checkstyle plugin for IntelliJ has some code you can look at to get an idea:
https://github.com/jshiell/checkstyle-idea/tree/5.26.0/src/csaccess/java/org/infernus/idea/checkstyle/service/cmd

It may, however, be easier to just call Checkstyle as a command-line program (via zt-exec, for example) and parse its XML report. That is if you don't need to have the direct feedback provided via in-process AuditListeners.

barfuin
  • 15,975
  • 10
  • 85
  • 128
0

I have a Java program
is a way to directly run checkstyle from within my program

You can call any Java program from within another Java program. When a Java program is called from the command line, it's main method is called that passes in all the command line parameters that is not for the java program itself. All you need to do in your Java program is call the same main that the command line calls. For checkstyle this is com.puppycrawl.tools.checkstyle.Main. See https://github.com/checkstyle/checkstyle/blob/bd7621fae3b1b887d46b8a678600db7e6d03185c/src/main/java/com/puppycrawl/tools/checkstyle/Main.java#L100 .

The downside to checkstyle however is it calls System.exit when it is done so you will never return from your call. To prevent a System.exit from terminating the JVM completely see Java: How to test methods that call System.exit()? for the SecurityManager example.

You can avoid all this System.exit business but it would require you to duplicate a bunch of Checkstyle's code, which is also in the Main class. See https://github.com/checkstyle/checkstyle/blob/bd7621fae3b1b887d46b8a678600db7e6d03185c/src/main/java/com/puppycrawl/tools/checkstyle/Main.java#L332 . It is up to you how you want to handle it.

rveach
  • 1,913
  • 14
  • 24