[2.x] fix: Allow cleanFileOutputTask to delete files outside target directory

**Problem**
When sourceManaged or resourceManaged is set to a path outside the target
directory, neither clean nor managedSourcePaths/clean removes the generated
files. The cleanFileOutputTask has a hard guard that skips any file not
inside the target directory, even though these files are tracked via the
previous mechanism and were produced by the task itself.

**Solution**
Replace the targetDir guard in cleanFileOutputTask with a baseDirectory
guard. Files tracked by previous are task-produced outputs that are safe
to delete as long as they are within the project root. The
cleanKeepFiles/cleanKeepGlobs filter still applies for user-specified
exclusions.

Fixes #6895
This commit is contained in:
carlos4s 2026-04-10 00:27:29 +02:00
parent 7218b2a1ac
commit 0b4d57b893
3 changed files with 16 additions and 3 deletions

View File

@ -167,10 +167,9 @@ private[sbt] object Clean {
})
.flatMapTask { case scope =>
Def.task {
val targetDir = (scope / target).value.toPath
val baseDir = (scope / baseDirectory).value.toPath
val filter = cleanFilter(scope).value
// We do not want to inadvertently delete files that are not in the target directory.
val excludeFilter: Path => Boolean = path => !path.startsWith(targetDir) || filter(path)
val excludeFilter: Path => Boolean = path => !path.startsWith(baseDir) || filter(path)
val delete = cleanDelete(scope).value
val st = (scope / streams).value
taskKey.previous.foreach(_.toSeqPath.foreach(p => if (!excludeFilter(p)) delete(p)))

View File

@ -0,0 +1,8 @@
name := "clean-managed-outside-target"
scalaVersion := "3.3.1"
Compile / sourceManaged := baseDirectory.value / "src_managed"
Compile / sourceGenerators += Def.task {
val file = (Compile / sourceManaged).value / "demo" / "Test.scala"
IO.write(file, """object Test extends App { println("Hi") }""")
Seq(file)
}.taskValue

View File

@ -0,0 +1,6 @@
> compile
$ exists src_managed/demo/Test.scala
> Compile / managedSourcePaths
> Compile / managedSourcePaths / clean
$ absent src_managed/demo/Test.scala