Skip to content

Instantly share code, notes, and snippets.

@ryan0x44
Last active April 5, 2023 12:43
Show Gist options
  • Save ryan0x44/c95718cc59e987dc2d44f629433d73b6 to your computer and use it in GitHub Desktop.
Save ryan0x44/c95718cc59e987dc2d44f629433d73b6 to your computer and use it in GitHub Desktop.
Java Checkstyle Cyclomatic Complexity Example
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC "-//Checkstyle//DTD Checkstyle Configuration 1.3//EN" "https://checkstyle.org/dtds/configuration_1_3.dtd">
<module name = "Checker">
<property name="charset" value="UTF-8"/>
<module name="TreeWalker">
<module name="CyclomaticComplexity">
<property name="max" value="1"/>
</module>
</module>
</module>
public class Example1 {
public static void main(String[] args) {
int a = 0;
if (a >= 0) {
System.out.println(">= 0");
if (a != 0) {
System.out.println("!= 0");
}
} else {
System.out.println("< 0");
}
}
}
public class Example2 {
public static void main(String[] args) {
int a = 0;
if (a >= 0) {
System.out.println(">= 0");
} else {
System.out.println("< 0");
}
if (a != 0) {
System.out.println("!= 0");
}
}
}
#!/bin/sh -e
echo "Downloading checkstyle ..."
if [ ! -f "checkstyle.jar" ]; then
curl -Lso checkstyle.jar https://github.com/checkstyle/checkstyle/releases/download/checkstyle-8.21/checkstyle-8.21-all.jar
fi
echo "Running checkstyle ..."
java -jar checkstyle.jar -c checks.xml *.java
@ryan0x44
Copy link
Author

Expected output:

./run.sh
Downloading checkstyle ...
Running checkstyle ...
Starting audit...
[ERROR] /Users/rdjurovich/cf-repos/cyclo-test/java/Example1.java:2:3: Cyclomatic Complexity is 3 (max allowed is 1). [CyclomaticComplexity]
[ERROR] /Users/rdjurovich/cf-repos/cyclo-test/java/Example2.java:2:3: Cyclomatic Complexity is 3 (max allowed is 1). [CyclomaticComplexity]
Audit done.
Checkstyle ends with 2 errors.

@shmsr
Copy link

shmsr commented Jun 9, 2019

There are multiple errors to your gist. I'm suggesting you fixes.

  1. In <run.sh>
    #!/bin/sh -e
    echo "Downloading checkstyle ..."
    if [ ! -f "checkstyle.jar" ]; then
    curl -Lso checkstyle.jar https://github.com/checkstyle/checkstyle/releases/download/checkstyle-8.21/checkstyle-8.21-all.jar
    fi
    echo "Running checkstyle ..."
    java -jar checkstyle.jar -c checks.xml $(find . -name '*.java')

Your existing code resulted in error:

no main manifest attribute, in checkstyle.jar
8.21 doesn't have -r flag, so for search recursively find command is used.
If used 5.21, you can use -r flag followed by $(pwd)

  1. In <checks.xml>
    Replace
    <!DOCTYPE module PUBLIC "-//Puppy Crawl//DTD Check Configuration 1.3//EN" "http://checkstyle.sourceforge.net/dtds/configuration_1_3.dtd">
    To
    <!DOCTYPE module PUBLIC "-//Checkstyle//DTD Checkstyle Configuration 1.3//EN" "https://checkstyle.org/dtds/configuration_1_3.dtd">

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment