2

I have a multimodule web project with a dependency graph similar to this

WAR-project
- A1
-- A2
-- A3
- B1
-- B2
---- B22
-- B3

that is the war project depends on A1 which in turn depends on A2 and A3 and so on.

Now prior to the packageing of the war project I want to copy some web resources from its dependent projects into the webapp. So my question is how do I programmatically traverse a SBT project's dependency graph ? i.e. in pseudu code

resourcesToCopy = []
visitedProjects = []
traverseProjectDependencies(project) {
  visitedProjects += project
  if(project has resourceFolder) {
    resourcesToCopy += resourceFolder.getPath
  }
  for(projectDependency in project) {
    if(projectDependency is not visited) {
      traverseProjectDependencies(projectDependency)
    }
  }
}

Note I am aware that if I add the resource folder to the classpath of each of the dependencies then I could retrieve it from the fullClasspath in the web project. But I would like to avoid this solution and also there are other scenarios where programmatically traversing and interfacing with dependencies could be useful.

Lars Tackmann
  • 20,275
  • 13
  • 66
  • 83

1 Answers1

1

The following code adds a aggr-res task that will aggregate all resources for dependent projects:

val aggrRes= TaskKey[Seq[File]]("aggr-res", "show aggregate resources")

val aggrResTask = aggrRes in Compile <<= {
  (thisProjectRef, buildStructure) flatMap aggrResources(resources in Compile)
}

def aggrResources[T](key: ScopedTask[Seq[T]])(proj: ProjectRef, struct: Load.BuildStructure) = {
  val deps = collectDeps(_.dependencies.map(_.project))(proj, struct)
  deps.flatMap(key in (_, Compile) get struct.data).join.map(_.flatten)
}

def collectDeps(op: ResolvedProject => Seq[ProjectRef])(projRef: ProjectRef, struct: Load.BuildStructure): Seq[ProjectRef] = {
  val deps = Project.getProject(projRef, struct).toSeq.flatMap(op)
  deps.flatMap(ref => ref +: collectDeps(op)(ref, struct)).distinct
}

I have made a gist with a more complete example here

Lars Tackmann
  • 20,275
  • 13
  • 66
  • 83