【问题标题】:How to catch exception in a beanshell?如何在 beanshell 中捕获异常?
【发布时间】:2021-03-26 03:50:54
【问题描述】:

我可以使用evaluateBeanshell 规则来强制执行一些约定: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>

但是有些项目没有 src 目录,规则会很难失败。我试过设置

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

如何安全地捕捉到不存在的 src 目录?

【问题讨论】:

  • 请检查oneold answer
  • @gowridev 这些 标记之一中的正则表达式的功能如何?我不想强制 src 目录的存在
  • 请查看maven rule apicustom api这两个链接
  • requireFilesExist 可能是最好的答案
  • 您应该重写问题/标题,以更清楚地表明您要检查文件夹是否存在:它与文件名中的字符关系不大。

标签: beanshell maven-enforcer-plugin


【解决方案1】:

这是我需要的

<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>

【讨论】:

    【解决方案2】:

    如果你想使用 Beanshell,你只需要返回一个布尔值。

    <evaluateBeanshell>
       <condition>new java.io.File("src").exists()</condition>
    </evaluateBeanshell>
    

    如果路径以文件/文件夹/符号链接的形式存在,则为 true,否则为 false,这将破坏构建。

    如果要检查多个方面,例如是否存在AND是否是目录,则添加多个条件:

    <evaluateBeanshell>
       <condition>new java.io.File("path").exists()</condition>
       <condition>new java.io.File("path").isDirectory()</condition>
    </evaluateBeanshell>
    

    (可以说检查它是否存在然后它是否是一个目录没有什么意义,但有助于说明这一点)

    如果您必须使用 Beanshell,还可以做很多事情。但最终,'requireFilesExist' 规则可能是对执行器更好的配置。

    【讨论】:

    • 你还没有理解我的问题。我要强制执行的规则是:如果文件存在于文件夹 src 下(可能存在也可能不存在),那么它的文件扩展名中不能有大写。当 src 不存在时,我不希望构建中断
    • 好的。但是Enforcer的能力还是一样的。编写一个返回布尔值的实用程序类,打包为 jar,然后将其用作条件。你可以把你需要的任何逻辑放在那里。或者您可以将更复杂的 Beanshell 放入条件中,或者使用“&&”/“||”进行链接,但我没有尝试过。
    猜你喜欢
    • 2011-04-03
    • 2013-09-04
    • 2021-05-23
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-16
    • 2022-06-23
    相关资源
    最近更新 更多