Search code examples
beanshellmaven-enforcer-plugin

How to catch exception in a beanshell?


I can use the evaluateBeanshell rule to enforce some convention: no colon's in directories below src.

<plugin>
  <artifactId>maven-enforcer-plugin</artifactId>
  <version>1.4.1</version>
  <executions>
    <execution>
      <id>enforce-beanshell</id>
      <goals>
        <goal>enforce</goal>
      </goals>
      <configuration>
        <rules>
          <evaluateBeanshell>
            <condition>org.codehaus.plexus.util.FileUtils.getDirectoryNames(new File("src"), "**/*:*", null, false).isEmpty()</condition>
          </evaluateBeanshell>
        </rules>
      </configuration>
    </execution>
  </executions>
</plugin>

But some projects don't have an src directory, and the rule will fail hard. I tried setting

<condition>org.codehaus.plexus.util.FileUtils.getDirectoryNames(new File("."), "src/**/[^A-Z]*", null, false).isEmpty()</condition>

How do I safely catch the non-existence of the src directory?


Solution

  • This does what I need

    <evaluateBeanshell>
      <condition>
        String projectSource = "${project.basedir}" + "/src";
        if (org.codehaus.plexus.util.FileUtils.fileExists(projectSource)){
          List filenames = org.codehaus.plexus.util.FileUtils.getFileNames(
            new File(projectSource),"**/*.*",null,false);
    
          for (Iterator it = filenames.iterator(); it.hasNext();) {
            String file = it.next();
            String extension = org.codehaus.plexus.util.FileUtils.getExtension(file);
    
            if (extension.equals(extension.toLowerCase())) {
              it.remove();
            } else {
              print("Invalid filename extension (no capitals): " + projectSource + "/" + file);
            };
          };
          return filenames.isEmpty();
        } else return true;
      </condition>
    </evaluateBeanshell>