PageRenderTime 29ms CodeModel.GetById 11ms app.highlight 13ms RepoModel.GetById 1ms app.codeStats 0ms

/framework/src/sbt-plugin/src/main/scala/PlaySettings.scala

http://github.com/playframework/Play20
Scala | 306 lines | 184 code | 94 blank | 28 comment | 2 complexity | 11ddb0d5e38721e081446c6d3a7b5e67 MD5 | raw file
  1/*
  2 * Copyright (C) 2009-2013 Typesafe Inc. <http://www.typesafe.com>
  3 */
  4package play
  5
  6import sbt.{ Project => SbtProject, _ }
  7import sbt.Keys._
  8import Keys._
  9import com.typesafe.sbt.SbtNativePackager._
 10import com.typesafe.sbt.packager.Keys._
 11import java.io.{ Writer, PrintWriter }
 12import play.console.Colors
 13
 14trait Settings {
 15  this: PlayCommands with PlayPositionMapper with PlayRun with PlaySourceGenerators =>
 16
 17  lazy val defaultJavaSettings = Seq[Setting[_]](
 18
 19    templatesImport ++= defaultJavaTemplatesImport,
 20
 21    routesImport ++= Seq(
 22      "play.libs.F"
 23    ),
 24
 25    ebeanEnabled := true
 26
 27  )
 28
 29  lazy val defaultScalaSettings = Seq[Setting[_]](
 30    templatesImport ++= defaultScalaTemplatesImport
 31  )
 32
 33  def closureCompilerSettings(optionCompilerOptions: com.google.javascript.jscomp.CompilerOptions) = Seq[Setting[_]](
 34    resourceGenerators in Compile <<= JavascriptCompiler(Some(optionCompilerOptions))(Seq(_)),
 35    resourceGenerators in Compile <+= LessCompiler,
 36    resourceGenerators in Compile <+= CoffeescriptCompiler
 37  )
 38
 39  /** Ask SBT to manage the classpath for the given configuration. */
 40  def manageClasspath(config: Configuration) = managedClasspath in config <<= (classpathTypes in config, update) map { (ct, report) =>
 41    Classpaths.managedJars(config, ct, report)
 42  }
 43
 44  lazy val defaultSettings = Seq[Setting[_]](
 45
 46    scalaVersion := play.core.PlayVersion.scalaVersion,
 47
 48    playPlugin := false,
 49
 50    resolvers ++= Seq(
 51      "Typesafe Releases Repository" at "http://repo.typesafe.com/typesafe/releases/"
 52    ),
 53
 54    target <<= baseDirectory / "target",
 55
 56    sourceDirectory in Compile <<= baseDirectory / "app",
 57    sourceDirectory in Test <<= baseDirectory / "test",
 58
 59    confDirectory <<= baseDirectory / "conf",
 60
 61    resourceDirectory in Compile <<= baseDirectory / "conf",
 62
 63    scalaSource in Compile <<= baseDirectory / "app",
 64    scalaSource in Test <<= baseDirectory / "test",
 65
 66    javaSource in Compile <<= baseDirectory / "app",
 67    javaSource in Test <<= baseDirectory / "test",
 68
 69    javacOptions in (Compile, doc) := List("-encoding", "utf8"),
 70
 71    libraryDependencies <+= (playPlugin) { isPlugin =>
 72      val d = "com.typesafe.play" %% "play" % play.core.PlayVersion.current
 73      if (isPlugin)
 74        d % "provided"
 75      else
 76        d
 77    },
 78    libraryDependencies += "com.typesafe.play" %% "play-test" % play.core.PlayVersion.current % "test",
 79
 80    ivyConfigurations += DocsApplication,
 81    libraryDependencies += "com.typesafe.play" %% "play-docs" % play.core.PlayVersion.current % DocsApplication.name,
 82    manageClasspath(DocsApplication),
 83
 84    parallelExecution in Test := false,
 85
 86    fork in Test := true,
 87
 88    testOptions in Test += Tests.Argument(TestFrameworks.Specs2, "sequential", "true", "junitxml", "console"),
 89
 90    testOptions in Test += Tests.Argument(TestFrameworks.JUnit, "--ignore-runners=org.specs2.runner.JUnitRunner"),
 91
 92    // Make sure Specs2 is at the end of the list of test frameworks, so that it gets priority over
 93    // JUnit. This is a hack/workaround to prevent Specs2 tests with @RunsWith annotations being
 94    // picked up by JUnit. We don't want JUnit to run the tests since JUnit ignores the Specs2
 95    // runnner, which means the tests run but their results are ignored by SBT.
 96    testFrameworks ~= { tf => tf.filter(_ != TestFrameworks.Specs2).:+(TestFrameworks.Specs2) },
 97
 98    testListeners <<= (target, streams).map((t, s) => Seq(new eu.henkelmann.sbt.JUnitXmlTestsListener(t.getAbsolutePath, s.log))),
 99
100    testResultReporter <<= testResultReporterTask,
101
102    testResultReporterReset <<= testResultReporterResetTask,
103
104    generateReverseRouter := true,
105
106    namespaceReverseRouter := false,
107
108    sourceGenerators in Compile <+= (state, confDirectory, sourceManaged in Compile, routesImport, generateReverseRouter, namespaceReverseRouter) map { (s, cd, sm, ri, grr, nrr) =>
109      RouteFiles(s, Seq(cd), sm, ri, grr, nrr)
110    },
111
112    // Adds config directory's source files to continuous hot reloading
113    watchSources <+= confDirectory map { all => all },
114
115    sourceGenerators in Compile <+= (state, unmanagedSourceDirectories in Compile, sourceManaged in Compile, templatesTypes, templatesImport, excludeFilter in unmanagedSources) map ScalaTemplates,
116
117    // Adds app directory's source files to continuous hot reloading
118    watchSources <++= baseDirectory map { path => ((path / "app") ** "*" --- (path / "app/assets") ** "*").get },
119
120    commands ++= Seq(shCommand, playCommand, playStartCommand, h2Command, classpathCommand, licenseCommand, computeDependenciesCommand),
121
122    // THE `in Compile` IS IMPORTANT!
123    run in Compile <<= playRunSetting,
124
125    shellPrompt := playPrompt,
126
127    copyResources in Compile <<= (copyResources in Compile, playCopyAssets) map { (r, pr) => r ++ pr },
128
129    mainClass in (Compile, run) := Some("play.core.server.NettyServer"),
130
131    compile in (Compile) <<= PostCompile(scope = Compile),
132
133    compile in Test <<= PostCompile(Test),
134
135    computeDependencies <<= computeDependenciesTask,
136
137    playVersion := play.core.PlayVersion.current,
138
139    // all dependencies from outside the project (all dependency jars)
140    playDependencyClasspath <<= externalDependencyClasspath in Runtime,
141
142    // all user classes, in this project and any other subprojects that it depends on
143    playReloaderClasspath <<= Classpaths.concatDistinct(exportedProducts in Runtime, internalDependencyClasspath in Runtime),
144
145    playCommonClassloader <<= playCommonClassloaderTask,
146
147    playDependencyClassLoader := createURLClassLoader,
148
149    playReloaderClassLoader := createDelegatedResourcesClassLoader,
150
151    playCopyAssets <<= playCopyAssetsTask,
152
153    playCompileEverything <<= playCompileEverythingTask,
154
155    playReload <<= playReloadTask,
156
157    sourcePositionMappers += playPositionMapper,
158
159    ivyLoggingLevel := UpdateLogging.DownloadOnly,
160
161    routesImport := Seq.empty[String],
162
163    playMonitoredFiles <<= playMonitoredFilesTask,
164
165    playDefaultPort := 9000,
166
167    // Default hooks
168
169    playOnStarted := Nil,
170
171    playOnStopped := Nil,
172
173    playRunHooks := Nil,
174
175    playRunHooks <++= playOnStarted map { funcs =>
176      funcs map play.PlayRunHook.makeRunHookFromOnStarted
177    },
178
179    playRunHooks <++= playOnStopped map { funcs =>
180      funcs map play.PlayRunHook.makeRunHookFromOnStopped
181    },
182
183    playInteractionMode := play.PlayConsoleInteractionMode,
184
185    // Assets
186
187    playAssetsDirectories := Seq.empty[File],
188
189    playExternalAssets := Seq.empty[(File, File => PathFinder, String)],
190
191    playAssetsDirectories <+= baseDirectory / "public",
192
193    requireJs := Nil,
194
195    requireJsFolder := "",
196
197    requireJsShim := "",
198
199    requireNativePath := None,
200
201    buildRequire <<= buildRequireTask,
202
203    packageBin in Compile <<= (packageBin in Compile).dependsOn(buildRequire),
204
205    resourceGenerators in Compile <+= LessCompiler,
206    resourceGenerators in Compile <+= CoffeescriptCompiler,
207    resourceGenerators in Compile <+= JavascriptCompiler(fullCompilerOptions = None),
208
209    lessEntryPoints <<= (sourceDirectory in Compile)(base => ((base / "assets" ** "*.less") --- base / "assets" ** "_*")),
210    coffeescriptEntryPoints <<= (sourceDirectory in Compile)(base => base / "assets" ** "*.coffee"),
211    javascriptEntryPoints <<= (sourceDirectory in Compile)(base => ((base / "assets" ** "*.js") --- (base / "assets" ** "_*"))),
212
213    lessOptions := Seq.empty[String],
214    coffeescriptOptions := Seq.empty[String],
215    closureCompilerOptions := Seq.empty[String],
216
217    // Settings
218
219    devSettings := Nil,
220
221    // Templates
222
223    templatesImport := defaultTemplatesImport,
224
225    templatesTypes := Map(
226      "html" -> "play.api.templates.HtmlFormat",
227      "txt" -> "play.api.templates.TxtFormat",
228      "xml" -> "play.api.templates.XmlFormat",
229      "js" -> "play.api.templates.JavaScriptFormat"
230    ),
231
232    // Native packaging
233
234    sourceDirectory in Universal <<= baseDirectory(_ / "dist"),
235
236    mainClass in Compile := Some("play.core.server.NettyServer"),
237
238    mappings in Universal <++= (confDirectory) map {
239      confDirectory: File =>
240        val confDirectoryLen = confDirectory.getCanonicalPath.length
241        val pathFinder = confDirectory ** ("*" -- "routes")
242        pathFinder.get map {
243          confFile: File =>
244            confFile -> ("conf/" + confFile.getCanonicalPath.substring(confDirectoryLen))
245        }
246    },
247
248    mappings in Universal <++= (doc in Compile) map {
249      docDirectory: File =>
250        val docDirectoryLen = docDirectory.getCanonicalPath.length
251        val pathFinder = docDirectory ** "*"
252        pathFinder.get map {
253          docFile: File =>
254            docFile -> ("share/doc/api/" + docFile.getCanonicalPath.substring(docDirectoryLen))
255        }
256    },
257
258    mappings in Universal <++= (baseDirectory) map {
259      baseDirectory: File =>
260        val pathFinder = baseDirectory * "README*"
261        pathFinder.get map {
262          readmeFile: File =>
263            readmeFile -> readmeFile.getName
264        }
265    },
266
267    // Adds the Play application directory to the command line args passed to Play
268    bashScriptExtraDefines += "addJava \"-Duser.dir=$(cd \"${app_home}/..\"; pwd -P)\"\n"
269
270  )
271
272  /**
273   * Add this to your build.sbt, eg:
274   *
275   * {{{
276   *   play.Project.emojiLogs
277   * }}}
278   *
279   * Note that this setting is not supported and may break or be removed or changed at any time.
280   */
281  lazy val emojiLogs = logManager ~= { lm =>
282    new LogManager {
283      def apply(data: sbt.Settings[Scope], state: State, task: Def.ScopedKey[_], writer: java.io.PrintWriter) = {
284        val l = lm.apply(data, state, task, writer)
285        val FailuresErrors = "(?s).*(\\d+) failures?, (\\d+) errors?.*".r
286        new Logger {
287          def filter(s: String) = {
288            val filtered = s.replace("\033[32m+\033[0m", "\u2705 ")
289              .replace("\033[33mx\033[0m", "\u274C ")
290              .replace("\033[31m!\033[0m", "\uD83D\uDCA5 ")
291            filtered match {
292              case FailuresErrors("0", "0") => filtered + " \uD83D\uDE04"
293              case FailuresErrors(_, _) => filtered + " \uD83D\uDE22"
294              case _ => filtered
295            }
296          }
297          def log(level: Level.Value, message: => String) = l.log(level, filter(message))
298          def success(message: => String) = l.success(message)
299          def trace(t: => Throwable) = l.trace(t)
300
301          override def ansiCodesSupported = l.ansiCodesSupported
302        }
303      }
304    }
305  }
306}