How to define directory structure following packages in project's Scala build definitions?

前端 未结 2 1864

There are two full build definition files in sbt project: Build.scala and Helpers.scala. They are located in project folder.

I

相关标签:
2条回答
  • 2021-01-14 12:29

    Sbt builds are recursive, which means that sbt build definition is built by sbt, applying the same rules as per normal project.

    Unlike Java, Scala has no strict relation between the package and folder structure. Meaning you can place your sources wherever you like and it doesn't have to match package declaration. Scala will not complain.

    Sbt knows where to search for folders by checking sourceDirectories setting key.

    You can check it easily by executing show sourceDirectories. However this will show the sourceDirectories for your actual project. How you can check it for the build? Quite easily, execute reload plugins, this will take you to your build. Execute show sourceDirectories, and it should show you that it looks for sources in /project/src/main/scala, project/src/main/java and one more, which is managed sources (doesn't matter for our case). Now you can execute reload return to go back to your main project.

    Given that you should be able to create an object let's say, named Helpers in project/src/main/scala/utils/Helpers.scala:

    package utils
    
    object Helpers {
      def printFancy(name: String) = println(s">>$name<<")
    }
    

    And use it in your Build.scala:

    import sbt._
    import Keys._
    
    import utils.Helpers._
    
    object MyBuild extends Build {
    
      val printProjectName = taskKey[Unit]("Prints fancy project name")
    
      lazy val root = project.in(file(".")).settings(
        printProjectName := printFancy(name.value)
      )
    
    }
    

    You can test it by executing printProjectName.

    > printProjectName
    >>root<<
    [success] Total time: 1 s, completed May 29, 2014 1:24:16 AM
    

    I've stated earlier that sbt is recursive. This means, that if you want, you can use the same technique to configure the sbt build, as you use for configuring building of your own project.

    If you don't want to keep your files under /project/src/main/scala, but just under /project/utils, you can do so by creating build.sbt in your project folder, with following content:

    unmanagedSourceDirectories in Compile += baseDirectory.value / "utils"
    

    Just as it is described in the documentation

    Now even if you place your utils in project/utils sbt should be able to find it.

    0 讨论(0)
  • you should use project/src/main/scala/utils instead of project/utils

    0 讨论(0)
提交回复
热议问题