Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can find all unused import programmatically?

In my case there are two reason for doing that:

  • Sometimes people by mistake import classes which present in macbooks JDKs but absent in Linux. That causes build to fail on ci servers which are Linux based boxes. I doesn’t happen frequently, but when it does happened I'm thinking that there should be some smarter way to find out that earlier.
  • Unused imports trigger warning in IDE/code analysis. From time to time somebody need to spend time on cleaning up this stuff. Even if its just single right click in IDE you still need to commit your changes and make sure everything alright on build.

I'm curious if there is any way to find unused imports programmatically (lets say from unit test) and fail locally if there are any.

Maybe failing a build because of unused import sounds harsh, but if it saves time for team overall it makes sens to do so (would love to hear opinion on that as well).

UPDATE:

I followed yegor256 suggestion and incorporated Checkstyle task with initially small subset of Sun Code Conventions (unused imports is one of them) and made it break a build if violations found.

After one week of trial we've got zero unused imports in our codebase and surprisingly zero complaints about this rule (by the way, Checkstyle is really fast: analyzing ~100KLoc taking less than one second).

As for using IDE for such analysis: yes, it good choice, but having this kind of checks run as part of automated build is better.

like image 756
Petro Semeniuk Avatar asked Sep 17 '12 05:09

Petro Semeniuk


2 Answers

What you're trying to do is called static code analysis. Checkstyle can help you. If you're using Maven, this plugin will do the automation for you: http://maven.apache.org/plugins/maven-checkstyle-plugin/

You can also take a look at qulice.com (I'm one of its developers), which integrates a few static analysis tools and pre-configures them (incl. Checkstyle, PMD, FindBugs).

like image 132
yegor256 Avatar answered Oct 25 '22 15:10

yegor256


If you are using eclipse IDE or IntelliJ IDEA, you can configure them to

1a. organize imports / remove unused imports on save or before commit (see cleanup preferences)

1b. switch the "unused imports" warning to an error (see error settings)

2a. configure a jre which does not include com.* stuff

2b. configure the warning of proprietary api usage from the jre to be an error

You might still want to check that on the build server, though. In this case the more complicated stuff like configuring CheckStyle would still be necessary.

like image 36
Christian Avatar answered Oct 25 '22 14:10

Christian