【问题标题】:Ant task to determine if a file is readonly确定文件是否为只读的 Ant 任务
【发布时间】:2011-08-26 18:32:34
【问题描述】:

我需要编写一个ant任务来判断某个文件是否是只读的,如果是,则失败。我想避免使用自定义选择器来执行此操作,这与我们构建系统的性质有关。任何人有任何想法如何去做这件事?我正在使用 ant 1.8 + ant-contrib。

谢谢!

【问题讨论】:

    标签: ant build readonly build.xml ant-contrib


    【解决方案1】:

    这样的方法能解决问题吗?

    <condition property="file.is.readonly">
      <not>
        <isfileselected file="${the.file.in.question}">
          <writable />
        </isfileselected>
      </not>
    </condition>
    <fail if="file.is.readonly" message="${the.file.in.question} is not writeable" />
    

    这使用 condition taskisfileselected condition(不是直接链接 - 您必须向下搜索页面)与 writable selector 组合(并使用 not 条件反转)。

    更新:

    一个可能更好的选择是:

    <fail message="${the.file.in.question} is not writeable">
      <condition>
        <not>
          <isfileselected file="${the.file.in.question}">
            <writable />
          </isfileselected>
        </not>
      </condition>
    </fail>
    

    这将检查和失败作为一个不同的操作而不是两个,因此您可能会发现它更清晰,并且不需要使用属性名称,因此您的命名空间更清晰。

    【讨论】:

    • 哇。你刚刚解决了我花了好几个小时解决的问题。我实际上理解你做了什么,我可以在未来复制。感谢您的帮助。
    • @Justin @Arne 如果您复制了原始版本,则需要将 writeable 更改为 writable - 我现在才刚刚测试过,发现我打错了。
    【解决方案2】:

    我确信有更好的方法,但我会抛出一些可能的方法。

    • 使用复制任务创建一个临时副本,然后尝试复制此文件以覆盖原始文件。 failonerror 属性会派上用场
    • 使用java任务执行一个任务,该任务执行一些简单的代码,例如:

      文件 f = 新文件(路径); f.canWrite()......

    【讨论】:

    • f.canWrite() 绝对是一个可行的选择。有没有办法只使用内置的 ant/ant-contrib 任务来完成此任务?
    【解决方案3】:

    编写一个供condition 任务使用的custom condition 怎么样?它更灵活。

    public class IsReadOnly extends ProjectComponent implements Condition
    {
      private Resource resource;
    
      /**
       * The resource to test.
       */
      public void add(Resource r) {
        if (resource != null) {
            throw new BuildException("only one resource can be tested");
        }
        resource = r;
      }
    
      /**
       * Argument validation.
       */
      protected void validate() throws BuildException {
        if (resource == null) {
            throw new BuildException("resource is required");
        }
      }
    
      public boolean eval() {
        validate();
        if (resource instanceof FileProvider) {
          return !((FileProvider)resource).getFile().canWrite();
        }
        try {
          resource.getOutputStream();
          return false;
        } catch (FileNotFoundException no) {
          return false;
        } catch (IOException no) {
          return true;
        }
      }
    }
    

    整合

    <typedef
      name="isreadonly"
      classname="IsReadOnly"
      classpath="${myclasses}"/>
    

    并像使用它

    <condition property="readonly">
      <isreadonly>
        <file file="${file}"/>
      </isreadonly>
    </condition>
    

    【讨论】:

      猜你喜欢
      • 2019-09-26
      • 1970-01-01
      • 2015-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多