这最初是由 @daniel-c-sobral 在 Gitter 上提出的:
How can I detect if the current project is a root project from inside a dynamic task?
更新:
与 Daniel 进一步交谈后,他澄清道:
It’s a plugin that is changing
test
to run a task, but only on the root project.
所以他似乎想检测特定任务的范围是否为根项目。
最佳答案
给出几个帮助器定义:
val rootProjectRef: Def.Initialize[ProjectRef] = Def.setting {
val rootBuildUri = loadedBuild.value.root
val rootProjectId = loadedBuild.value.units(rootBuildUri).root
ProjectRef(rootBuildUri, rootProjectId)
}
val currentProjectRef: Def.Initialize[Task[ProjectRef]] =
Def.task(Project.session(state.value).current)
我们可以相当干净地实现确定当前选定的项目是否是(根)构建的根项目(您可以从任何其他任务(动态与否)调用)的任务,以及更一般的“这是项目根项目?”以及“这个项目是当前选择的项目吗?”问题:
val isRootProject = settingKey[Boolean]("Is this the root project?")
val isCurrentProject = taskKey[Boolean]("Is this the currently selected project?")
val isCurrentProjectRoot = taskKey[Boolean]("Is the currently select project the root project?")
inScope(Global)(Def.settings(
isCurrentProjectRoot := currentProjectRef.value == rootProjectRef.value,
))
val commonSettings = Def.settings(
isRootProject := thisProjectRef.value == rootProjectRef.value,
isCurrentProject := thisProjectRef.value == currentProjectRef.value,
)
lazy val root = project in file(".") settings commonSettings aggregate app
lazy val app = project settings commonSettings
实际操作:
> show root / isRootProject
[info] true
> show app / isRootProject
[info] false
>
> show root / isCurrentProject
[info] true
[success] Total time: 0 s, completed 23 Jan 2020, 00:02:58
> show app / isCurrentProject
[info] false
[success] Total time: 0 s, completed 23 Jan 2020, 00:03:04
>
> project
[info] root (in build file:/s/t-sbt-amIRoot/)
>
> show isCurrentProjectRoot
[info] true
[success] Total time: 0 s, completed 23 Jan 2020, 00:03:11
>
>
>
> project app
[info] Set current project to app (in build file:/s/t-sbt-amIRoot/)
>
> show root / isCurrentProject
[info] false
[success] Total time: 0 s, completed 23 Jan 2020, 00:03:34
> show app / isCurrentProject
[info] true
[success] Total time: 0 s, completed 23 Jan 2020, 00:03:37
>
> show isCurrentProjectRoot
[info] false
[success] Total time: 0 s, completed 23 Jan 2020, 00:03:42
[success] Total time: 0 s, completed 22 Jan 2020, 22:04:43
需要注意的几点:
首先,请注意 isRootProject
可以作为设置实现,因为它是已加载构建的不可变值。
其次,请注意,范围 isCurrentProjectRoot
是毫无意义的(这就是为什么它是全局的,因为它不依赖于项目内的任何内容),但并不非法,这可能会产生误导,例如:
> project /
[info] Set current project to root (in build file:/s/t-sbt-amIRoot/)
>
> show isCurrentProjectRoot
[info] true
[success] Total time: 0 s, completed 23 Jan 2020, 00:06:23
>
> show app / isCurrentProjectRoot
[info] true
[success] Total time: 0 s, completed 23 Jan 2020, 00:06:26
关于scala - 如何检测当前项目是否是 sbt 动态任务内部的根项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59867515/