skuzzle/restrict-imports-enforcer-rule

Match direct fully qualified uses when banning an import

Closed this issue · 5 comments

I noticed that if I, say, ban org.apache.commons.lang.* then

import org.apache.commons.lang.StringUtils;

is properly flagged, as expected, but one can bypass this by using StringUtils with its fully qualified name, e.g.:

org.apache.commons.lang.StringUtils.isBlank(string);

This is a bit unfortunate, as it leaves a way to still explicitly use a class from a banned import. Is there currently a way of disallowing this? If not, it would be very nice to have the feature!

Hi,

unfortunately, there is no current way of preventing full qualified class usage. That's actually a thing that I did not think about until now.
Given the way the comparison engine is currently implemented, this is not easy to fix. The plugin doesn't parse the whole source file to build an AST. Instead, it relies on certain invariants that always hold true for well formed java programms. It only reads the head part of each source file which contains the import statements.
So in order to detect full qualified class usages, we'd need to either do a full parse of each source file or implement some Regex heurisitcs.
I need to give this a little more thought but I think it is a very valid feature request and quite a short coming of the current implementation.

I see... well, I'm glad at least I brought it to attention. Hopefully this is possible in some future release. In the meantime I'll keep using the rule, thanks for it!

Ok, this issue did not leave me alone so I experimented a bit and built a small prototype. It will require some more testing but I'm confident that I can release it behind a little feature flag soon. Once released, the behavior can be enabled using

<configuration>
    <rules>
        <RestrictImports>
            <parseFullCompilationUnit>true</parseFullCompilationUnit>
            <!-- ... -->
        </RestrictImports>
    </rules>
</configuration>

I've added JavaParser.org dependency to parse and analyze the complete source file. Note that this will be considerably slower than the current analysis

Sounds great! Thanks for taking the time and eager to try this soon :)

First preview of this feature has just been released as 2.1.0 so I'm closing this issue here. Any feedback can be shared in a separate issue