首页 > 解决方案 > Maven 插件开发 - 如何检测修改的文件?

问题描述

我正在编写新的 maven 插件,我已经成功地将 StaleSourceScanner 与 SuffixMapping 结合使用,但它不能与 SingleTargetSourceMapping 一起使用。始终将所有文件检测为已修改。

更具体地说,这将是一个分析类文件的工具,所以我的源文件在 ${project.build.outputDirectory} 中。我为上次运行创建了一个时间戳文件,用于比较更改。

不幸的是,StaleSourceScanner 根本没有记录。

(Maven 阶段是:process-classes;staleMillis = 0 显示在调试中)

代码是:

    private Set<File> findChangedFilesSimple() throws MojoExecutionException
    {
        HashSet<String> sourceIncludes =
            new HashSet<>(Arrays.asList("**/*.class"));
        Set sourceExcludes = Collections.EMPTY_SET;

        StaleSourceScanner sourceInclusionScanner =
            new StaleSourceScanner(
                staleMillis, sourceIncludes, sourceExcludes);

        sourceInclusionScanner.addSourceMapping(
            new SingleTargetSourceMapping(
                ".class", timeStampFile.getPath()));

        Set<File> effectedFiles;

        try
        {
            effectedFiles =
                sourceInclusionScanner.getIncludedSources(
                    classesDirectory, timestampDirectory);
        }
        catch (InclusionScanException e)
        {
            throw new MojoExecutionException(
                "Error scanning source directory: " + classesDirectory, e);
        }

        return effectedFiles;
    }

标签: mavenpluginsmojomaven-plugin-development

解决方案


好的,已经通过分析SingleTargetSourceMapping源码发现了问题:

  1. 对于 getIncludedSources,targetDir 应该是 timestampFile 所在的目录。(到目前为止一切顺利。)
  2. 为 SingleTargetSourceMapping 提供的 timestampFile 是相对文件名,相对于上面提到的 targetDir。因此,应该使用 timeStampFile.getName() 而不是 timeStampFile.getPath()。

固定源代码:

    private Set<File> findChangedFilesSimple() throws MojoExecutionException
    {
        HashSet<String> sourceIncludes =
            new HashSet<>(Arrays.asList("**/*.class"));
        Set sourceExcludes = Collections.EMPTY_SET;

        StaleSourceScanner sourceInclusionScanner =
            new StaleSourceScanner(
                staleMillis, sourceIncludes, sourceExcludes);

        sourceInclusionScanner.addSourceMapping(
            new SingleTargetSourceMapping(
                ".class", timeStampFile.getName()));

        Set<File> effectedFiles;

        try
        {
            effectedFiles =
                sourceInclusionScanner.getIncludedSources(
                    classesDirectory, timeStampFile.getParentFile());
        }
        catch (InclusionScanException e)
        {
            throw new MojoExecutionException(
                "Error scanning source directory: " + classesDirectory, e);
        }

        return effectedFiles;
    }

推荐阅读