fix: Fix clean task to delete managed sources located outside the target directory

This commit is contained in:
carlos4s 2026-04-13 04:40:31 +02:00
parent 0b4d57b893
commit 730f4a525d
3 changed files with 24 additions and 2 deletions

View File

@ -1965,7 +1965,18 @@ object Defaults extends BuildCommon with DefExtra {
}
/** Implements `cleanFiles` task. */
private[sbt] def cleanFilesTask: Initialize[Task[Vector[File]]] = Def.task { Vector.empty[File] }
private[sbt] def cleanFilesTask: Initialize[Task[Vector[File]]] = {
import ScopeFilter.Make.*
val allConfigs = ScopeFilter(configurations = inAnyConfiguration)
Def.task {
val targetDir = target.value.toPath
val managedSrcDirs = managedSourceDirectories.?.all(allConfigs).value.flatten.flatten
val managedRscDirs = managedResourceDirectories.?.all(allConfigs).value.flatten.flatten
(managedSrcDirs ++ managedRscDirs)
.filter(d => !d.toPath.startsWith(targetDir))
.toVector
}
}
def runMainTask(
classpath: Initialize[Task[Classpath]],

View File

@ -107,6 +107,7 @@ private[sbt] object Clean {
val excludeFilter = cleanFilter(scope).value
val delete = cleanDelete(scope).value
val targetDir = (scope / target).?.value.map(_.toPath)
val baseDir = (scope / baseDirectory).?.value.map(_.toPath)
targetDir.withFilter(_ => full).foreach(deleteContents(_, excludeFilter, view, delete))
(scope / cleanFiles).?.value.getOrElse(Nil).foreach { x =>
@ -123,8 +124,10 @@ private[sbt] object Clean {
val streamsGlobs =
(streamsKey.toSeq ++ stampsKey)
.map(k => manager(k).cacheDirectory.toPath.toGlob / **)
// Use baseDirectory instead of target so that file outputs outside the
// target directory but within the project root are also cleaned.
((scope / fileOutputs).value.filter { g =>
targetDir.fold(true)(g.base.startsWith)
baseDir.fold(true)(g.base.startsWith)
} ++ streamsGlobs)
.foreach { g =>
val filter: Path => Boolean = { path =>

View File

@ -1,6 +1,14 @@
# Test that managedSourcePaths / clean removes managed sources outside target
> compile
$ exists src_managed/demo/Test.scala
> Compile / managedSourcePaths
> Compile / managedSourcePaths / clean
$ absent src_managed/demo/Test.scala
# Test that clean also removes managed sources outside target
> compile
$ exists src_managed/demo/Test.scala
> clean
$ absent src_managed/demo/Test.scala