自定义Maven插件:如何正确处理FileSet?
解决自定义Maven插件中FileSet遍历返回空列表的问题
出现这个问题的核心原因是FileSetManager没有关联Maven项目的上下文路径,默认可能用了当前工作目录而非项目根目录,导致匹配不到文件。以下是具体解决步骤:
首先在插件类中注入Maven项目和会话上下文,这是解析路径的关键:
@Parameter(defaultValue = "${project}", readonly = true) private MavenProject project; @Parameter(defaultValue = "${session}", readonly = true) private MavenSession session;遍历FileSet时,显式指定baseDir并初始化FileSetManager:
// 初始化FileSetManager,传入日志器 FileSetManager fileSetManager = new FileSetManager(session.getLogger()); for (FileSet fileSet : filesets) { // 确定文件集的基础目录:如果FileSet没指定directory,默认用项目根目录 File baseDir = fileSet.getDirectory() != null ? fileSet.getDirectory() : project.getBasedir(); // 传入baseDir路径,解析包含的文件 String[] includedFiles = fileSetManager.getIncludedFiles(fileSet, baseDir.getAbsolutePath()); // 遍历处理每个文件 for (String relativePath : includedFiles) { File targetFile = new File(baseDir, relativePath); // 这里写你的文件处理逻辑,比如读取、修改等 } }检查pom中的FileSet配置是否符合Ant路径规则,比如:
<configuration> <filesets> <fileset> <!-- 相对路径基于项目根目录 --> <directory>src/main/java</directory> <includes> <include>**/*.java</include> </includes> <excludes> <exclude>**/test/**</exclude> </excludes> </fileset> </filesets> </configuration>
额外注意:如果你的插件运行在非项目根目录的上下文(比如多模块项目的子模块),显式指定baseDir能避免路径解析错误。调用getIncludedFiles时一定要传入正确的baseDir,而不是只传FileSet参数。
内容的提问来源于stack exchange,提问作者queeg
相关产品推荐
相关产品推荐

