概要

AntからPMDを実行します。

サンプルターゲット

<target name="pmd">
  <taskdef name="pmd" classname="net.sourceforge.pmd.ant.PMDTask" />
  <mkdir dir="${build.reports}" />
  <pmd rulesetfiles="java-basic,java-imports,java-strings" encoding="${compile.encoding}">
    <classpath refid="project.class.path" />
    <formatter type="xml" toFile="${build.reports}/pmd.xml" />
    <formatter type="text" toConsole="true" />
    <fileset dir="${src.dir}">
      <include name="**/*.java" />
    </fileset>
  </pmd>
</target>

解説

  1. PMDからダウンロードしたpmd-bin-x.x.ziplib以下にあるpmd-x.x.jarなどのjarファイルを%ANT_HOME%\libにコピー
  2. ant pmdで、pmd.xmlを生成し、jenkinsPMDプラグインなどで読み込む

toFile or toConsole

FindBugsのように、xmlファイルとコンソールの両方に結果を表示したい場合が多いのですが、

ant -v pmd

では、情報が多すぎるのでformatter要素のtoConsole属性を使用します。

  • PMD - Ant Task にあるように、<formatter type="html" toFile="pmd_report.html" toConsole="true"/>や、<formatter type="xml" toFile="${build.reports}/pmd.xml" toConsole="true" />toFiletoConsoleを指定しても、ファイルにのみ結果が書き出されて、コンソールには何も出力されない
  • <formatter type="text" toConsole="true" />と、toFile属性なしでtoConsole="true"とする必要がある?
    • <formatter type="text" toConsole="false" />は、toFile or toConsole needs to be specified in Formatterとなって、BUILD FAILED
  • ファイルとコンソールの両方に出力する場合は、formatterを複数指定しなくてはならない?

ruleset

チェックするルールをruleset.xmlなどに記述して、これをrulesetfiles属性で参照する方法もあります。

  • ruleset.xmlを使用するサンプルターゲット
<target name="pmd">
  <taskdef name="pmd" classname="net.sourceforge.pmd.ant.PMDTask" />
  <mkdir dir="${build.reports}" />
  <pmd rulesetfiles="ruleset.xml" encoding="${compile.encoding}">
    <sourceLanguage name="java" version="1.7"/>
    <classpath refid="project.class.path" />
    <formatter type="xml" toFile="${build.reports}/pmd.xml" />
    <formatter type="text" toConsole="true" />
    <fileset dir="${src.dir}">
      <include name="**/*.java" />
    </fileset>
  </pmd>
</target>
  • ruleset.xmlのサンプル
<?xml version="1.0"?>
<ruleset name="Custom ruleset"
    xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd">

  <description>This ruleset checks my code for bad stuff</description>

  <rule ref="rulesets/java/basic.xml" />
  <rule ref="rulesets/java/braces.xml" />
  <rule ref="rulesets/java/clone.xml" />
  <rule ref="rulesets/java/codesize.xml" />
  <rule ref="rulesets/java/controversial.xml">
    <exclude name="DataflowAnomalyAnalysis" />
    <exclude name="OnlyOneReturn" />
    <exclude name="AvoidLiteralsInIfCondition" />
    <exclude name="NullAssignment" />
    <!-- exclude name="AssignmentInOperand" / -->
    <exclude name="AtLeastOneConstructor" />
    <exclude name="AvoidUsingShortType" />
  </rule>
  <rule ref="rulesets/java/coupling.xml">
    <exclude name="LawOfDemeter" />
    <exclude name="LoosePackageCoupling" />
  </rule>
  <rule ref="rulesets/java/design.xml">
    <exclude name="AvoidSynchronizedAtMethodLevel" />
    <exclude name="AvoidDeeplyNestedIfStmts" />
  </rule>
  <rule ref="rulesets/java/design.xml/AvoidDeeplyNestedIfStmts">
    <properties>
      <property name="problemDepth" value="4"/>
    </properties>
  </rule>
  <rule ref="rulesets/java/empty.xml" />
  <rule ref="rulesets/java/finalizers.xml" />
  <rule ref="rulesets/java/imports.xml" />
  <rule ref="rulesets/java/migrating.xml">
    <exclude name="ReplaceVectorWithList" />
  </rule>
  <rule ref="rulesets/java/naming.xml">
    <exclude name="ShortClassName" />
    <exclude name="ShortVariable" />
    <exclude name="LongVariable" />
  </rule>
  <rule ref="rulesets/java/optimizations.xml">
    <exclude name="AvoidInstantiatingObjectsInLoops" />
    <exclude name="LocalVariableCouldBeFinal" />
    <exclude name="MethodArgumentCouldBeFinal" />
  </rule>
  <rule ref="rulesets/java/strictexception.xml" />
  <rule ref="rulesets/java/strings.xml" />
  <rule ref="rulesets/java/sunsecure.xml" />
  <rule ref="rulesets/java/typeresolution.xml" />
  <rule ref="rulesets/java/unnecessary.xml" />
  <rule ref="rulesets/java/unusedcode.xml" />

<!-- 
  <rule ref="rulesets/java/comments.xml" />
  <rule ref="rulesets/java/j2ee.xml" />
  <rule ref="rulesets/java/javabeans.xml" />
  <rule ref="rulesets/java/junit.xml" />
  <rule ref="rulesets/java/logging-jakarta-commons.xml" />
  <rule ref="rulesets/java/logging-java.xml" />
  <rule ref="rulesets/java/migrating_to_13.xml" />
  <rule ref="rulesets/java/migrating_to_14.xml" />
  <rule ref="rulesets/java/migrating_to_15.xml" />
  <rule ref="rulesets/java/migrating_to_junit4.xml" />
-->
</ruleset>

PMD 5.0.0

  • RuleSet short names now require a language prefix, 'basic' is now 'java-basic', and 'rulesets/basic.xml' is now 'rulesets/java/basic.xml'
    • 上記のサンプルで、rulesetfiles属性のbasicなどを、java-basicに変更
  • Removed -targetjdk use -version {name} {version} instead
    • 上記のサンプルから、targetjdk="${compile.source}"を削除

PMD 5.1.2

import java.awt.*;
import javax.swing.*;

public class Foo {
    public JComponent makeUI() {
        Box box = Box.createVerticalBox();
        JTextField field = new JTextField();
        box.add(makePanel("aaa", field));
        return box;
    }
    private static JPanel makePanel(String title, JComponent c) {
        JPanel p = new JPanel(new BorderLayout());
        p.setBorder(BorderFactory.createTitledBorder(title));
        p.add(c);
        return p;
    }
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override public void run() {
                createAndShowGUI();
            }
        });
    }
    public static void createAndShowGUI() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new Foo().makeUI());
        f.setSize(320, 240);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }
}

PMD 5.1.3-SNAPSHOT

  • 上記の誤検出はpmd-bin-5.1.3-SNAPSHOT.zipですべて無くなったけど、新規で今まで問題なかった?以下のようなコードのmakeButton(Action action, String title)UnusedPrivateMethodとなってしまう。
C:\temp>C:\pmd-bin-5.1.3-SNAPSHOT\bin\pmd.bat -dir . -rulesets java-unusedcode
C:\temp\MenuBarFactoryTest.java:44: Avoid unused private methods such as 'makeButton(Action,String)'.
import java.awt.*;
import java.util.Arrays;
import java.util.List;
import javax.swing.*;
import javax.swing.text.DefaultEditorKit;

public final class MenuBarFactoryTest {
  public static JMenuBar makeManuBar() {
    JMenuBar mb = new JMenuBar();
    mb.add(makeFileMenu());
    return mb;
  }
  private static JMenu makeFileMenu() {
    JMenu menu = new JMenu("File");
    menu.add(makeEditMenuItem(makeEditButtonBar(Arrays.asList(
        makeButton(new DefaultEditorKit.CutAction(),   "Cut"),
        makeButton(new DefaultEditorKit.CopyAction(),  "Copy"),
        makeButton(new DefaultEditorKit.PasteAction(), "Paste")))));
    return menu;
  }
  private static JMenuItem makeEditMenuItem(final JComponent edit) {
    JMenuItem item = new JMenuItem("Edit") {
      @Override public Dimension getPreferredSize() {
        Dimension d = super.getPreferredSize();
        d.width += edit.getPreferredSize().width;
        d.height = Math.max(edit.getPreferredSize().height, d.height);
        return d;
      }
    };
    item.setEnabled(false);
    item.setLayout(new GridBagLayout());
    item.add(edit);
    return item;
  }
  private static JComponent makeEditButtonBar(List<AbstractButton> list) {
    JPanel p = new JPanel(new GridLayout(1, list.size(), 0, 0));
    for (AbstractButton b : list) {
      p.add(b);
    }
    p.setBorder(BorderFactory.createEmptyBorder(4, 10, 4, 10));
    p.setOpaque(false);
    return p;
  }
  private static AbstractButton makeButton(Action action, String title) {
    JButton b = new JButton(action);
    b.setText(title);
    return b;
  }
  public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
      @Override public void run() {
        createAndShowGUI();
      }
    });
  }
  public static void createAndShowGUI() {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    f.setJMenuBar(makeManuBar());
    f.setSize(320, 240);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
  }
}

警告

GodClass

  • Ruleset: Design
    /**
      * Very high threshold for WMC (Weighted Method Count). See: Lanza.
      * Object-Oriented Metrics in Practice. Page 16.
      */
    private static final int WMC_VERY_HIGH = 47;
    
    /**
     * Few means between 2 and 5. See: Lanza. Object-Oriented Metrics in
     * Practice. Page 18.
     */
    private static final int FEW_THRESHOLD = 5;
    
    /**
     * One third is a low value. See: Lanza. Object-Oriented Metrics in
     * Practice. Page 17.
     */
    private static final double ONE_THIRD_THRESHOLD = 1.0 / 3.0; //0.33333
    
    //...
    if (wmcCounter >= WMC_VERY_HIGH && atfdCounter > FEW_THRESHOLD && tcc < ONE_THIRD_THRESHOLD) {
    //...
    

SimplifiedTernary

  • PMD Java – Basic
    public class SimplifiedTernaryTest {
      public static void main(String... args) {
        //boolean condition = true;
        boolean b1 = condition ? true  : something(); // can be as simple as condition || something();
        boolean b2 = condition ? false : something(); // can be as simple as !condition && something();
        boolean b3 = condition ? something() : true;  // can be as simple as !condition || something();
        boolean b4 = condition ? something() : false; // can be as simple as condition && something();
      }
      private static boolean something() {
        return true;
      }
    }
    
  • 例:
    model2 = new BasicDirectoryModel(getFileChooser()) {
      @Override public boolean renameFile(File oldFile, File newFile) {
        //return oldFile.canWrite() ? super.renameFile(oldFile, newFile) : false;
        return oldFile.canWrite() && super.renameFile(oldFile, newFile);
      }
    };
    

Jenkins

  • Jenkinsfile
    • antを呼び出す方法がよく分からない
pipeline {
    agent any
    stages {
        stage('Checkout') {
            steps {
                git url: 'https://github.com/aterai/java-swing-tips.git'
            }
        }
        stage('PMD') {
            steps {
                sh "~/.sdkman/candidates/ant/current/bin/ant -file all.xml pmd"
                step([$class: 'PmdPublisher', pattern: '**/pmd.xml'])
            }
        }
        stage('CheckStyle') {
            steps {
                sh "~/.sdkman/candidates/ant/current/bin/ant -file all.xml checkstyle"
                step([$class: 'CheckStylePublisher', pattern: '**/checkstyle-result.xml'])
            }
        }
    }
}
  • メモ: 最近のWeekly版(2.5x頃?)は、「インストール完了後、ジョブがなければJenkinsを再起動する」でジョブが実行中でも再起動されてしまい、ビルドが失敗する?
    • 「ビルドを並列実行」を「しない」にしているビルドを複数を実行すると、後から実行したビルドがビルドキューに入らず、並列実行されてしまう
    • 「システムの設定」で「同時ビルド数」を1にすれば、並列実行されなくなる
    • Jenkins Security Advisory 2017-04-26
      • SECURITY-412: Restart Jenkins immediately, after all builds are finished, or after all plugin installations and builds are finished

参考リンク

コメント