【发布时间】:2011-08-26 18:32:34
【问题描述】:
我需要编写一个ant任务来判断某个文件是否是只读的,如果是,则失败。我想避免使用自定义选择器来执行此操作,这与我们构建系统的性质有关。任何人有任何想法如何去做这件事?我正在使用 ant 1.8 + ant-contrib。
谢谢!
【问题讨论】:
标签: ant build readonly build.xml ant-contrib
我需要编写一个ant任务来判断某个文件是否是只读的,如果是,则失败。我想避免使用自定义选择器来执行此操作,这与我们构建系统的性质有关。任何人有任何想法如何去做这件事?我正在使用 ant 1.8 + ant-contrib。
谢谢!
【问题讨论】:
标签: ant build readonly build.xml ant-contrib
这样的方法能解决问题吗?
<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 task 和 isfileselected 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>
这将检查和失败作为一个不同的操作而不是两个,因此您可能会发现它更清晰,并且不需要使用属性名称,因此您的命名空间更清晰。
【讨论】:
writeable 更改为 writable - 我现在才刚刚测试过,发现我打错了。
我确信有更好的方法,但我会抛出一些可能的方法。
使用java任务执行一个任务,该任务执行一些简单的代码,例如:
文件 f = 新文件(路径); f.canWrite()......
【讨论】:
编写一个供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>
【讨论】: