You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Gradle CodeNarc插件配置自定义文件名扩展名?

问题描述

我正尝试在项目中使用Gradle 8.0.2的CodeNarc插件。由于某些原因,Groovy文件使用了非标准扩展名,目前插件仅扫描*.groovy文件。我的build.gradle配置如下:

plugins {
    id 'groovy'
    id 'java'
    id 'codenarc'
}

repository {
    mavenCentral()
}

dependencies {
    implementation 'org.apache.groovy:groovy-all:4.0.10'
}

sourceSets {
    main {
        groovy {
            srcDirs = ['directory1', 'directory2']
        }
    }
}

项目中包含以下文件:

  • directory1/utils.groovy
  • directory1/something.groovy
  • directory2/another.myextension

执行./gradlew codenarcMain --info时,提示:

No matching files found for FileSet with basedir [/home/path/to/project/directory2]

添加如下配置后仍无效果:

codenarcMain {
    include('**/*.myextension', '**/*.groovy')
}

请问如何在Gradle中为CodeNarc插件正确注册自定义扩展名?

解决方案

CodeNarc插件默认关联Gradle的Groovy源集,但仅识别源集配置的Groovy文件扩展名。需先让Gradle将.myextension文件视为Groovy文件,再配置CodeNarc扫描,具体步骤如下:

1. 修改Groovy源集的文件范围

在sourceSets中为Groovy源添加自定义扩展名,确保Gradle将这些文件纳入Groovy源集:

sourceSets {
    main {
        groovy {
            srcDirs = ['directory1', 'directory2']
            // 同时保留原有groovy扩展名和自定义扩展名
            include '**/*.groovy', '**/*.myextension'
        }
    }
}

2. 配置CodeNarc任务

CodeNarc会自动扫描Groovy源集内的文件,此时无需额外配置即可扫描到.myextension文件。如果需要显式绑定源集,可添加:

codenarcMain {
    source = sourceSets.main.groovy
}

若要单独指定CodeNarc的扫描范围,也可直接配置:

codenarcMain {
    include '**/*.groovy', '**/*.myextension'
    baseDir = project.projectDir
}

3. 验证配置

重新执行./gradlew codenarcMain --info,此时CodeNarc应能正常扫描directory2/another.myextension,不会再出现找不到匹配文件的提示。

关键原因:之前单独配置codenarcMain的include无效,是因为CodeNarc默认扫描的是Groovy源集的文件,而源集未包含.myextension文件,任务自然无法找到对应内容。必须先让Gradle将自定义扩展名文件纳入Groovy源集,CodeNarc才能正确识别。

内容的提问来源于stack exchange,提问作者epR8GaYuh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 09:53:40