-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathbuild.sbt
363 lines (313 loc) · 13 KB
/
build.sbt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
import org.nlogo.PlayScrapePlugin
import org.nlogo.PlayScrapePlugin.credentials.{ fromCredentialsProfile, fromEnvironmentVariables }
import com.typesafe.sbt.web.Import.WebKeys.webTarget
import com.typesafe.sbt.web.{ Compat, PathMapping }
import com.typesafe.sbt.web.pipeline.Pipeline
import sbt.io.Path.relativeTo
import sbt.IO
import java.nio.file.{ Files, StandardCopyOption }
import scala.sys.process.{ Process, ProcessLogger }
name := "Galapagos"
version := "1.0-SNAPSHOT"
scalaVersion := "2.12.17"
scalacOptions ++= Seq(
"-encoding", "UTF-8",
"-deprecation",
"-unchecked",
"-feature",
"-language:_",
// Scala 2.12.4 produces warnings for unused imports, but Play generates
// files as part of compilation that have unused imports, so we have to
// disable these warnings for now. -JMB July 2017
"-Xlint:-unused",
"-Ywarn-value-discard",
"-Xfatal-warnings"
)
lazy val root = (project in file("."))
.enablePlugins(PlayScala, PlayScrapePlugin)
.settings(
// Disable NPM node modules
Assets / JsEngineKeys.npmNodeModules := Nil,
TestAssets / JsEngineKeys.npmNodeModules := Nil
)
val tortoiseVersion = "1.0-be6b6e0"
resolvers ++= Seq(
"compilerjvm" at "https://dl.cloudsmith.io/public/netlogo/tortoise/maven/"
, "netlogowebjs" at "https://dl.cloudsmith.io/public/netlogo/tortoise/maven/"
, "netlogoheadless" at "https://dl.cloudsmith.io/public/netlogo/netlogo/maven/"
, "play-scraper" at "https://dl.cloudsmith.io/public/netlogo/play-scraper/maven/"
)
libraryDependencies ++= Seq(
ehcache
, filters
, guice
// these guice imports are temporary to support Java 17 with Play 2.8.16. They should be removed once a later version
// of Play properly references them. -Jeremy B September 2022
, "com.google.inject" % "guice" % "5.1.0"
, "com.google.inject.extensions" % "guice-assistedinject" % "5.1.0"
, "org.nlogo" % "compilerjvm" % tortoiseVersion
, "org.nlogo" % "netlogowebjs" % tortoiseVersion
// ideally these would be moved to `package.json`, but they aren't on npm at these exact versions, so here they stay.
// -Jeremy B September 2022
, "org.webjars" % "markdown-js" % "0.5.0-1"
, "org.webjars.bower" % "google-caja" % "6005.0.0"
// akka-testkit must match the akka version used by Play -Jeremy B September 2022
, "com.typesafe.akka" %% "akka-testkit" % "2.6.20" % Test
, "org.scalatestplus.play" %% "scalatestplus-play" % "5.1.0" % Test
)
evictionErrorLevel := Level.Warn
Assets / unmanagedResourceDirectories += baseDirectory.value / "node_modules"
// This is definitely not meant to be universal, just to get the info without the typical color codes -Jeremy B February
// 2023
def unAnsi(str: String): String =
str.replaceAll("\\u001B\\[\\d+m", "")
def runNpm(log: Logger, runDir: File, args: Seq[String], env: (String, String)*): Unit = {
val npmArgs = Seq("npm") ++ args
log.info(npmArgs.mkString(" "))
val output = new StringBuilder()
val writingLogger = ProcessLogger(
(out) => {
output.append(unAnsi(out))
output.append("\n")
log.info(out)
}
, (err) => {
output.append(unAnsi(err))
output.append("\n")
}
)
val result = Process(npmArgs, runDir, env:_*).!(writingLogger)
if (result != 0) {
throw new MessageOnlyException(s"npm command indicated an unsuccessful result.\n\n${output.toString}")
}
()
}
lazy val npmInstall = taskKey[Unit]("runs `npm install` if necessary based on current repo status")
npmInstall := {
val log = streams.value.log
val nodeDir = baseDirectory.value / "node_modules"
val nodeExists = nodeDir.exists && nodeDir.isDirectory && nodeDir.list.length > 0
val integrityFile = nodeDir / ".package-lock.json"
val packageJson = baseDirectory.value / "package.json"
if (!nodeExists || !integrityFile.exists || integrityFile.olderThan(packageJson)) {
runNpm(log, baseDirectory.value, Seq("install", "--ignore-optional"))
}
}
lazy val coffeeInputDirectory = Def.setting[File] { baseDirectory.value / "app" / "assets" / "javascripts" }
lazy val coffeeOutputDirectory = Def.setting[File] { baseDirectory.value / "target" / "coffee-output" / "main" }
lazy val coffee = taskKey[Unit]("compile coffeescript files")
coffee := Def.task {
val log = streams.value.log
val baseDir = baseDirectory.value
val coffeeInputDir = coffeeInputDirectory.value
val coffeeChangedDir = baseDirectory.value / "target" / "coffee-changed"
val coffeeOutputDir = coffeeOutputDirectory.value
val coffeeInputPath = coffeeInputDir.asPath
val coffeeChangedPath = coffeeChangedDir.asPath
val coffeeOutputPath = coffeeOutputDir.asPath
// get our file paths straight
val inOutFiles = (coffeeInputDir ** ("*.coffee")).get.map( (sourceFile) => {
val relativePath = coffeeInputPath.relativize(sourceFile.asPath)
val changedFile = coffeeChangedPath.resolve(relativePath).toFile
val fileName = sourceFile.getName.split("\\.").dropRight(1).mkString(".")
val relativeParent = relativePath.getParent
val outputParentPath = if (relativeParent == null) {
coffeeOutputPath
} else {
coffeeOutputPath.resolve(relativePath.getParent)
}
val outputFile = outputParentPath.resolve(s"$fileName.js").toFile
(sourceFile, changedFile, outputFile)
})
// get only the coffee files that have changed
val changedFiles = inOutFiles.filter({ case (sourceFile, _, outputFile) =>
!outputFile.exists || outputFile.olderThan(sourceFile)
})
// compile the coffee files if necessary.
if (changedFiles.length == 0) {
log.info("No changes found in CoffeeScript files.")
} else {
log.info(s"Compiling ${changedFiles.length} changed CoffeeScript file(s).")
// put the changed coffee files into a temp directory, so we can compile them while maintaining their relative paths.
IO.delete(coffeeChangedDir)
changedFiles.foreach({ case (sourceFile, changedFile, _) =>
Files.createDirectories(changedFile.getParentFile.asPath)
Files.copy(sourceFile.toPath, changedFile.toPath, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING)
})
runNpm(
log,
baseDir,
Seq("exec", "--", "coffee", "--compile", "--map", "--output", coffeeOutputPath.toString, coffeeChangedPath.toString)
)
}
// then copy all the non-coffee script files, too
(coffeeInputDir ** ("*.js")).get.foreach( (sourceFile) => {
val sourcePath = sourceFile.asPath
val outputPath = coffeeInputPath.relativize(sourcePath)
IO.copyFile(sourcePath.toFile, coffeeOutputPath.resolve(outputPath).toFile)
})
}.dependsOn(npmInstall).value
lazy val coffeelint = taskKey[Unit]("lint coffeescript files")
coffeelint := Def.task {
runNpm(
streams.value.log,
baseDirectory.value,
Seq("exec", "--", "coffeelint", "-f", "coffeelint.json", coffeeInputDirectory.value.toString)
)
}.dependsOn(npmInstall).value
lazy val testInputDirectory = Def.setting[File] { baseDirectory.value / "test" / "assets" / "javascripts" }
lazy val testOutputDirectory = Def.setting[File] { baseDirectory.value / "target" / "coffee-output" / "test" }
lazy val mochaTest = taskKey[Unit]("run mocha js tests")
mochaTest := Def.task {
val log = streams.value.log
log.info("Running mocha JS tests")
IO.delete(testOutputDirectory.value)
runNpm(
log,
baseDirectory.value,
Seq("exec", "--", "coffee", "--compile", "--map", "--output", testOutputDirectory.value.toString, testInputDirectory.value.toString)
)
runNpm(
log,
baseDirectory.value,
Seq("exec", "--", "mocha", "--recursive", s"${testOutputDirectory.value.toString}/**/*.js")
)
}.dependsOn(coffee).value
lazy val bundleDirectory = Def.setting[File] { baseDirectory.value / "target" / "rollup" }
lazy val bundle = taskKey[Pipeline.Stage]("full coffeescript build and bundle with rollup as pipeline")
bundle / includeFilter := "*.coffee" || "*.js"
bundle / excludeFilter := HiddenFileFilter
bundle := Def.task {
val streamsValue = streams.value
val baseDir = baseDirectory.value
val scriptsDir = "javascripts" + java.io.File.separator
val include = (bundle / includeFilter).value
val exclude = (bundle / excludeFilter).value
val coffeeOutputDir = coffeeOutputDirectory.value
val bundleDir = bundleDirectory.value.relativeTo(baseDir).get
val nodeEnv = if (PlayDevMode.isDevMode) "development" else "production"
(inputMappings: Seq[PathMapping]) => {
// Partition input mappings into files we want to bundle and files we just want to ignore and pass through to the
// next pipeline stage. - David D. 7/2021
val (outputMappings, ignoredFiles) = inputMappings.partition({
case (file, relativePath) =>
relativePath.startsWith(scriptsDir) && !file.isDirectory && !exclude.accept(file) && include.accept(file)
})
// Run the function only if files have changed since the last run - David D. 7/2021
val runBundler = FileFunction.cached(streamsValue.cacheDirectory / "rollup", FilesInfo.hash) { _ =>
IO.delete(bundleDir)
runNpm(
streamsValue.log,
baseDir,
Seq("exec", "--", "rollup", "--config", "rollup.config.js",
// Custom arguments with the 'config-' prefix are passed through to rollup.config.js. - David D. 7/2021
"--config-sourceDir", coffeeOutputDir.getPath,
"--config-targetDir", bundleDir.getPath,
// Rollup prints all messages, including info to STDERR, but SBT would then display everything as errors and
// clutter the output. The --silent flag causes Rollup to output only errors, which we still want to see.
// - David D. 7/2021
"--silent"
),
"NODE_ENV" -> nodeEnv
)
(bundleDir ** ("*.js" || "*.js.map")).get.toSet
}
val bundledFiles: Seq[PathMapping] = runBundler(outputMappings.map(_._1).toSet) pair relativeTo(bundleDir)
bundledFiles ++ ignoredFiles
}
}.dependsOn(coffee).value
(Compile / compile) := (Compile / compile).dependsOn(npmInstall).value
// Don't digest chunks, because they are `import`ed by filename in other script files. Besides, they already contain
// a digest in their filename anyway, so there is no need to do it twice.
// - David D. 7/2021
digest / excludeFilter := "*.chunk.js"
// We want to run the bundler in different modes in production and development. Unfortunately pipelineStages don't
// provide a way to run hooks only in development (`pipelineStages in Assets` are run in prod *and* dev). So we need to
// use a playRunHook to detect if we're in development mode (`sbt run`). - David D. 7/2021
PlayKeys.playRunHooks += PlayDevMode()
// Used in Dev and Prod
Assets / pipelineStages ++= Seq(bundle)
// Used in Prod
pipelineStages ++= Seq(digest)
Test / javaOptions ++= Seq(
"--add-exports=java.base/sun.security.x509=ALL-UNNAMED"
, "--add-opens=java.base/sun.security.ssl=ALL-UNNAMED"
)
Test / test := (Test / test).dependsOn(mochaTest).value
Test / fork := true
routesGenerator := InjectedRoutesGenerator
scrapeRoutes ++= Seq(
"/humans.txt",
"/docs/authoring",
"/docs/differences",
"/docs/faq",
"/docs/attributions",
"/whats-new",
"/model/list.json",
"/model/statuses.json",
"/netlogo-engine.js",
"/netlogo-agentmodel.js",
"/settings",
"/tortoise-compiler.js",
"/tortoise-compiler.js.map",
"/server-error",
"/not-found",
"/robots.txt",
"/standalone",
"/launch",
"/web",
"/nettango-builder",
"/nettango-library",
"/nettango-player",
"/nettango-player-standalone",
"/ntango-build",
"/ntango-play",
"/ntango-play-standalone"
)
scrapeDelay := 120
def isBuildServer: Boolean = !Option(System.getenv("BUILD_SERVER")).isEmpty
def buildBranch: String =
if (Option(System.getenv("CHANGE_TARGET")).isEmpty)
System.getenv("BUILD_BRANCH")
else
"PR-" + System.getenv("CHANGE_ID") + "-" + System.getenv("CHANGE_TARGET")
scrapePublishCredential := (Def.settingDyn {
if (isBuildServer)
Def.setting { fromEnvironmentVariables }
else
// Requires setting up a credentials profile, ask Robert for more details
Def.setting { fromCredentialsProfile("nlw-admin") }
}).value
scrapePublishBucketID := (Def.settingDyn {
val branchDeploy = Map(
"production" -> "netlogo-web-prod-content",
"master" -> "netlogo-web-staging-content",
"scrape-test" -> "netlogo-web-experiments-content/scrape-test"
)
if (isBuildServer)
Def.setting { branchDeploy.get(buildBranch) }
else
Def.setting { branchDeploy.get("production") }
}).value
scrapePublishDistributionID := (Def.settingDyn {
val branchPublish = Map(
"production" -> "E3AIHWIXSMPCAI",
"master" -> "E360I3EFLPUZR0",
"scrape-test" -> "E2TDYOH5TZH83M"
)
if (isBuildServer)
Def.setting { branchPublish.get(buildBranch) }
else
Def.setting { branchPublish.get("production") }
}).value
scrapeAbsoluteURL := (Def.settingDyn {
val branchURL = Map(
"production" -> "netlogoweb.org",
"master" -> "staging.netlogoweb.org",
"scrape-test" -> "experiments.netlogoweb.org/scrape-test"
)
if (isBuildServer)
Def.setting { branchURL.get(buildBranch) }
else
Def.setting { branchURL.get("production") }
}).value