是否有Ant任务来检查符号链接是否悬空?

时间:2014-01-28 20:27:02

标签: java ant

我的构建系统中有一些符号链接指向jars,如果jars不存在,我需要构建它们。即如果符号链接是悬空的。是否有Ant任务或解决方法来检查它?

至于为什么我不能在这些jar中包含适当的Ant依赖,原因是它们的构建过程很长,涉及从ftp存储库进行的即时Internet下载,这需要太长时间并且不受我的控制

1 个答案:

答案 0 :(得分:1)

好的,所以最后我实现了一个自定义Ant任务(最后的代码),可以像这样在Ant中使用:

<file-pronouncer filePath="path/to/file" retProperty="prop-holding-type-of-that-file"/>

然后可以阅读:

<echo message="the file-pronouncer task for file 'path/to/file' returned: ${prop-holding-type-of-that-file}"/>

有以下可能的结果:

 [echo] the file-pronouncer task for file 'a' returned: regular-file
 [echo] the file-pronouncer task for file 'b' returned: symlink-ok
 [echo] the file-pronouncer task for file 'c' returned: symlink-dangling
 [echo] the file-pronouncer task for file 'd' returned: not-exists

FilePronouncer自定义Ant任务的代码

import java.io.IOException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import java.nio.file.Path;
import java.nio.file.Files;
import java.nio.file.FileSystems;
import java.nio.file.LinkOption;
import java.nio.file.attribute.BasicFileAttributes;
import org.apache.tools.ant.BuildException;

public class FilePronouncer extends Task {

    private String filePath    = null;
    private String retProperty = null;

    public String getFilePath() {  
        return filePath;  
    }  

    public void setFilePath(String filePath) {  
        this.filePath = filePath;
    }

    public String getRetProperty() {  
        return retProperty;  
    }  

    public void setRetProperty(String property) {  
        this.retProperty = property;  
    }

    public void execute() {
        try {
        Path path = FileSystems.getDefault().getPath(filePath);
        boolean fileExists           = Files.exists(path, LinkOption.NOFOLLOW_LINKS);
        Boolean isSymlink            = null;
        Boolean filePointedToExists  = null;
        if (fileExists) {
            BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
            isSymlink = attrs.isSymbolicLink();
            if (isSymlink)
                filePointedToExists = Files.exists(path);
        }
        Project project = getProject();  
        String rv = null;
        if (!fileExists)
            rv = "not-exists";
        else {
            if (!isSymlink)
                rv = "regular-file";
            else {
                if (filePointedToExists)
                    rv = "symlink-ok";
                else
                    rv = "symlink-dangling";
            }
        }
        project.setProperty(retProperty, rv);
        } catch (IOException e) {
            throw new BuildException(e);
        }
    }
}