如何在SBT中为非托管JAR添加对应源码JAR
配置SBT将非托管源码JAR关联到依赖
你可以通过给源码JAR添加sources分类器属性,让SBT和IDE自动关联对应的依赖与源码。以下是修改后的完整配置:
import sbt.nio.file._ import sbt.Attributed import sbt.Artifact lazy val MyProject = project .settings( Compile / unmanagedJars ++= { // 定义依赖和源码目录 val depRoot = file("myManagedRoot") val depDir = depRoot / "deps" val sourceDir = depRoot / "sources" // 读取所有依赖JAR,转为Attributed[File](SBT类路径要求的格式) val depJars = FileTreeView.default .list(depDir.toGlob / "*.jar") .collect { case (path, attrs) if attrs.isRegularFile => Attributed.blank(path.toFile) } // 匹配对应源码JAR,添加sources分类器属性 val sourceJars = depJars.flatMap { attrDepJar => val jarBaseName = attrDepJar.data.getName.stripSuffix(".jar") val sourceJarPath = sourceDir / s"$jarBaseName-sources.jar" if (sourceJarPath.exists()) { Some(Attributed.blank(sourceJarPath).withAttribute(Artifact.Classifier, "sources")) } else None } // 合并依赖JAR和源码JAR到非托管类路径 depJars ++ sourceJars } )
关键说明:
- Attributed文件:SBT的类路径元素是
Attributed[File]类型,通过Attributed.blank创建基础实例,再用withAttribute添加sources分类器,告诉SBT这是对应依赖的源码包。 - 自动匹配:通过依赖JAR的文件名(去掉
.jar后缀)拼接-sources.jar,自动关联对应的源码文件,无需手动逐个配置。 - 容错处理:如果某个依赖没有对应的源码JAR,代码会自动跳过,不会抛出错误。
效果:
- 运行
updateClassifiers任务时,SBT会直接使用本地的源码JAR,不会尝试从远程仓库下载。 - IDE(如IntelliJ IDEA)导入项目后,会自动将源码JAR关联到对应的依赖JAR,支持跳转查看源码。
内容的提问来源于stack exchange,提问作者Alec
相关产品推荐
相关产品推荐

